From 50e990c64fa23ce94efa76b9e72df7f8ec3cee6a Mon Sep 17 00:00:00 2001 From: Scott Main Date: Thu, 21 Jun 2012 17:14:39 -0700 Subject: Massive clobber of all HTML files in developer docs for new site design Change-Id: Idc55a0b368c1d2c1e7d4999601b739dd57f08eb3 --- docs/html/about/about_toc.cs | 44 + docs/html/about/dashboards/index.jd | 235 ++ docs/html/about/flexible.jd | 34 + docs/html/about/index.jd | 157 ++ docs/html/about/marketplace.jd | 62 + docs/html/about/start.jd | 63 + docs/html/about/versions/android-1.1.jd | 246 ++ docs/html/about/versions/android-1.5-highlights.jd | 208 ++ docs/html/about/versions/android-1.5.jd | 375 ++++ docs/html/about/versions/android-1.6-highlights.jd | 213 ++ docs/html/about/versions/android-1.6.jd | 505 +++++ docs/html/about/versions/android-2.0-highlights.jd | 201 ++ docs/html/about/versions/android-2.0.1.jd | 361 +++ docs/html/about/versions/android-2.0.jd | 384 ++++ docs/html/about/versions/android-2.1.jd | 373 ++++ docs/html/about/versions/android-2.2-highlights.jd | 298 +++ docs/html/about/versions/android-2.2.jd | 252 +++ docs/html/about/versions/android-2.3-highlights.jd | 444 ++++ docs/html/about/versions/android-2.3.3.jd | 192 ++ docs/html/about/versions/android-2.3.4.jd | 148 ++ docs/html/about/versions/android-2.3.jd | 710 ++++++ docs/html/about/versions/android-3.0-highlights.jd | 261 +++ docs/html/about/versions/android-3.0.jd | 976 ++++++++ docs/html/about/versions/android-3.1-highlights.jd | 381 ++++ docs/html/about/versions/android-3.1.jd | 863 +++++++ docs/html/about/versions/android-3.2.jd | 556 +++++ docs/html/about/versions/android-4.0-highlights.jd | 1066 +++++++++ docs/html/about/versions/android-4.0.3.jd | 304 +++ docs/html/about/versions/android-4.0.jd | 1829 +++++++++++++++ docs/html/about/versions/api-levels.jd | 421 ++++ docs/html/about/versions/index.jd | 141 ++ docs/html/community/index.html | 10 - docs/html/design/building-blocks/index.jd | 2 +- docs/html/design/building-blocks/progress.jd | 1 - docs/html/design/design_toc.cs | 4 - docs/html/design/index.jd | 4 +- docs/html/design/media/typography_sizes.png | Bin 7361 -> 3923 bytes docs/html/design/patterns/index.jd | 2 +- docs/html/design/style/iconography.jd | 2 +- docs/html/design/style/index.jd | 2 +- docs/html/develop/index.jd | 366 +++ docs/html/distribute/distribute_toc.cs | 112 + .../distribute/googleplay/about/distribution.jd | 127 ++ .../html/distribute/googleplay/about/monetizing.jd | 152 ++ .../html/distribute/googleplay/about/visibility.jd | 247 ++ docs/html/distribute/googleplay/index.html | 10 + docs/html/distribute/googleplay/promote/badges.jd | 203 ++ docs/html/distribute/googleplay/promote/brand.jd | 174 ++ docs/html/distribute/googleplay/promote/index.jd | 43 + docs/html/distribute/googleplay/promote/linking.jd | 213 ++ .../distribute/googleplay/promote/product-pages.jd | 4 + docs/html/distribute/googleplay/publish/console.jd | 201 ++ docs/html/distribute/googleplay/publish/index.jd | 23 + .../distribute/googleplay/publish/preparing.jd | 570 +++++ .../html/distribute/googleplay/publish/register.jd | 72 + .../googleplay/strategies/app-quality.jd | 116 + .../distribute/googleplay/strategies/featuring.jd | 4 + .../html/distribute/googleplay/strategies/index.jd | 33 + docs/html/distribute/index.jd | 39 + docs/html/distribute/open.jd | 107 + docs/html/favicon-a.ico | Bin 0 -> 1150 bytes docs/html/favicon.ico | Bin 1150 -> 318 bytes docs/html/guide/appendix/api-levels.jd | 421 ---- docs/html/guide/appendix/g-app-intents.jd | 2 +- docs/html/guide/appendix/glossary.jd | 8 +- docs/html/guide/appendix/install-location.jd | 4 +- docs/html/guide/appendix/market-filters.jd | 454 ---- docs/html/guide/appendix/media-formats.jd | 6 +- docs/html/guide/basics/what-is-android.jd | 141 -- docs/html/guide/components/activities.jd | 776 +++++++ docs/html/guide/components/bound-services.jd | 675 ++++++ docs/html/guide/components/fragments.jd | 836 +++++++ docs/html/guide/components/fundamentals.jd | 518 +++++ docs/html/guide/components/index.jd | 56 + docs/html/guide/components/intents-filters.jd | 1055 +++++++++ docs/html/guide/components/loaders.jd | 500 +++++ .../html/guide/components/processes-and-threads.jd | 424 ++++ docs/html/guide/components/services.jd | 874 ++++++++ docs/html/guide/components/tasks-and-back-stack.jd | 595 +++++ .../guide/developing/building/building-cmdline.jd | 371 --- .../guide/developing/building/building-eclipse.jd | 165 -- docs/html/guide/developing/building/index.jd | 81 - docs/html/guide/developing/debug-tasks.html | 10 - docs/html/guide/developing/debugging/ddms.jd | 357 --- .../developing/debugging/debugging-devtools.jd | 85 - .../guide/developing/debugging/debugging-log.jd | 308 --- .../debugging/debugging-projects-cmdline.jd | 78 - .../developing/debugging/debugging-projects.jd | 67 - .../developing/debugging/debugging-tracing.jd | 402 ---- .../guide/developing/debugging/debugging-ui.jd | 547 ----- docs/html/guide/developing/debugging/index.jd | 188 -- docs/html/guide/developing/device.jd | 267 --- docs/html/guide/developing/devices/emulator.jd | 1571 ------------- docs/html/guide/developing/devices/index.jd | 78 - .../developing/devices/managing-avds-cmdline.jd | 369 --- .../html/guide/developing/devices/managing-avds.jd | 237 -- docs/html/guide/developing/eclipse-adt.html | 10 - docs/html/guide/developing/index.jd | 150 -- docs/html/guide/developing/other-ide.html | 10 - docs/html/guide/developing/projects/index.jd | 446 ---- .../guide/developing/projects/projects-cmdline.jd | 295 --- .../guide/developing/projects/projects-eclipse.jd | 237 -- docs/html/guide/developing/testing/index.jd | 36 - .../guide/developing/testing/testing_eclipse.jd | 535 ----- .../guide/developing/testing/testing_otheride.jd | 694 ------ docs/html/guide/developing/tools/MonkeyDevice.jd | 1355 ----------- docs/html/guide/developing/tools/MonkeyImage.jd | 437 ---- docs/html/guide/developing/tools/MonkeyRunner.jd | 448 ---- docs/html/guide/developing/tools/aapt.html | 10 - docs/html/guide/developing/tools/adb.jd | 669 ------ docs/html/guide/developing/tools/adt.jd | 527 ----- docs/html/guide/developing/tools/aidl.jd | 465 ---- docs/html/guide/developing/tools/android.jd | 393 ---- docs/html/guide/developing/tools/avd.html | 10 - docs/html/guide/developing/tools/bmgr.jd | 193 -- docs/html/guide/developing/tools/ddms.html | 10 - docs/html/guide/developing/tools/dmtracedump.jd | 66 - docs/html/guide/developing/tools/draw9patch.jd | 59 - docs/html/guide/developing/tools/emulator.jd | 581 ----- docs/html/guide/developing/tools/etc1tool.jd | 68 - .../guide/developing/tools/hierarchy-viewer.jd | 18 - docs/html/guide/developing/tools/hprof-conv.jd | 16 - docs/html/guide/developing/tools/index.jd | 85 - docs/html/guide/developing/tools/layoutopt.jd | 24 - docs/html/guide/developing/tools/logcat.jd | 106 - docs/html/guide/developing/tools/mksdcard.jd | 55 - docs/html/guide/developing/tools/monkey.jd | 242 -- .../developing/tools/monkeyrunner_concepts.jd | 319 --- docs/html/guide/developing/tools/othertools.html | 10 - docs/html/guide/developing/tools/proguard.jd | 189 -- docs/html/guide/developing/tools/sqlite3.jd | 59 - docs/html/guide/developing/tools/traceview.jd | 16 - docs/html/guide/developing/tools/zipalign.jd | 67 - docs/html/guide/google/index.jd | 97 + .../guide/google/play/billing/billing_about.html | 12 + .../guide/google/play/billing/billing_admin.jd | 530 +++++ .../google/play/billing/billing_best_practices.jd | 111 + .../guide/google/play/billing/billing_integrate.jd | 1100 +++++++++ .../guide/google/play/billing/billing_overview.jd | 507 +++++ .../guide/google/play/billing/billing_reference.jd | 491 ++++ .../google/play/billing/billing_subscriptions.jd | 859 +++++++ .../guide/google/play/billing/billing_testing.jd | 293 +++ docs/html/guide/google/play/billing/index.jd | 116 + docs/html/guide/google/play/expansion-files.jd | 1270 +++++++++++ docs/html/guide/google/play/filters.jd | 454 ++++ docs/html/guide/google/play/index.jd | 16 + .../google/play/licensing/adding-licensing.jd | 1071 +++++++++ docs/html/guide/google/play/licensing/index.jd | 61 + .../google/play/licensing/licensing-reference.jd | 439 ++++ docs/html/guide/google/play/licensing/overview.jd | 246 ++ .../html/guide/google/play/licensing/setting-up.jd | 701 ++++++ .../guide/google/play/publishing/multiple-apks.jd | 643 ++++++ docs/html/guide/guide_toc.cs | 1228 +++++----- docs/html/guide/index.jd | 140 +- docs/html/guide/market/billing/billing_about.html | 12 - docs/html/guide/market/billing/billing_admin.jd | 517 ----- .../guide/market/billing/billing_best_practices.jd | 111 - .../html/guide/market/billing/billing_integrate.jd | 1092 --------- docs/html/guide/market/billing/billing_overview.jd | 469 ---- .../html/guide/market/billing/billing_reference.jd | 418 ---- docs/html/guide/market/billing/billing_testing.jd | 293 --- docs/html/guide/market/billing/index.jd | 94 - docs/html/guide/market/expansion-files.jd | 1270 ----------- .../guide/market/licensing/adding-licensing.jd | 1072 --------- docs/html/guide/market/licensing/index.jd | 61 - .../guide/market/licensing/licensing-reference.jd | 439 ---- docs/html/guide/market/licensing/overview.jd | 246 -- docs/html/guide/market/licensing/setting-up.jd | 701 ------ docs/html/guide/market/publishing/multiple-apks.jd | 643 ------ .../guide/practices/app-design/accessibility.html | 11 + docs/html/guide/practices/app-design/index.jd | 21 + docs/html/guide/practices/app-design/jni.jd | 719 ++++++ .../html/guide/practices/app-design/performance.jd | 410 ++++ .../guide/practices/app-design/responsiveness.jd | 140 ++ .../guide/practices/app-design/seamlessness.jd | 249 +++ docs/html/guide/practices/compatibility.jd | 6 +- .../html/guide/practices/design/accessibility.html | 11 - docs/html/guide/practices/design/index.jd | 21 - docs/html/guide/practices/design/jni.jd | 719 ------ docs/html/guide/practices/design/performance.jd | 410 ---- docs/html/guide/practices/design/responsiveness.jd | 140 -- docs/html/guide/practices/design/seamlessness.jd | 249 --- docs/html/guide/practices/index.html | 8 - docs/html/guide/practices/index.jd | 52 + docs/html/guide/practices/jni.jd | 719 ++++++ docs/html/guide/practices/optimizing-for-3.0.jd | 26 +- docs/html/guide/practices/performance.jd | 410 ++++ docs/html/guide/practices/responsiveness.jd | 140 ++ docs/html/guide/practices/screens-distribution.jd | 2 +- docs/html/guide/practices/screens-support-1.5.jd | 2 +- docs/html/guide/practices/screens_support.jd | 6 +- docs/html/guide/practices/seamlessness.jd | 249 +++ docs/html/guide/practices/security.jd | 5 +- docs/html/guide/practices/tablets-and-handsets.jd | 12 +- .../ui_guidelines/activity_task_design.jd | 16 +- .../ui_guidelines/icon_design_launcher.jd | 4 +- .../ui_guidelines/icon_design_launcher_archive.jd | 2 +- .../guide/practices/ui_guidelines/widget_design.jd | 2 +- docs/html/guide/publishing/app-signing.jd | 618 ----- docs/html/guide/publishing/licensing.html | 11 - docs/html/guide/publishing/preparing.jd | 358 --- docs/html/guide/publishing/publishing.jd | 703 ------ docs/html/guide/publishing/publishing_overview.jd | 231 -- docs/html/guide/publishing/versioning.jd | 174 -- docs/html/guide/topics/admin/index.jd | 22 + docs/html/guide/topics/admin/keychain.jd | 4 + docs/html/guide/topics/appwidgets/index.jd | 4 +- docs/html/guide/topics/clipboard/copy-paste.jd | 1094 --------- docs/html/guide/topics/connectivity/bluetooth.jd | 1086 +++++++++ docs/html/guide/topics/connectivity/index.jd | 42 + .../guide/topics/connectivity/nfc/advanced-nfc.jd | 300 +++ docs/html/guide/topics/connectivity/nfc/index.jd | 33 + docs/html/guide/topics/connectivity/nfc/nfc.jd | 923 ++++++++ docs/html/guide/topics/connectivity/sip.jd | 490 ++++ .../guide/topics/connectivity/usb/accessory.jd | 462 ++++ docs/html/guide/topics/connectivity/usb/adk.jd | 909 ++++++++ docs/html/guide/topics/connectivity/usb/host.jd | 440 ++++ docs/html/guide/topics/connectivity/usb/index.jd | 67 + docs/html/guide/topics/connectivity/wifip2p.jd | 611 +++++ docs/html/guide/topics/data/backup.jd | 12 +- docs/html/guide/topics/data/data-storage.jd | 23 +- docs/html/guide/topics/data/index.html | 9 - docs/html/guide/topics/data/index.jd | 23 + docs/html/guide/topics/data/install-location.jd | 206 ++ docs/html/guide/topics/drawing/index.html | 9 - docs/html/guide/topics/drawing/opengl.jd | 53 - docs/html/guide/topics/fundamentals.jd | 518 ----- docs/html/guide/topics/fundamentals/activities.jd | 777 ------- .../guide/topics/fundamentals/bound-services.jd | 675 ------ docs/html/guide/topics/fundamentals/fragments.jd | 836 ------- docs/html/guide/topics/fundamentals/loaders.jd | 500 ----- .../topics/fundamentals/processes-and-threads.jd | 486 ---- docs/html/guide/topics/fundamentals/services.jd | 874 -------- .../topics/fundamentals/tasks-and-back-stack.jd | 596 ----- docs/html/guide/topics/graphics/2d-graphics.jd | 2 +- docs/html/guide/topics/graphics/animation.jd | 64 - docs/html/guide/topics/graphics/index.jd | 90 +- docs/html/guide/topics/graphics/opengl.jd | 52 +- docs/html/guide/topics/graphics/overview.jd | 73 + docs/html/guide/topics/graphics/prop-animation.jd | 25 + .../guide/topics/graphics/renderscript/compute.jd | 253 +++ .../guide/topics/graphics/renderscript/graphics.jd | 994 ++++++++ .../guide/topics/graphics/renderscript/index.jd | 804 +++++++ .../topics/graphics/renderscript/reference.jd | 18 + docs/html/guide/topics/intents/index.html | 9 - docs/html/guide/topics/intents/intents-filters.jd | 1055 --------- docs/html/guide/topics/location/index.jd | 10 +- .../topics/location/obtaining-user-location.jd | 454 ---- docs/html/guide/topics/location/strategies.jd | 454 ++++ docs/html/guide/topics/manifest/action-element.jd | 2 +- .../html/guide/topics/manifest/activity-element.jd | 2 +- .../html/guide/topics/manifest/category-element.jd | 2 +- .../topics/manifest/compatible-screens-element.jd | 4 +- docs/html/guide/topics/manifest/data-element.jd | 2 +- .../guide/topics/manifest/intent-filter-element.jd | 2 +- .../html/guide/topics/manifest/manifest-element.jd | 2 +- docs/html/guide/topics/manifest/manifest-intro.jd | 2 +- .../topics/manifest/supports-gl-texture-element.jd | 2 +- .../guide/topics/manifest/uses-feature-element.jd | 4 +- .../guide/topics/manifest/uses-library-element.jd | 2 +- .../html/guide/topics/manifest/uses-sdk-element.jd | 430 +++- docs/html/guide/topics/media/camera.jd | 3 +- docs/html/guide/topics/media/index.jd | 115 +- docs/html/guide/topics/media/mediaplayer.jd | 2 +- docs/html/guide/topics/network/sip.jd | 490 ---- docs/html/guide/topics/nfc/advanced-nfc.jd | 300 --- docs/html/guide/topics/nfc/index.jd | 33 - docs/html/guide/topics/nfc/nfc.jd | 923 -------- .../guide/topics/providers/calendar-provider.jd | 49 +- .../guide/topics/providers/contacts-provider.jd | 2361 ++++++++++++++++++++ .../topics/providers/content-provider-basics.jd | 4 +- .../topics/providers/content-provider-creating.jd | 4 +- .../guide/topics/providers/content-providers.jd | 14 + docs/html/guide/topics/renderscript/compute.jd | 253 --- docs/html/guide/topics/renderscript/graphics.jd | 993 -------- docs/html/guide/topics/renderscript/index.jd | 804 ------- docs/html/guide/topics/renderscript/reference.jd | 18 - .../guide/topics/resources/animation-resource.jd | 4 +- docs/html/guide/topics/resources/index.jd | 154 +- .../html/guide/topics/resources/layout-resource.jd | 6 +- docs/html/guide/topics/resources/localization.jd | 29 +- docs/html/guide/topics/resources/menu-resource.jd | 11 +- docs/html/guide/topics/resources/overview.jd | 103 + .../guide/topics/resources/providing-resources.jd | 8 +- .../html/guide/topics/resources/runtime-changes.jd | 4 +- docs/html/guide/topics/search/index.jd | 2 +- docs/html/guide/topics/search/search-dialog.jd | 2 +- docs/html/guide/topics/security/index.jd | 65 + docs/html/guide/topics/security/permissions.jd | 407 ++++ docs/html/guide/topics/security/security.jd | 1155 ++++++---- docs/html/guide/topics/sensors/index.jd | 118 +- docs/html/guide/topics/sensors/sensors_overview.jd | 38 +- docs/html/guide/topics/testing/activity_testing.jd | 394 ---- .../topics/testing/contentprovider_testing.jd | 225 -- docs/html/guide/topics/testing/index.jd | 86 - docs/html/guide/topics/testing/service_testing.jd | 180 -- docs/html/guide/topics/testing/testing_android.jd | 666 ------ docs/html/guide/topics/testing/what_to_test.jd | 86 - docs/html/guide/topics/text/copy-paste.jd | 1094 +++++++++ .../guide/topics/text/creating-input-method.jd | 528 +++++ docs/html/guide/topics/text/index.jd | 40 + .../guide/topics/text/spell-checker-framework.jd | 236 ++ docs/html/guide/topics/ui/accessibility/apps.jd | 8 +- docs/html/guide/topics/ui/accessibility/index.jd | 4 +- .../html/guide/topics/ui/accessibility/services.jd | 4 +- docs/html/guide/topics/ui/actionbar.jd | 19 +- docs/html/guide/topics/ui/binding.jd | 27 +- docs/html/guide/topics/ui/controls.jd | 92 + docs/html/guide/topics/ui/controls/button.jd | 245 ++ docs/html/guide/topics/ui/controls/checkbox.jd | 101 + docs/html/guide/topics/ui/controls/pickers.jd | 259 +++ docs/html/guide/topics/ui/controls/radiobutton.jd | 103 + docs/html/guide/topics/ui/controls/spinner.jd | 147 ++ docs/html/guide/topics/ui/controls/text.jd | 306 +++ docs/html/guide/topics/ui/controls/togglebutton.jd | 124 + docs/html/guide/topics/ui/declaring-layout.jd | 249 ++- docs/html/guide/topics/ui/dialogs.jd | 2 +- .../guide/topics/ui/images/android_focused.png | Bin 0 -> 2785 bytes .../html/guide/topics/ui/images/android_normal.png | Bin 0 -> 2056 bytes .../guide/topics/ui/images/android_pressed.png | Bin 0 -> 2337 bytes docs/html/guide/topics/ui/images/hello-gallery.png | Bin 0 -> 5593 bytes .../html/guide/topics/ui/images/hello-gridview.png | Bin 0 -> 21768 bytes .../guide/topics/ui/images/hello-linearlayout.png | Bin 0 -> 4207 bytes .../html/guide/topics/ui/images/hello-listview.png | Bin 0 -> 26359 bytes docs/html/guide/topics/ui/images/hello-mapview.png | Bin 0 -> 50499 bytes .../topics/ui/images/hello-relativelayout.png | Bin 0 -> 2399 bytes .../guide/topics/ui/images/hello-tablelayout.png | Bin 0 -> 3446 bytes .../guide/topics/ui/images/hello-tabwidget.png | Bin 0 -> 10393 bytes docs/html/guide/topics/ui/images/hello-webview.png | Bin 0 -> 16490 bytes .../guide/topics/ui/images/ic_tab_artists_grey.png | Bin 0 -> 791 bytes .../topics/ui/images/ic_tab_artists_white.png | Bin 0 -> 1127 bytes docs/html/guide/topics/ui/index.jd | 285 +-- docs/html/guide/topics/ui/layout-objects.jd | 289 +-- docs/html/guide/topics/ui/layout/grid.jd | 187 ++ docs/html/guide/topics/ui/layout/gridview.jd | 191 ++ docs/html/guide/topics/ui/layout/linear.jd | 116 + docs/html/guide/topics/ui/layout/listview.jd | 151 ++ docs/html/guide/topics/ui/layout/relative.jd | 118 + docs/html/guide/topics/ui/layout/tabs.jd | 219 ++ docs/html/guide/topics/ui/menus.jd | 2 +- docs/html/guide/topics/ui/notifiers/index.jd | 10 +- .../guide/topics/ui/notifiers/notifications.jd | 32 +- docs/html/guide/topics/ui/overview.jd | 74 + .../guide/topics/ui/sharables/sample_images.zip | Bin 0 -> 254816 bytes docs/html/guide/topics/usb/accessory.jd | 462 ---- docs/html/guide/topics/usb/adk.jd | 916 -------- docs/html/guide/topics/usb/host.jd | 440 ---- docs/html/guide/topics/usb/index.jd | 67 - docs/html/guide/topics/views/custom-views.jd | 544 ----- docs/html/guide/topics/views/intro.jd | 49 - docs/html/guide/topics/views/ui-xml.jd | 138 -- docs/html/guide/topics/wireless/bluetooth.jd | 1086 --------- docs/html/guide/topics/wireless/index.jd | 23 - docs/html/guide/topics/wireless/wifi.jd | 18 - docs/html/guide/topics/wireless/wifip2p.jd | 611 ----- docs/html/guide/tutorials/hello-world.html | 10 - docs/html/guide/tutorials/images/hello_world_0.png | Bin 6328 -> 0 bytes docs/html/guide/tutorials/images/hello_world_1.png | Bin 10031 -> 0 bytes docs/html/guide/tutorials/images/hello_world_2.png | Bin 11040 -> 0 bytes docs/html/guide/tutorials/images/hello_world_3.png | Bin 11000 -> 0 bytes docs/html/guide/tutorials/images/hello_world_4.png | Bin 61711 -> 0 bytes docs/html/guide/tutorials/images/hello_world_5.png | Bin 6244 -> 0 bytes docs/html/guide/tutorials/images/hello_world_8.png | Bin 10993 -> 0 bytes docs/html/guide/tutorials/images/hello_world_9.png | Bin 6791 -> 0 bytes docs/html/guide/tutorials/index.html | 10 - docs/html/guide/tutorials/localization/index.html | 10 - .../tutorials/notepad/codelab/NotepadCodeLab.zip | Bin 90916 -> 0 bytes docs/html/guide/tutorials/notepad/index.html | 10 - docs/html/guide/tutorials/notepad/notepad-ex1.jd | 582 ----- docs/html/guide/tutorials/notepad/notepad-ex2.jd | 642 ------ docs/html/guide/tutorials/notepad/notepad-ex3.jd | 366 --- .../tutorials/notepad/notepad-extra-credit.jd | 70 - docs/html/guide/tutorials/notepad/notepad-index.jd | 143 -- .../guide/tutorials/views/hello-autocomplete.jd | 116 - .../html/guide/tutorials/views/hello-datepicker.jd | 151 -- docs/html/guide/tutorials/views/hello-formstuff.jd | 262 --- docs/html/guide/tutorials/views/hello-gallery.jd | 135 -- docs/html/guide/tutorials/views/hello-gridview.jd | 129 -- .../guide/tutorials/views/hello-linearlayout.jd | 130 -- docs/html/guide/tutorials/views/hello-listview.jd | 90 - docs/html/guide/tutorials/views/hello-mapview.jd | 245 -- .../guide/tutorials/views/hello-relativelayout.jd | 75 - docs/html/guide/tutorials/views/hello-spinner.jd | 106 - .../guide/tutorials/views/hello-tablelayout.jd | 118 - docs/html/guide/tutorials/views/hello-tabwidget.jd | 124 - .../html/guide/tutorials/views/hello-timepicker.jd | 159 -- docs/html/guide/tutorials/views/hello-webview.jd | 118 - docs/html/guide/tutorials/views/images/android.png | Bin 693 -> 0 bytes .../guide/tutorials/views/images/androidmarker.png | Bin 702 -> 0 bytes .../tutorials/views/images/hello-autocomplete.png | Bin 4601 -> 0 bytes .../tutorials/views/images/hello-datepicker.png | Bin 7322 -> 0 bytes .../tutorials/views/images/hello-formstuff.png | Bin 4258 -> 0 bytes .../guide/tutorials/views/images/hello-gallery.png | Bin 5593 -> 0 bytes .../tutorials/views/images/hello-gridview.png | Bin 21768 -> 0 bytes .../tutorials/views/images/hello-linearlayout.png | Bin 4207 -> 0 bytes .../tutorials/views/images/hello-listview.png | Bin 6926 -> 0 bytes .../guide/tutorials/views/images/hello-mapview.png | Bin 16922 -> 0 bytes .../views/images/hello-relativelayout.png | Bin 2399 -> 0 bytes .../guide/tutorials/views/images/hello-spinner.png | Bin 2513 -> 0 bytes .../tutorials/views/images/hello-tablelayout.png | Bin 3446 -> 0 bytes .../tutorials/views/images/hello-tabwidget.png | Bin 2117 -> 0 bytes .../tutorials/views/images/hello-timepicker.png | Bin 5644 -> 0 bytes .../guide/tutorials/views/images/hello-webview.png | Bin 5874 -> 0 bytes docs/html/guide/tutorials/views/index.html | 10 - docs/html/guide/webapps/debugging.jd | 6 +- docs/html/guide/webapps/index.jd | 77 +- docs/html/guide/webapps/overview.jd | 71 + docs/html/images/about/growth-chart.png | Bin 0 -> 147154 bytes docs/html/images/activity_fragment_lifecycle.png | Bin 47065 -> 43463 bytes docs/html/images/activity_lifecycle.png | Bin 81796 -> 82637 bytes docs/html/images/android-logo.png | Bin 0 -> 2793 bytes docs/html/images/billing_subscription_flow.png | Bin 0 -> 56972 bytes .../brand/android_app_on_play_logo_large.png | Bin 0 -> 4095 bytes .../brand/android_app_on_play_logo_small.png | Bin 0 -> 2891 bytes docs/html/images/brand/droid.gif | Bin 0 -> 6371 bytes .../images/brand/get_it_on_play_logo_large.png | Bin 0 -> 3995 bytes .../images/brand/get_it_on_play_logo_small.png | Bin 0 -> 2752 bytes docs/html/images/brand/google_play_logo_450.png | Bin 0 -> 5910 bytes docs/html/images/brand/learnmore.gif | Bin 0 -> 3300 bytes docs/html/images/brand/logo_android.gif | Bin 0 -> 1034 bytes docs/html/images/brand/mediaplayer.gif | Bin 0 -> 5816 bytes docs/html/images/brand/norad.gif | Bin 0 -> 889 bytes docs/html/images/dac-design-icon.png | Bin 0 -> 4237 bytes docs/html/images/debugging-tall.png | Bin 0 -> 149662 bytes docs/html/images/develop-placeholder.png | Bin 0 -> 26860 bytes docs/html/images/develop/app_components.png | Bin 0 -> 112736 bytes docs/html/images/develop/auth-code.png | Bin 0 -> 16105 bytes docs/html/images/develop/connectivity.png | Bin 0 -> 99713 bytes docs/html/images/develop/marquee-play.png | Bin 0 -> 57091 bytes docs/html/images/develop/resources.png | Bin 0 -> 57422 bytes docs/html/images/distribute/feature-market.png | Bin 0 -> 3964 bytes docs/html/images/distribute/feature-monetize.png | Bin 0 -> 8039 bytes docs/html/images/distribute/feature-register.png | Bin 0 -> 4459 bytes docs/html/images/distribute/marquee-play.png | Bin 0 -> 113586 bytes docs/html/images/editorschoice_ann.png | Bin 0 -> 187 bytes docs/html/images/fragment_lifecycle.png | Bin 74551 -> 75783 bytes .../html/images/fundamentals/diagram_backstack.png | Bin 42790 -> 42966 bytes .../diagram_backstack_singletask_multiactivity.png | Bin 57883 -> 59073 bytes .../fundamentals/diagram_multiple_instances.png | Bin 24344 -> 23644 bytes .../images/fundamentals/diagram_multitasking.png | Bin 24646 -> 25030 bytes docs/html/images/fundamentals/fragments.png | Bin 37486 -> 49465 bytes docs/html/images/fundamentals/restore_instance.png | Bin 73436 -> 73704 bytes .../service_binding_tree_lifecycle.png | Bin 76028 -> 80443 bytes docs/html/images/gp-apps-home.png | Bin 0 -> 254308 bytes docs/html/images/gp-buyer-currency.png | Bin 0 -> 37422 bytes docs/html/images/gp-collectibles.png | Bin 0 -> 61717 bytes docs/html/images/gp-dc-countries.png | Bin 0 -> 32900 bytes docs/html/images/gp-dc-details.png | Bin 0 -> 254690 bytes docs/html/images/gp-dc-home.png | Bin 0 -> 58768 bytes docs/html/images/gp-dc-profile.png | Bin 0 -> 55143 bytes docs/html/images/gp-dc-reviews.png | Bin 0 -> 79404 bytes docs/html/images/gp-dc-stats-mini.png | Bin 0 -> 69890 bytes docs/html/images/gp-dc-stats.png | Bin 0 -> 128669 bytes docs/html/images/gp-details-pages-magicpiano.png | Bin 0 -> 363318 bytes docs/html/images/gp-details-ww-purchase.png | Bin 0 -> 59564 bytes docs/html/images/gp-details-ww.png | Bin 0 -> 123069 bytes docs/html/images/gp-devconsole-home.png | Bin 0 -> 141513 bytes docs/html/images/gp-device.png | Bin 0 -> 138914 bytes docs/html/images/gp-games-home.png | Bin 0 -> 88720 bytes docs/html/images/gp-growth-downloads.png | Bin 0 -> 39580 bytes docs/html/images/gp-rating-web.png | Bin 0 -> 58423 bytes docs/html/images/gp-sendto.png | Bin 0 -> 48342 bytes docs/html/images/gp-subs.png | Bin 0 -> 48429 bytes docs/html/images/gp-supported-dev-requirements.png | Bin 0 -> 21130 bytes docs/html/images/gp-tab.png | Bin 0 -> 100677 bytes docs/html/images/gp-top-new-paid.png | Bin 0 -> 79187 bytes docs/html/images/gpp-cat-feature280-photo.png | Bin 0 -> 254786 bytes docs/html/images/gpp-cat-feature280-puzzle.png | Bin 0 -> 217985 bytes docs/html/images/gpp-cat-feature280-sports.png | Bin 0 -> 170856 bytes docs/html/images/home-marquee.jpg | Bin 0 -> 25416 bytes docs/html/images/home/design.png | Bin 0 -> 201003 bytes docs/html/images/home/developers_live.png | Bin 0 -> 238375 bytes docs/html/images/home/google-io.png | Bin 0 -> 611444 bytes docs/html/images/home/google-play.png | Bin 0 -> 250345 bytes docs/html/images/home/ics-android.png | Bin 0 -> 82115 bytes docs/html/images/layoutparams.png | Bin 61601 -> 61909 bytes docs/html/images/market/version-codes.png | Bin 20098 -> 20789 bytes docs/html/images/opengl/ccw-square.png | Bin 0 -> 15301 bytes docs/html/images/opengl/ccw-winding.png | Bin 0 -> 17960 bytes docs/html/images/opengl/coordinates.png | Bin 14019 -> 19368 bytes docs/html/images/opengl/helloopengl-es10-1.png | Bin 8448 -> 0 bytes docs/html/images/opengl/helloopengl-es10-2.png | Bin 7259 -> 0 bytes docs/html/images/opengl/helloopengl-es20-1.png | Bin 6935 -> 0 bytes docs/html/images/opengl/helloopengl-es20-2.png | Bin 6833 -> 0 bytes docs/html/images/opengl/ogl-triangle-projected.png | Bin 0 -> 12765 bytes docs/html/images/opengl/ogl-triangle-touch.png | Bin 0 -> 14560 bytes docs/html/images/opengl/ogl-triangle.png | Bin 0 -> 12302 bytes docs/html/images/play_tableft.png | Bin 0 -> 475930 bytes docs/html/images/providers/ContactsDataFlow.png | Bin 0 -> 38071 bytes docs/html/images/providers/contacts_structure.png | Bin 0 -> 18777 bytes docs/html/images/providers/contacts_tables.png | Bin 0 -> 57257 bytes docs/html/images/providers/data_columns.png | Bin 0 -> 22128 bytes .../publishing/publishing_unknown_sources.png | Bin 49351 -> 0 bytes .../publishing/publishing_unknown_sources_sm.png | Bin 0 -> 9836 bytes .../images/publishing/publishing_via_email.png | Bin 53620 -> 47608 bytes .../images/resources/res-selection-flowchart.png | Bin 75022 -> 76558 bytes .../images/resources/resource_devices_diagram1.png | Bin 19175 -> 22141 bytes .../images/resources/resource_devices_diagram2.png | Bin 19956 -> 22429 bytes docs/html/images/robot-sdk.png | Bin 0 -> 98477 bytes docs/html/images/robot-tiny.png | Bin 0 -> 454 bytes .../images/screens_support/screens-densities.png | Bin 16219 -> 19640 bytes .../html/images/screens_support/screens-ranges.png | Bin 22143 -> 22609 bytes docs/html/images/sdk-cube.png | Bin 0 -> 90911 bytes docs/html/images/service_lifecycle.png | Bin 74708 -> 75061 bytes docs/html/images/tools-home.png | Bin 0 -> 190613 bytes docs/html/images/topdev_ann.png | Bin 0 -> 264 bytes .../training/basics/basic-lifecycle-create.png | Bin 70470 -> 78949 bytes .../training/basics/basic-lifecycle-paused.png | Bin 67399 -> 75348 bytes .../training/basics/basic-lifecycle-savestate.png | Bin 49135 -> 51430 bytes .../training/basics/basic-lifecycle-stopped.png | Bin 71327 -> 79764 bytes .../images/training/basics/basic-lifecycle.png | Bin 62632 -> 69368 bytes .../images/training/basics/network-settings1.png | Bin 0 -> 21155 bytes .../images/training/basics/network-settings2.png | Bin 0 -> 24700 bytes docs/html/images/ui/button-types.png | Bin 0 -> 2997 bytes docs/html/images/ui/buttons-holo.png | Bin 0 -> 6400 bytes docs/html/images/ui/checkboxes.png | Bin 0 -> 29858 bytes docs/html/images/ui/edittext-actionlabel.png | Bin 0 -> 14345 bytes docs/html/images/ui/edittext-actionsend.png | Bin 0 -> 4340 bytes docs/html/images/ui/edittext-autocomplete.png | Bin 0 -> 18252 bytes docs/html/images/ui/edittext-email.png | Bin 0 -> 22098 bytes docs/html/images/ui/edittext-noextract.png | Bin 0 -> 26788 bytes docs/html/images/ui/edittext-phone.png | Bin 0 -> 22308 bytes docs/html/images/ui/edittext-text-next.png | Bin 0 -> 21739 bytes docs/html/images/ui/edittext-text.png | Bin 0 -> 25358 bytes docs/html/images/ui/edittext.png | Bin 0 -> 2367 bytes docs/html/images/ui/gridlayout-small.png | Bin 0 -> 21912 bytes docs/html/images/ui/gridlayout.png | Bin 0 -> 70249 bytes docs/html/images/ui/gridview-small.png | Bin 0 -> 20625 bytes docs/html/images/ui/gridview.png | Bin 0 -> 64565 bytes docs/html/images/ui/linearlayout-small.png | Bin 0 -> 20967 bytes docs/html/images/ui/linearlayout.png | Bin 0 -> 67936 bytes docs/html/images/ui/listview-small.png | Bin 0 -> 18055 bytes docs/html/images/ui/listview.png | Bin 0 -> 57993 bytes docs/html/images/ui/pickers.png | Bin 0 -> 39836 bytes docs/html/images/ui/radiobuttons.png | Bin 0 -> 10610 bytes docs/html/images/ui/relativelayout-small.png | Bin 0 -> 20777 bytes docs/html/images/ui/relativelayout.png | Bin 0 -> 67073 bytes docs/html/images/ui/sample-linearlayout.png | Bin 0 -> 12918 bytes docs/html/images/ui/sample-relativelayout.png | Bin 0 -> 15231 bytes docs/html/images/ui/spinner.png | Bin 0 -> 4738 bytes docs/html/images/ui/switch.png | Bin 0 -> 7702 bytes docs/html/images/ui/tabs-small.png | Bin 0 -> 22887 bytes docs/html/images/ui/tabs.png | Bin 0 -> 73947 bytes docs/html/images/ui/togglebutton.png | Bin 0 -> 5830 bytes docs/html/images/ui/ui-controls.png | Bin 0 -> 17888 bytes docs/html/images/ui/ui_index.png | Bin 0 -> 50178 bytes docs/html/images/ui/webview-small.png | Bin 0 -> 25681 bytes docs/html/images/ui/webview.png | Bin 0 -> 79862 bytes docs/html/images/viewgroup.png | Bin 24973 -> 25722 bytes docs/html/images/webapps/webapps.png | Bin 35420 -> 38655 bytes docs/html/index.jd | 272 +-- .../monitoring-device-state/battery-monitoring.jd | 120 + .../connectivity-monitoring.jd | 70 + .../monitoring-device-state/docking-monitoring.jd | 74 + .../es/training/monitoring-device-state/index.jd | 49 + .../monitoring-device-state/manifest-receivers.jd | 50 + docs/html/intl/es/training/multiscreen/adaptui.jd | 212 ++ docs/html/intl/es/training/multiscreen/index.jd | 63 + .../es/training/multiscreen/screendensities.jd | 100 + .../intl/es/training/multiscreen/screensizes.jd | 279 +++ docs/html/intl/ja/guide/developing/eclipse-adt.jd | 14 +- docs/html/intl/ja/guide/developing/other-ide.jd | 30 +- docs/html/intl/ja/guide/index.jd | 4 +- docs/html/intl/ja/guide/publishing/app-signing.jd | 4 +- docs/html/intl/ja/guide/publishing/preparing.jd | 14 +- docs/html/intl/ja/guide/publishing/versioning.jd | 6 +- docs/html/intl/ja/guide/topics/fundamentals.jd | 10 +- docs/html/intl/ja/guide/tutorials/hello-world.jd | 8 +- docs/html/intl/ja/index.jd | 2 +- .../intl/ja/resources/tutorials/hello-world.jd | 8 +- docs/html/intl/ja/sdk/1.5_r2/installing.jd | 8 +- docs/html/intl/ja/sdk/1.5_r3/installing.jd | 8 +- .../monitoring-device-state/battery-monitoring.jd | 120 + .../connectivity-monitoring.jd | 70 + .../monitoring-device-state/docking-monitoring.jd | 74 + .../ja/training/monitoring-device-state/index.jd | 49 + .../monitoring-device-state/manifest-receivers.jd | 50 + docs/html/intl/ja/training/multiscreen/adaptui.jd | 212 ++ docs/html/intl/ja/training/multiscreen/index.jd | 64 + .../ja/training/multiscreen/screendensities.jd | 100 + .../intl/ja/training/multiscreen/screensizes.jd | 279 +++ .../monitoring-device-state/battery-monitoring.jd | 120 + .../connectivity-monitoring.jd | 70 + .../monitoring-device-state/docking-monitoring.jd | 74 + .../ko/training/monitoring-device-state/index.jd | 49 + .../monitoring-device-state/manifest-receivers.jd | 50 + docs/html/intl/ko/training/multiscreen/adaptui.jd | 212 ++ docs/html/intl/ko/training/multiscreen/index.jd | 64 + .../ko/training/multiscreen/screendensities.jd | 100 + .../intl/ko/training/multiscreen/screensizes.jd | 279 +++ .../monitoring-device-state/battery-monitoring.jd | 120 + .../connectivity-monitoring.jd | 70 + .../monitoring-device-state/docking-monitoring.jd | 74 + .../ru/training/monitoring-device-state/index.jd | 49 + .../monitoring-device-state/manifest-receivers.jd | 50 + docs/html/intl/ru/training/multiscreen/adaptui.jd | 212 ++ docs/html/intl/ru/training/multiscreen/index.jd | 64 + .../ru/training/multiscreen/screendensities.jd | 100 + .../intl/ru/training/multiscreen/screensizes.jd | 279 +++ .../monitoring-device-state/battery-monitoring.jd | 120 + .../connectivity-monitoring.jd | 70 + .../monitoring-device-state/docking-monitoring.jd | 74 + .../training/monitoring-device-state/index.jd | 49 + .../monitoring-device-state/manifest-receivers.jd | 50 + .../intl/zh-CN/training/multiscreen/adaptui.jd | 212 ++ docs/html/intl/zh-CN/training/multiscreen/index.jd | 64 + .../zh-CN/training/multiscreen/screendensities.jd | 100 + .../intl/zh-CN/training/multiscreen/screensizes.jd | 279 +++ docs/html/legal.jd | 129 ++ docs/html/license.jd | 52 +- docs/html/live/index.jd | 5 +- docs/html/mwc2010/index.html | 8 - docs/html/offline.jd | 8 +- .../resources/articles/avoiding-memory-leaks.jd | 111 - .../resources/articles/backward-compatibility.jd | 252 --- .../resources/articles/can-i-use-this-intent.jd | 71 - docs/html/resources/articles/contacts.jd | 424 ---- .../resources/articles/creating-input-method.jd | 528 ----- docs/html/resources/articles/drawable-mutations.jd | 93 - .../articles/faster-screen-orientation-change.jd | 133 -- docs/html/resources/articles/future-proofing.jd | 91 - docs/html/resources/articles/gestures.jd | 213 -- docs/html/resources/articles/glsurfaceview.jd | 270 --- docs/html/resources/articles/images/File.png | Bin 14329 -> 0 bytes docs/html/resources/articles/images/File_002.png | Bin 13623 -> 0 bytes docs/html/resources/articles/images/JFlubber.png | Bin 8824 -> 0 bytes docs/html/resources/articles/images/WikiNotes.png | Bin 58942 -> 0 bytes .../articles/images/all_drawables_changed.png | Bin 60168 -> 0 bytes docs/html/resources/articles/images/android.png | Bin 79299 -> 0 bytes docs/html/resources/articles/images/buttons.png | Bin 4733 -> 0 bytes docs/html/resources/articles/images/contacts-2.png | Bin 12970 -> 0 bytes docs/html/resources/articles/images/contacts.png | Bin 73617 -> 0 bytes .../articles/images/correct_drawables.png | Bin 60746 -> 0 bytes .../articles/images/ddms_allocation_tracker.png | Bin 83383 -> 0 bytes .../articles/images/ddms_allocation_trackerl.png | Bin 514553 -> 0 bytes docs/html/resources/articles/images/device.png | Bin 112261 -> 0 bytes docs/html/resources/articles/images/device_002.png | Bin 97176 -> 0 bytes docs/html/resources/articles/images/gestures.png | Bin 11254 -> 0 bytes .../resources/articles/images/gestures_002.png | Bin 140982 -> 0 bytes .../resources/articles/images/gestures_003.png | Bin 15609 -> 0 bytes .../resources/articles/images/gestures_004.png | Bin 15484 -> 0 bytes .../resources/articles/images/gestures_005.png | Bin 14652 -> 0 bytes .../resources/articles/images/gestures_006.png | Bin 14643 -> 0 bytes docs/html/resources/articles/images/grid.png | Bin 32134 -> 0 bytes docs/html/resources/articles/images/ime.png | Bin 14225 -> 0 bytes docs/html/resources/articles/images/ime_002.png | Bin 14589 -> 0 bytes docs/html/resources/articles/images/ime_003.png | Bin 51163 -> 0 bytes docs/html/resources/articles/images/ime_004.png | Bin 10840 -> 0 bytes docs/html/resources/articles/images/ime_005.png | Bin 13099 -> 0 bytes docs/html/resources/articles/images/ime_006.png | Bin 14041 -> 0 bytes .../articles/images/layouts_comparison_small.png | Bin 132330 -> 0 bytes docs/html/resources/articles/images/list01.png | Bin 81747 -> 0 bytes docs/html/resources/articles/images/list02.png | Bin 85815 -> 0 bytes .../html/resources/articles/images/list_fade_1.png | Bin 44890 -> 0 bytes .../html/resources/articles/images/list_fade_2.png | Bin 136484 -> 0 bytes .../html/resources/articles/images/list_fade_3.png | Bin 105257 -> 0 bytes .../html/resources/articles/images/list_fade_4.png | Bin 190068 -> 0 bytes .../articles/images/live_wallpapers_small.png | Bin 152066 -> 0 bytes docs/html/resources/articles/images/merge1.jpg | Bin 49327 -> 0 bytes docs/html/resources/articles/images/merge2.png | Bin 29721 -> 0 bytes docs/html/resources/articles/images/merge3.png | Bin 26044 -> 0 bytes docs/html/resources/articles/images/merge4.jpg | Bin 44128 -> 0 bytes docs/html/resources/articles/images/merge5.png | Bin 35091 -> 0 bytes .../resources/articles/images/mutated_states.png | Bin 60394 -> 0 bytes .../resources/articles/images/on-screen-inputs.png | Bin 44392 -> 0 bytes .../articles/images/on-screen-inputs_002.png | Bin 34148 -> 0 bytes .../articles/images/on-screen-inputs_003.png | Bin 24749 -> 0 bytes .../articles/images/on-screen-inputs_004.png | Bin 55736 -> 0 bytes .../articles/images/on-screen-inputs_005.png | Bin 14092 -> 0 bytes .../articles/images/on-screen-inputs_006.png | Bin 24405 -> 0 bytes .../articles/images/photostream_landscape.png | Bin 104835 -> 0 bytes .../articles/images/photostream_portrait.png | Bin 124993 -> 0 bytes docs/html/resources/articles/images/qsb.png | Bin 34882 -> 0 bytes docs/html/resources/articles/images/qsb_002.png | Bin 246945 -> 0 bytes docs/html/resources/articles/images/qsb_003.png | Bin 43897 -> 0 bytes .../resources/articles/images/relativelayout_1.png | Bin 10385 -> 0 bytes .../resources/articles/images/relativelayout_2.png | Bin 8335 -> 0 bytes .../resources/articles/images/relativelayout_3.png | Bin 8394 -> 0 bytes .../articles/images/relativelayout_wire_1.png | Bin 3554 -> 0 bytes .../articles/images/relativelayout_wire_2.png | Bin 3553 -> 0 bytes .../articles/images/relativelayout_wire_3.png | Bin 3543 -> 0 bytes docs/html/resources/articles/images/search01.png | Bin 132998 -> 0 bytes docs/html/resources/articles/images/search02.png | Bin 115605 -> 0 bytes ...e-api-changes-starting-with_runningservices.png | Bin 40632 -> 0 bytes ...rvice-api-changes-starting-with_stopservice.png | Bin 39834 -> 0 bytes .../resources/articles/images/shared_states.png | Bin 54451 -> 0 bytes docs/html/resources/articles/images/shelves2.png | Bin 123418 -> 0 bytes .../resources/articles/images/speech-input.png | Bin 41478 -> 0 bytes docs/html/resources/articles/images/text_field.png | Bin 63949 -> 0 bytes docs/html/resources/articles/images/ui-1.6.png | Bin 14329 -> 0 bytes docs/html/resources/articles/images/ui-1.6_002.png | Bin 13623 -> 0 bytes docs/html/resources/articles/images/viewstub1.png | Bin 123418 -> 0 bytes docs/html/resources/articles/images/viewstub2.png | Bin 112198 -> 0 bytes docs/html/resources/articles/images/viewstub3.png | Bin 30279 -> 0 bytes docs/html/resources/articles/images/viewstub4.png | Bin 46944 -> 0 bytes docs/html/resources/articles/images/webview.png | Bin 14463 -> 0 bytes .../articles/images/window_background.png | Bin 136846 -> 0 bytes .../articles/images/window_background_null.png | Bin 136728 -> 0 bytes .../articles/images/window_background_root.png | Bin 29229 -> 0 bytes docs/html/resources/articles/index.jd | 168 -- .../resources/articles/layout-tricks-efficiency.jd | 179 -- .../html/resources/articles/layout-tricks-merge.jd | 202 -- .../html/resources/articles/layout-tricks-reuse.jd | 81 - .../html/resources/articles/layout-tricks-stubs.jd | 86 - .../resources/articles/listview-backgrounds.jd | 88 - docs/html/resources/articles/live-folders.jd | 170 -- docs/html/resources/articles/live-wallpapers.jd | 102 - .../resources/articles/multitasking-android-way.jd | 103 - docs/html/resources/articles/on-screen-inputs.jd | 265 --- docs/html/resources/articles/painless-threading.jd | 149 -- docs/html/resources/articles/qsb.jd | 169 -- .../articles/service-api-changes-starting-with.jd | 177 -- docs/html/resources/articles/speech-input.jd | 94 - .../resources/articles/spell-checker-framework.jd | 236 -- docs/html/resources/articles/timed-ui-updates.jd | 151 -- docs/html/resources/articles/touch-mode.jd | 140 -- docs/html/resources/articles/track-mem.jd | 64 - docs/html/resources/articles/tts.jd | 243 -- docs/html/resources/articles/ui-1.5.jd | 50 - docs/html/resources/articles/ui-1.6.jd | 132 -- docs/html/resources/articles/using-webviews.jd | 63 - docs/html/resources/articles/wikinotes-intents.jd | 257 --- docs/html/resources/articles/wikinotes-linkify.jd | 115 - docs/html/resources/articles/window-bg-speed.jd | 127 -- docs/html/resources/articles/zipalign.jd | 100 - docs/html/resources/browser.jd | 49 - docs/html/resources/community-groups.jd | 120 - docs/html/resources/community-more.jd | 71 - docs/html/resources/dashboard/opengl.jd | 79 - docs/html/resources/dashboard/platform-versions.jd | 117 - docs/html/resources/dashboard/screens.jd | 101 - docs/html/resources/images/ActionBarCompat1.png | Bin 0 -> 19637 bytes docs/html/resources/images/ActionBarCompat2.png | Bin 0 -> 22271 bytes docs/html/resources/images/BluetoothChat1.png | Bin 0 -> 16064 bytes docs/html/resources/images/BluetoothChat2.png | Bin 0 -> 15678 bytes docs/html/resources/images/BluetoothHDP.png | Bin 0 -> 58734 bytes docs/html/resources/images/BusinessCard1.png | Bin 0 -> 6425 bytes docs/html/resources/images/BusinessCard2.png | Bin 0 -> 8902 bytes docs/html/resources/images/ContactManager1.png | Bin 0 -> 18050 bytes docs/html/resources/images/ContactManager2.png | Bin 0 -> 17125 bytes docs/html/resources/images/CubeLiveWallpaper1.png | Bin 0 -> 49522 bytes docs/html/resources/images/CubeLiveWallpaper3.png | Bin 0 -> 45714 bytes docs/html/resources/images/HomeSample.png | Bin 0 -> 44416 bytes docs/html/resources/images/JetBoy.png | Bin 0 -> 53801 bytes docs/html/resources/images/KeyChainDemo1.png | Bin 0 -> 142236 bytes docs/html/resources/images/KeyChainDemo2.png | Bin 0 -> 40334 bytes docs/html/resources/images/KeyChainDemo3.png | Bin 0 -> 62468 bytes docs/html/resources/images/KeyChainDemo4.png | Bin 0 -> 61334 bytes docs/html/resources/images/MultiResolution.png | Bin 0 -> 96462 bytes docs/html/resources/images/NewsReader.png | Bin 0 -> 183245 bytes docs/html/resources/images/NfcDemo.png | Bin 0 -> 12750 bytes docs/html/resources/images/SampleSyncAdapter1.png | Bin 0 -> 32368 bytes docs/html/resources/images/SampleSyncAdapter2.png | Bin 0 -> 45843 bytes docs/html/resources/images/SampleSyncAdapter3.png | Bin 0 -> 38011 bytes .../resources/images/SearchableDictionary1.png | Bin 0 -> 15800 bytes .../resources/images/SearchableDictionary2.png | Bin 0 -> 18114 bytes docs/html/resources/images/SipDemo.png | Bin 0 -> 72267 bytes docs/html/resources/images/Snake.png | Bin 0 -> 5445 bytes docs/html/resources/images/SoftKeyboard.png | Bin 0 -> 13426 bytes docs/html/resources/images/SpinnerTest1.png | Bin 0 -> 8872 bytes docs/html/resources/images/SpinnerTest2.png | Bin 0 -> 17278 bytes docs/html/resources/images/StackWidget.png | Bin 0 -> 2525 bytes docs/html/resources/images/TicTacToeLib.png | Bin 0 -> 28337 bytes docs/html/resources/images/TicTacToeMain.png | Bin 0 -> 37680 bytes .../resources/images/VoicemailProviderDemo.png | Bin 0 -> 34137 bytes docs/html/resources/images/WeatherListWidget.png | Bin 0 -> 28360 bytes docs/html/resources/images/WifiDirect.png | Bin 0 -> 33285 bytes docs/html/resources/images/Wiktionary.png | Bin 0 -> 35229 bytes docs/html/resources/images/WiktionarySimple.png | Bin 0 -> 69288 bytes docs/html/resources/images/XmlPhotosAdapter.png | Bin 0 -> 108550 bytes docs/html/resources/images/XmlRssReader.png | Bin 0 -> 118780 bytes docs/html/resources/images/hcgallery-phone1.png | Bin 0 -> 26118 bytes docs/html/resources/images/hcgallery-phone2.png | Bin 0 -> 52306 bytes docs/html/resources/images/hcgallery.png | Bin 0 -> 249709 bytes docs/html/resources/images/randommusicplayer.png | Bin 0 -> 18502 bytes docs/html/resources/images/sample_lunarlander.png | Bin 0 -> 27514 bytes docs/html/resources/images/sample_note.png | Bin 0 -> 6011 bytes docs/html/resources/images/sample_notepad.png | Bin 0 -> 6530 bytes .../resources/images/sample_notepadtest_junit.png | Bin 0 -> 20515 bytes docs/html/resources/images/vpn-confirmation.png | Bin 0 -> 60214 bytes docs/html/resources/index.jd | 90 - docs/html/resources/resources-data.js | 946 -------- docs/html/resources/resources_toc.cs | 687 ------ docs/html/resources/samples/get.jd | 92 - .../resources/samples/images/ActionBarCompat1.png | Bin 19637 -> 0 bytes .../resources/samples/images/ActionBarCompat2.png | Bin 22271 -> 0 bytes .../resources/samples/images/BluetoothChat1.png | Bin 16064 -> 0 bytes .../resources/samples/images/BluetoothChat2.png | Bin 15678 -> 0 bytes .../html/resources/samples/images/BluetoothHDP.png | Bin 58734 -> 0 bytes .../resources/samples/images/BusinessCard1.png | Bin 6425 -> 0 bytes .../resources/samples/images/BusinessCard2.png | Bin 8902 -> 0 bytes .../resources/samples/images/ContactManager1.png | Bin 18050 -> 0 bytes .../resources/samples/images/ContactManager2.png | Bin 17125 -> 0 bytes .../samples/images/CubeLiveWallpaper1.png | Bin 49522 -> 0 bytes .../samples/images/CubeLiveWallpaper3.png | Bin 45714 -> 0 bytes docs/html/resources/samples/images/HomeSample.png | Bin 44416 -> 0 bytes docs/html/resources/samples/images/JetBoy.png | Bin 53801 -> 0 bytes .../resources/samples/images/KeyChainDemo1.png | Bin 142236 -> 0 bytes .../resources/samples/images/KeyChainDemo2.png | Bin 40334 -> 0 bytes .../resources/samples/images/KeyChainDemo3.png | Bin 62468 -> 0 bytes .../resources/samples/images/KeyChainDemo4.png | Bin 61334 -> 0 bytes .../resources/samples/images/MultiResolution.png | Bin 96462 -> 0 bytes docs/html/resources/samples/images/NewsReader.png | Bin 183245 -> 0 bytes docs/html/resources/samples/images/NfcDemo.png | Bin 12750 -> 0 bytes .../samples/images/SampleSyncAdapter1.png | Bin 32368 -> 0 bytes .../samples/images/SampleSyncAdapter2.png | Bin 45843 -> 0 bytes .../samples/images/SampleSyncAdapter3.png | Bin 38011 -> 0 bytes .../samples/images/SearchableDictionary1.png | Bin 15800 -> 0 bytes .../samples/images/SearchableDictionary2.png | Bin 18114 -> 0 bytes docs/html/resources/samples/images/SipDemo.png | Bin 72267 -> 0 bytes docs/html/resources/samples/images/Snake.png | Bin 5445 -> 0 bytes .../html/resources/samples/images/SoftKeyboard.png | Bin 13426 -> 0 bytes .../html/resources/samples/images/SpinnerTest1.png | Bin 8872 -> 0 bytes .../html/resources/samples/images/SpinnerTest2.png | Bin 17278 -> 0 bytes docs/html/resources/samples/images/StackWidget.png | Bin 2525 -> 0 bytes .../html/resources/samples/images/TicTacToeLib.png | Bin 28337 -> 0 bytes .../resources/samples/images/TicTacToeMain.png | Bin 37680 -> 0 bytes .../samples/images/VoicemailProviderDemo.png | Bin 34137 -> 0 bytes .../resources/samples/images/WeatherListWidget.png | Bin 28360 -> 0 bytes docs/html/resources/samples/images/WifiDirect.png | Bin 33285 -> 0 bytes docs/html/resources/samples/images/Wiktionary.png | Bin 35229 -> 0 bytes .../resources/samples/images/WiktionarySimple.png | Bin 69288 -> 0 bytes .../resources/samples/images/XmlPhotosAdapter.png | Bin 108550 -> 0 bytes .../html/resources/samples/images/XmlRssReader.png | Bin 118780 -> 0 bytes .../resources/samples/images/hcgallery-phone1.png | Bin 26118 -> 0 bytes .../resources/samples/images/hcgallery-phone2.png | Bin 52306 -> 0 bytes docs/html/resources/samples/images/hcgallery.png | Bin 249709 -> 0 bytes .../resources/samples/images/randommusicplayer.png | Bin 18502 -> 0 bytes .../samples/images/sample_lunarlander.png | Bin 27514 -> 0 bytes docs/html/resources/samples/images/sample_note.png | Bin 6011 -> 0 bytes .../resources/samples/images/sample_notepad.png | Bin 6530 -> 0 bytes .../samples/images/sample_notepadtest_junit.png | Bin 20515 -> 0 bytes .../resources/samples/images/vpn-confirmation.png | Bin 60214 -> 0 bytes docs/html/resources/samples/index.jd | 11 - docs/html/resources/topics.jd | 72 - docs/html/resources/tutorials/hello-world.jd | 607 ----- docs/html/resources/tutorials/index.html | 8 - .../html/resources/tutorials/localization/index.jd | 595 ----- docs/html/resources/tutorials/notepad/index.jd | 4 +- .../resources/tutorials/notepad/notepad-ex1.jd | 2 +- .../resources/tutorials/notepad/notepad-ex3.jd | 2 +- .../tutorials/notepad/notepad-extra-credit.jd | 2 +- .../html/resources/tutorials/opengl/opengl-es10.jd | 532 ----- .../html/resources/tutorials/opengl/opengl-es20.jd | 652 ------ .../resources/tutorials/testing/activity_test.jd | 1381 ------------ .../tutorials/testing/helloandroid_test.jd | 508 ----- .../tutorials/views/hello-autocomplete.jd | 173 -- .../resources/tutorials/views/hello-datepicker.jd | 173 -- .../resources/tutorials/views/hello-formstuff.jd | 400 ---- .../resources/tutorials/views/hello-gallery.jd | 171 -- .../resources/tutorials/views/hello-gridview.jd | 182 -- .../tutorials/views/hello-linearlayout.jd | 133 -- .../resources/tutorials/views/hello-listview.jd | 170 -- .../resources/tutorials/views/hello-mapview.jd | 303 --- .../tutorials/views/hello-relativelayout.jd | 89 - .../resources/tutorials/views/hello-spinner.jd | 149 -- .../resources/tutorials/views/hello-tablelayout.jd | 124 - .../resources/tutorials/views/hello-tabwidget.jd | 210 -- .../resources/tutorials/views/hello-timepicker.jd | 167 -- .../resources/tutorials/views/hello-webview.jd | 131 -- .../resources/tutorials/views/images/android.png | Bin 693 -> 0 bytes .../tutorials/views/images/android_focused.png | Bin 2785 -> 0 bytes .../tutorials/views/images/android_normal.png | Bin 2056 -> 0 bytes .../tutorials/views/images/android_pressed.png | Bin 2337 -> 0 bytes .../tutorials/views/images/androidmarker.png | Bin 702 -> 0 bytes .../tutorials/views/images/hello-autocomplete.png | Bin 17719 -> 0 bytes .../tutorials/views/images/hello-datepicker.png | Bin 7322 -> 0 bytes .../tutorials/views/images/hello-formstuff.png | Bin 23272 -> 0 bytes .../tutorials/views/images/hello-gallery.png | Bin 5593 -> 0 bytes .../tutorials/views/images/hello-gridview.png | Bin 21768 -> 0 bytes .../tutorials/views/images/hello-linearlayout.png | Bin 4207 -> 0 bytes .../tutorials/views/images/hello-listview.png | Bin 26359 -> 0 bytes .../tutorials/views/images/hello-mapview.png | Bin 50499 -> 0 bytes .../views/images/hello-relativelayout.png | Bin 2399 -> 0 bytes .../tutorials/views/images/hello-spinner.png | Bin 2513 -> 0 bytes .../tutorials/views/images/hello-tablelayout.png | Bin 3446 -> 0 bytes .../tutorials/views/images/hello-tabwidget.png | Bin 10393 -> 0 bytes .../tutorials/views/images/hello-timepicker.png | Bin 5644 -> 0 bytes .../tutorials/views/images/hello-webview.png | Bin 16490 -> 0 bytes .../tutorials/views/images/ic_tab_artists_grey.png | Bin 791 -> 0 bytes .../views/images/ic_tab_artists_white.png | Bin 1127 -> 0 bytes docs/html/resources/tutorials/views/index.jd | 121 - docs/html/sdk/OLD_RELEASENOTES.jd | 12 +- docs/html/sdk/RELEASENOTES.jd | 30 +- docs/html/sdk/adding-components.jd | 209 -- docs/html/sdk/adt-notes.jd | 5 - docs/html/sdk/adt_download.html | 10 - docs/html/sdk/android-1.1.jd | 246 -- docs/html/sdk/android-1.5-highlights.jd | 208 -- docs/html/sdk/android-1.5.jd | 375 ---- docs/html/sdk/android-1.6-highlights.jd | 213 -- docs/html/sdk/android-1.6.jd | 505 ----- docs/html/sdk/android-2.0-highlights.jd | 201 -- docs/html/sdk/android-2.0.1.jd | 361 --- docs/html/sdk/android-2.0.jd | 384 ---- docs/html/sdk/android-2.1.jd | 373 ---- docs/html/sdk/android-2.2-highlights.jd | 298 --- docs/html/sdk/android-2.2.jd | 470 ---- docs/html/sdk/android-2.3-highlights.jd | 446 ---- docs/html/sdk/android-2.3.3.jd | 419 ---- docs/html/sdk/android-2.3.4.jd | 381 ---- docs/html/sdk/android-2.3.jd | 942 -------- docs/html/sdk/android-3.0-highlights.jd | 263 --- docs/html/sdk/android-3.0.jd | 1186 ---------- docs/html/sdk/android-3.1-highlights.jd | 380 ---- docs/html/sdk/android-3.1.jd | 1106 --------- docs/html/sdk/android-3.2.jd | 741 ------ docs/html/sdk/android-4.0-highlights.jd | 1009 --------- docs/html/sdk/android-4.0.3.jd | 555 ----- docs/html/sdk/android-4.0.jd | 2059 ----------------- .../sdk/api_diff/10/changes/changes-summary.html | 2 +- .../sdk/api_diff/11/changes/changes-summary.html | 2 +- .../sdk/api_diff/12/changes/changes-summary.html | 2 +- .../sdk/api_diff/13/changes/changes-summary.html | 2 +- .../sdk/api_diff/14/changes/changes-summary.html | 2 +- .../sdk/api_diff/15/changes/changes-summary.html | 2 +- .../sdk/api_diff/3/changes/changes-summary.html | 2 +- .../sdk/api_diff/4/changes/changes-summary.html | 2 +- .../sdk/api_diff/5/changes/changes-summary.html | 2 +- .../sdk/api_diff/6/changes/changes-summary.html | 2 +- .../sdk/api_diff/7/changes/changes-summary.html | 2 +- .../sdk/api_diff/8/changes/changes-summary.html | 2 +- .../sdk/api_diff/9/changes/changes-summary.html | 2 +- docs/html/sdk/compatibility-library.jd | 484 ---- docs/html/sdk/download.jd | 93 - docs/html/sdk/eclipse-adt.jd | 1413 ------------ docs/html/sdk/exploring.jd | 166 ++ docs/html/sdk/images/4.0/contact-call.xcf | Bin 1081675 -> 0 bytes docs/html/sdk/index.jd | 131 +- docs/html/sdk/installing.jd | 590 ----- docs/html/sdk/installing/adding-packages.jd | 78 + docs/html/sdk/installing/index.jd | 133 ++ docs/html/sdk/installing/installing-adt.jd | 206 ++ docs/html/sdk/installing/next.jd | 52 + docs/html/sdk/ndk/1.5_r1/index.jd | 6 - docs/html/sdk/ndk/1.6_r1/index.jd | 5 - docs/html/sdk/ndk/index.jd | 1055 --------- docs/html/sdk/ndk/overview.jd | 559 ----- docs/html/sdk/oem-usb.jd | 324 --- docs/html/sdk/older_releases.jd | 2 +- docs/html/sdk/preview/features.jd | 8 - docs/html/sdk/preview/index.jd | 2 - docs/html/sdk/preview/installing.jd | 8 - docs/html/sdk/preview/requirements.jd | 8 - docs/html/sdk/preview/upgrading.jd | 8 - docs/html/sdk/requirements.jd | 114 - docs/html/sdk/sdk_toc.cs | 228 -- docs/html/sdk/terms.jd | 207 -- docs/html/sdk/terms_body.html | 336 --- docs/html/sdk/tools-notes.jd | 857 ------- docs/html/sdk/win-usb.jd | 6 +- docs/html/search.jd | 148 -- docs/html/shareables/training/CustomView.zip | Bin 0 -> 72290 bytes docs/html/shareables/training/FragmentBasics.zip | Bin 283520 -> 283814 bytes docs/html/shareables/training/NetworkUsage.zip | Bin 0 -> 24270 bytes docs/html/shareables/training/OpenGLES.zip | Bin 0 -> 27980 bytes docs/html/sitemap-intl.txt | 8 +- docs/html/sitemap.txt | 150 +- docs/html/support.jd | 74 + docs/html/tools/aidl.jd | 465 ++++ docs/html/tools/avd.html | 10 + docs/html/tools/building/building-cmdline.jd | 371 +++ docs/html/tools/building/building-eclipse.jd | 165 ++ docs/html/tools/building/index.jd | 81 + docs/html/tools/debug-tasks.html | 10 + docs/html/tools/debugging/ddms.jd | 357 +++ docs/html/tools/debugging/debugging-devtools.jd | 77 + docs/html/tools/debugging/debugging-log.jd | 308 +++ .../tools/debugging/debugging-projects-cmdline.jd | 78 + docs/html/tools/debugging/debugging-projects.jd | 67 + docs/html/tools/debugging/debugging-tracing.jd | 402 ++++ docs/html/tools/debugging/debugging-ui.jd | 547 +++++ docs/html/tools/debugging/index.jd | 186 ++ docs/html/tools/device.jd | 267 +++ docs/html/tools/devices/emulator.jd | 1571 +++++++++++++ docs/html/tools/devices/index.jd | 78 + docs/html/tools/devices/managing-avds-cmdline.jd | 369 +++ docs/html/tools/devices/managing-avds.jd | 237 ++ docs/html/tools/eclipse-adt.html | 10 + docs/html/tools/extras/index.jd | 5 + docs/html/tools/extras/oem-usb.jd | 328 +++ docs/html/tools/extras/support-library.jd | 507 +++++ docs/html/tools/help/MonkeyDevice.jd | 1355 +++++++++++ docs/html/tools/help/MonkeyImage.jd | 437 ++++ docs/html/tools/help/MonkeyRunner.jd | 448 ++++ docs/html/tools/help/aapt.html | 10 + docs/html/tools/help/adb.jd | 669 ++++++ docs/html/tools/help/adt.jd | 527 +++++ docs/html/tools/help/android.jd | 393 ++++ docs/html/tools/help/bmgr.jd | 193 ++ docs/html/tools/help/ddms.html | 10 + docs/html/tools/help/dmtracedump.jd | 66 + docs/html/tools/help/draw9patch.jd | 59 + docs/html/tools/help/emulator.jd | 581 +++++ docs/html/tools/help/etc1tool.jd | 68 + docs/html/tools/help/hierarchy-viewer.jd | 18 + docs/html/tools/help/hprof-conv.jd | 16 + docs/html/tools/help/index.jd | 84 + docs/html/tools/help/layoutopt.jd | 24 + docs/html/tools/help/logcat.jd | 106 + docs/html/tools/help/mksdcard.jd | 55 + docs/html/tools/help/monkey.jd | 242 ++ docs/html/tools/help/monkeyrunner_concepts.jd | 319 +++ docs/html/tools/help/proguard.jd | 189 ++ docs/html/tools/help/sqlite3.jd | 59 + docs/html/tools/help/traceview.jd | 16 + docs/html/tools/help/zipalign.jd | 67 + docs/html/tools/index.jd | 96 + docs/html/tools/other-ide.html | 10 + docs/html/tools/othertools.html | 10 + docs/html/tools/projects/index.jd | 446 ++++ docs/html/tools/projects/projects-cmdline.jd | 295 +++ docs/html/tools/projects/projects-eclipse.jd | 237 ++ docs/html/tools/publishing/app-signing.jd | 618 +++++ docs/html/tools/publishing/preparing.jd | 359 +++ docs/html/tools/publishing/publishing_overview.jd | 238 ++ docs/html/tools/publishing/versioning.jd | 174 ++ docs/html/tools/revisions/index.jd | 9 + docs/html/tools/revisions/platforms.jd | 831 +++++++ docs/html/tools/samples/index.jd | 31 + docs/html/tools/sdk/OLD_RELEASENOTES.jd | 527 +++++ docs/html/tools/sdk/RELEASENOTES.jd | 803 +++++++ docs/html/tools/sdk/addons.jd | 9 + docs/html/tools/sdk/adt-notes.jd | 5 + docs/html/tools/sdk/adt_download.html | 10 + docs/html/tools/sdk/download.jd | 93 + docs/html/tools/sdk/eclipse-adt.jd | 1178 ++++++++++ docs/html/tools/sdk/images/2.0/camera-modes.png | Bin 0 -> 87824 bytes docs/html/tools/sdk/images/2.0/email-inbox.png | Bin 0 -> 38766 bytes docs/html/tools/sdk/images/2.0/mms-search.png | Bin 0 -> 12842 bytes .../tools/sdk/images/2.0/multiple-accounts.png | Bin 0 -> 39122 bytes docs/html/tools/sdk/images/2.0/quick-connect.png | Bin 0 -> 30379 bytes docs/html/tools/sdk/images/2.2/22browser.png | Bin 0 -> 126458 bytes docs/html/tools/sdk/images/2.2/22exchange.png | Bin 0 -> 113049 bytes docs/html/tools/sdk/images/2.2/22gallery.png | Bin 0 -> 146789 bytes docs/html/tools/sdk/images/2.2/22home.png | Bin 0 -> 146759 bytes docs/html/tools/sdk/images/2.2/22hotspot.png | Bin 0 -> 50561 bytes docs/html/tools/sdk/images/2.2/22keyboard.png | Bin 0 -> 41355 bytes docs/html/tools/sdk/images/2.2/jit-graph.png | Bin 0 -> 11990 bytes docs/html/tools/sdk/images/2.3/ffc.png | Bin 0 -> 311628 bytes docs/html/tools/sdk/images/2.3/home-menu.png | Bin 0 -> 278552 bytes docs/html/tools/sdk/images/2.3/home-plain.png | Bin 0 -> 428133 bytes docs/html/tools/sdk/images/2.3/nfc.png | Bin 0 -> 27547 bytes docs/html/tools/sdk/images/2.3/onetouch.png | Bin 0 -> 43272 bytes docs/html/tools/sdk/images/2.3/power.png | Bin 0 -> 62788 bytes docs/html/tools/sdk/images/2.3/running.png | Bin 0 -> 72197 bytes docs/html/tools/sdk/images/2.3/selection.png | Bin 0 -> 30206 bytes docs/html/tools/sdk/images/2.3/sipcall.png | Bin 0 -> 34554 bytes docs/html/tools/sdk/images/3.0/browser.png | Bin 0 -> 73398 bytes docs/html/tools/sdk/images/3.0/browser_full.png | Bin 0 -> 751808 bytes docs/html/tools/sdk/images/3.0/camera.png | Bin 0 -> 81122 bytes docs/html/tools/sdk/images/3.0/camera_full.png | Bin 0 -> 870501 bytes docs/html/tools/sdk/images/3.0/contacts.png | Bin 0 -> 15102 bytes docs/html/tools/sdk/images/3.0/contacts_full.png | Bin 0 -> 126300 bytes docs/html/tools/sdk/images/3.0/copy.png | Bin 0 -> 21333 bytes docs/html/tools/sdk/images/3.0/copy_full.png | Bin 0 -> 97476 bytes docs/html/tools/sdk/images/3.0/home_hero1.png | Bin 0 -> 158528 bytes docs/html/tools/sdk/images/3.0/home_hero1_full.png | Bin 0 -> 798511 bytes .../tools/sdk/images/3.0/homescreen_cust_port.png | Bin 0 -> 84171 bytes .../sdk/images/3.0/homescreen_cust_port_full.png | Bin 0 -> 675192 bytes docs/html/tools/sdk/images/3.0/mail_drag.png | Bin 0 -> 25096 bytes docs/html/tools/sdk/images/3.0/mail_drag_full.png | Bin 0 -> 126694 bytes docs/html/tools/sdk/images/3.0/tasks.png | Bin 0 -> 76666 bytes docs/html/tools/sdk/images/3.0/tasks_full.png | Bin 0 -> 753902 bytes docs/html/tools/sdk/images/3.0/widgets.png | Bin 0 -> 236461 bytes docs/html/tools/sdk/images/3.1/controls.png | Bin 0 -> 103866 bytes docs/html/tools/sdk/images/3.1/home.png | Bin 0 -> 142023 bytes docs/html/tools/sdk/images/3.1/home_full.png | Bin 0 -> 624953 bytes docs/html/tools/sdk/images/3.1/resizeable.png | Bin 0 -> 64928 bytes docs/html/tools/sdk/images/3.1/tasks.png | Bin 0 -> 136355 bytes docs/html/tools/sdk/images/4.0/allapps-lg.png | Bin 0 -> 167249 bytes docs/html/tools/sdk/images/4.0/allapps.png | Bin 0 -> 26073 bytes docs/html/tools/sdk/images/4.0/bbench.png | Bin 0 -> 9161 bytes docs/html/tools/sdk/images/4.0/beam-lg.png | Bin 0 -> 121355 bytes docs/html/tools/sdk/images/4.0/beam-maps-lg.png | Bin 0 -> 175873 bytes docs/html/tools/sdk/images/4.0/beam-maps.png | Bin 0 -> 23063 bytes docs/html/tools/sdk/images/4.0/beam.png | Bin 0 -> 17497 bytes docs/html/tools/sdk/images/4.0/browser-lg.png | Bin 0 -> 212370 bytes docs/html/tools/sdk/images/4.0/browser-tabs-lg.png | Bin 0 -> 230345 bytes docs/html/tools/sdk/images/4.0/browser-tabs.png | Bin 0 -> 27626 bytes docs/html/tools/sdk/images/4.0/browser.png | Bin 0 -> 29700 bytes .../tools/sdk/images/4.0/calendar-widget-lg.png | Bin 0 -> 191944 bytes docs/html/tools/sdk/images/4.0/calendar-widget.png | Bin 0 -> 28184 bytes docs/html/tools/sdk/images/4.0/camera-lg.png | Bin 0 -> 360317 bytes docs/html/tools/sdk/images/4.0/camera.png | Bin 0 -> 48868 bytes docs/html/tools/sdk/images/4.0/contact-call-lg.png | Bin 0 -> 206397 bytes docs/html/tools/sdk/images/4.0/contact-call.png | Bin 0 -> 29626 bytes docs/html/tools/sdk/images/4.0/contact-call.xcf | Bin 0 -> 1081675 bytes .../tools/sdk/images/4.0/contact-connect-lg.png | Bin 0 -> 185666 bytes docs/html/tools/sdk/images/4.0/contact-connect.png | Bin 0 -> 27749 bytes .../html/tools/sdk/images/4.0/contact-email-lg.png | Bin 0 -> 106147 bytes docs/html/tools/sdk/images/4.0/contact-email.png | Bin 0 -> 22350 bytes .../html/tools/sdk/images/4.0/contact-faves-lg.png | Bin 0 -> 280921 bytes docs/html/tools/sdk/images/4.0/contact-faves.png | Bin 0 -> 36503 bytes docs/html/tools/sdk/images/4.0/face-unlock-lg.png | Bin 0 -> 228900 bytes docs/html/tools/sdk/images/4.0/face-unlock.png | Bin 0 -> 148069 bytes docs/html/tools/sdk/images/4.0/folders.xcf | Bin 0 -> 259819 bytes docs/html/tools/sdk/images/4.0/gallery-edit-lg.png | Bin 0 -> 360693 bytes docs/html/tools/sdk/images/4.0/gallery-edit.png | Bin 0 -> 43068 bytes .../html/tools/sdk/images/4.0/gallery-share-lg.png | Bin 0 -> 340002 bytes docs/html/tools/sdk/images/4.0/gallery-share.png | Bin 0 -> 46363 bytes docs/html/tools/sdk/images/4.0/gallery-widget.png | Bin 0 -> 268739 bytes docs/html/tools/sdk/images/4.0/home-lg.png | Bin 0 -> 290279 bytes docs/html/tools/sdk/images/4.0/home.png | Bin 0 -> 51314 bytes docs/html/tools/sdk/images/4.0/live-effects.png | Bin 0 -> 64701 bytes docs/html/tools/sdk/images/4.0/lock-camera-lg.png | Bin 0 -> 185967 bytes docs/html/tools/sdk/images/4.0/lock-camera.png | Bin 0 -> 26512 bytes docs/html/tools/sdk/images/4.0/lock-lg.png | Bin 0 -> 235618 bytes docs/html/tools/sdk/images/4.0/lock.png | Bin 0 -> 30920 bytes .../tools/sdk/images/4.0/quick-responses-lg.png | Bin 0 -> 125876 bytes docs/html/tools/sdk/images/4.0/quick-responses.png | Bin 0 -> 20648 bytes docs/html/tools/sdk/images/4.0/screenshot-lg.png | Bin 0 -> 572192 bytes docs/html/tools/sdk/images/4.0/screenshot.png | Bin 0 -> 62111 bytes docs/html/tools/sdk/images/4.0/tasks-lg.png | Bin 0 -> 335903 bytes docs/html/tools/sdk/images/4.0/tasks.png | Bin 0 -> 43450 bytes docs/html/tools/sdk/images/4.0/text-replace-lg.png | Bin 0 -> 114302 bytes docs/html/tools/sdk/images/4.0/text-replace.png | Bin 0 -> 19053 bytes docs/html/tools/sdk/images/4.0/tts-lg.png | Bin 0 -> 121886 bytes docs/html/tools/sdk/images/4.0/tts.png | Bin 0 -> 27595 bytes docs/html/tools/sdk/images/4.0/usage-all-lg.png | Bin 0 -> 83625 bytes docs/html/tools/sdk/images/4.0/usage-all.png | Bin 0 -> 17602 bytes docs/html/tools/sdk/images/4.0/usage-maps-lg.png | Bin 0 -> 92558 bytes docs/html/tools/sdk/images/4.0/usage-maps.png | Bin 0 -> 19163 bytes docs/html/tools/sdk/images/battery.png | Bin 0 -> 22208 bytes docs/html/tools/sdk/images/camera.png | Bin 0 -> 47444 bytes docs/html/tools/sdk/images/donut_small_bg.png | Bin 0 -> 4031 bytes docs/html/tools/sdk/images/market.png | Bin 0 -> 40382 bytes docs/html/tools/sdk/images/search.png | Bin 0 -> 24245 bytes docs/html/tools/sdk/index.jd | 10 + docs/html/tools/sdk/installing.jd | 590 +++++ docs/html/tools/sdk/libraries.jd | 9 + docs/html/tools/sdk/ndk/1.5_r1/index.jd | 6 + docs/html/tools/sdk/ndk/1.6_r1/index.jd | 5 + docs/html/tools/sdk/ndk/index.jd | 1128 ++++++++++ docs/html/tools/sdk/ndk/overview.jd | 588 +++++ docs/html/tools/sdk/older_releases.jd | 613 +++++ docs/html/tools/sdk/platforms.jd | 9 + docs/html/tools/sdk/preview/features.jd | 8 + docs/html/tools/sdk/preview/index.jd | 2 + docs/html/tools/sdk/preview/installing.jd | 8 + docs/html/tools/sdk/preview/requirements.jd | 8 + docs/html/tools/sdk/preview/upgrading.jd | 8 + docs/html/tools/sdk/tools-notes.jd | 855 +++++++ docs/html/tools/sdk/usb-drivers.jd | 9 + docs/html/tools/sdk/win-usb.jd | 172 ++ docs/html/tools/testing/activity_test.jd | 1334 +++++++++++ docs/html/tools/testing/activity_testing.jd | 375 ++++ docs/html/tools/testing/contentprovider_testing.jd | 217 ++ docs/html/tools/testing/index.jd | 40 + docs/html/tools/testing/service_testing.jd | 176 ++ docs/html/tools/testing/testing_android.jd | 640 ++++++ docs/html/tools/testing/testing_eclipse.jd | 535 +++++ docs/html/tools/testing/testing_otheride.jd | 690 ++++++ docs/html/tools/testing/what_to_test.jd | 86 + docs/html/tools/tools_toc.cs | 214 ++ docs/html/tools/workflow.jd | 150 ++ docs/html/tools/workflow/app-signing.jd | 618 +++++ docs/html/tools/workflow/index.jd | 150 ++ docs/html/tools/workflow/publishing/app-signing.jd | 618 +++++ docs/html/tools/workflow/publishing/preparing.jd | 358 +++ docs/html/tools/workflow/publishing/publishing.jd | 703 ++++++ .../workflow/publishing/publishing_overview.jd | 231 ++ docs/html/tools/workflow/publishing/versioning.jd | 174 ++ docs/html/tools/workflow/publishing_overview.jd | 231 ++ docs/html/tools/workflow/versioning.jd | 174 ++ docs/html/training/advanced.jd | 11 + docs/html/training/backward-compatible-ui/index.jd | 2 +- .../training/basics/activity-lifecycle/index.jd | 2 +- .../training/basics/activity-lifecycle/pausing.jd | 2 +- .../basics/activity-lifecycle/recreating.jd | 2 +- .../training/basics/activity-lifecycle/starting.jd | 2 +- .../training/basics/activity-lifecycle/stopping.jd | 4 +- docs/html/training/basics/firstapp/building-ui.jd | 29 +- .../training/basics/firstapp/creating-project.jd | 16 +- docs/html/training/basics/firstapp/index.jd | 2 +- docs/html/training/basics/firstapp/running-app.jd | 10 +- .../training/basics/firstapp/starting-activity.jd | 10 +- .../training/basics/fragments/communicating.jd | 2 +- docs/html/training/basics/fragments/creating.jd | 4 +- docs/html/training/basics/fragments/fragment-ui.jd | 2 +- docs/html/training/basics/fragments/index.jd | 2 +- docs/html/training/basics/fragments/support-lib.jd | 4 +- docs/html/training/basics/intents/index.jd | 4 +- docs/html/training/basics/intents/sending.jd | 2 +- .../html/training/basics/network-ops/connecting.jd | 284 +++ docs/html/training/basics/network-ops/index.jd | 73 + docs/html/training/basics/network-ops/managing.jd | 445 ++++ docs/html/training/basics/network-ops/xml.jd | 555 +++++ .../basics/supporting-devices/languages.jd | 4 + .../basics/supporting-devices/platforms.jd | 8 +- docs/html/training/camera/index.jd | 2 +- docs/html/training/camera/photobasics.jd | 2 +- docs/html/training/camera/videobasics.jd | 2 +- docs/html/training/custom-views/create-view.jd | 281 +++ docs/html/training/custom-views/custom-drawing.jd | 284 +++ docs/html/training/custom-views/index.jd | 79 + .../training/custom-views/making-interactive.jd | 292 +++ docs/html/training/custom-views/optimizing-view.jd | 176 ++ .../design-navigation/ancestral-temporal.jd | 4 +- .../html/training/design-navigation/wireframing.jd | 6 +- docs/html/training/displaying-bitmaps/index.jd | 2 +- .../training/displaying-bitmaps/process-bitmap.jd | 4 +- .../efficient-network-access.jd | 2 +- docs/html/training/graphics/opengl/draw.jd | 195 ++ docs/html/training/graphics/opengl/environment.jd | 223 ++ docs/html/training/graphics/opengl/index.jd | 75 + docs/html/training/graphics/opengl/motion.jd | 92 + docs/html/training/graphics/opengl/projection.jd | 152 ++ docs/html/training/graphics/opengl/shapes.jd | 153 ++ docs/html/training/graphics/opengl/touch.jd | 145 ++ docs/html/training/id-auth/index.jd | 2 +- .../training/implementing-navigation/ancestral.jd | 4 +- .../html/training/implementing-navigation/index.jd | 4 +- .../training/implementing-navigation/lateral.jd | 2 +- .../training/implementing-navigation/temporal.jd | 4 +- .../improving-layouts/optimizing-layout.jd | 6 +- docs/html/training/index.jd | 12 +- docs/html/training/managing-audio/index.jd | 2 +- .../monitoring-device-state/battery-monitoring.jd | 2 +- .../connectivity-monitoring.jd | 2 +- .../monitoring-device-state/docking-monitoring.jd | 2 +- .../html/training/monitoring-device-state/index.jd | 4 +- .../monitoring-device-state/manifest-receivers.jd | 2 +- docs/html/training/multiple-apks/api.jd | 14 +- docs/html/training/multiple-apks/index.jd | 2 +- docs/html/training/multiple-apks/multiple.jd | 12 +- docs/html/training/multiple-apks/screensize.jd | 12 +- docs/html/training/multiple-apks/texture.jd | 10 +- docs/html/training/multiscreen/index.jd | 8 +- docs/html/training/multiscreen/screensizes.jd | 2 +- docs/html/training/sharing/index.jd | 2 +- docs/html/training/sharing/receive.jd | 6 +- docs/html/training/sharing/send.jd | 2 +- docs/html/training/training_toc.cs | 685 ++++++ docs/html/training/tv/optimizing-layouts-tv.jd | 4 +- docs/html/videos/index.jd | 355 --- 1236 files changed, 92516 insertions(+), 86246 deletions(-) create mode 100644 docs/html/about/about_toc.cs create mode 100644 docs/html/about/dashboards/index.jd create mode 100644 docs/html/about/flexible.jd create mode 100644 docs/html/about/index.jd create mode 100644 docs/html/about/marketplace.jd create mode 100644 docs/html/about/start.jd create mode 100644 docs/html/about/versions/android-1.1.jd create mode 100644 docs/html/about/versions/android-1.5-highlights.jd create mode 100644 docs/html/about/versions/android-1.5.jd create mode 100644 docs/html/about/versions/android-1.6-highlights.jd create mode 100644 docs/html/about/versions/android-1.6.jd create mode 100644 docs/html/about/versions/android-2.0-highlights.jd create mode 100644 docs/html/about/versions/android-2.0.1.jd create mode 100644 docs/html/about/versions/android-2.0.jd create mode 100644 docs/html/about/versions/android-2.1.jd create mode 100644 docs/html/about/versions/android-2.2-highlights.jd create mode 100644 docs/html/about/versions/android-2.2.jd create mode 100644 docs/html/about/versions/android-2.3-highlights.jd create mode 100644 docs/html/about/versions/android-2.3.3.jd create mode 100644 docs/html/about/versions/android-2.3.4.jd create mode 100644 docs/html/about/versions/android-2.3.jd create mode 100644 docs/html/about/versions/android-3.0-highlights.jd create mode 100644 docs/html/about/versions/android-3.0.jd create mode 100644 docs/html/about/versions/android-3.1-highlights.jd create mode 100644 docs/html/about/versions/android-3.1.jd create mode 100644 docs/html/about/versions/android-3.2.jd create mode 100644 docs/html/about/versions/android-4.0-highlights.jd create mode 100644 docs/html/about/versions/android-4.0.3.jd create mode 100644 docs/html/about/versions/android-4.0.jd create mode 100644 docs/html/about/versions/api-levels.jd create mode 100644 docs/html/about/versions/index.jd delete mode 100644 docs/html/community/index.html create mode 100644 docs/html/develop/index.jd create mode 100644 docs/html/distribute/distribute_toc.cs create mode 100644 docs/html/distribute/googleplay/about/distribution.jd create mode 100644 docs/html/distribute/googleplay/about/monetizing.jd create mode 100644 docs/html/distribute/googleplay/about/visibility.jd create mode 100644 docs/html/distribute/googleplay/index.html create mode 100644 docs/html/distribute/googleplay/promote/badges.jd create mode 100644 docs/html/distribute/googleplay/promote/brand.jd create mode 100644 docs/html/distribute/googleplay/promote/index.jd create mode 100644 docs/html/distribute/googleplay/promote/linking.jd create mode 100644 docs/html/distribute/googleplay/promote/product-pages.jd create mode 100644 docs/html/distribute/googleplay/publish/console.jd create mode 100644 docs/html/distribute/googleplay/publish/index.jd create mode 100644 docs/html/distribute/googleplay/publish/preparing.jd create mode 100644 docs/html/distribute/googleplay/publish/register.jd create mode 100644 docs/html/distribute/googleplay/strategies/app-quality.jd create mode 100644 docs/html/distribute/googleplay/strategies/featuring.jd create mode 100644 docs/html/distribute/googleplay/strategies/index.jd create mode 100644 docs/html/distribute/index.jd create mode 100644 docs/html/distribute/open.jd create mode 100644 docs/html/favicon-a.ico delete mode 100644 docs/html/guide/appendix/api-levels.jd delete mode 100644 docs/html/guide/appendix/market-filters.jd delete mode 100644 docs/html/guide/basics/what-is-android.jd create mode 100644 docs/html/guide/components/activities.jd create mode 100644 docs/html/guide/components/bound-services.jd create mode 100644 docs/html/guide/components/fragments.jd create mode 100644 docs/html/guide/components/fundamentals.jd create mode 100644 docs/html/guide/components/index.jd create mode 100644 docs/html/guide/components/intents-filters.jd create mode 100644 docs/html/guide/components/loaders.jd create mode 100644 docs/html/guide/components/processes-and-threads.jd create mode 100644 docs/html/guide/components/services.jd create mode 100644 docs/html/guide/components/tasks-and-back-stack.jd delete mode 100644 docs/html/guide/developing/building/building-cmdline.jd delete mode 100644 docs/html/guide/developing/building/building-eclipse.jd delete mode 100644 docs/html/guide/developing/building/index.jd delete mode 100644 docs/html/guide/developing/debug-tasks.html delete mode 100644 docs/html/guide/developing/debugging/ddms.jd delete mode 100644 docs/html/guide/developing/debugging/debugging-devtools.jd delete mode 100644 docs/html/guide/developing/debugging/debugging-log.jd delete mode 100644 docs/html/guide/developing/debugging/debugging-projects-cmdline.jd delete mode 100644 docs/html/guide/developing/debugging/debugging-projects.jd delete mode 100644 docs/html/guide/developing/debugging/debugging-tracing.jd delete mode 100644 docs/html/guide/developing/debugging/debugging-ui.jd delete mode 100644 docs/html/guide/developing/debugging/index.jd delete mode 100644 docs/html/guide/developing/device.jd delete mode 100644 docs/html/guide/developing/devices/emulator.jd delete mode 100644 docs/html/guide/developing/devices/index.jd delete mode 100644 docs/html/guide/developing/devices/managing-avds-cmdline.jd delete mode 100644 docs/html/guide/developing/devices/managing-avds.jd delete mode 100644 docs/html/guide/developing/eclipse-adt.html delete mode 100644 docs/html/guide/developing/index.jd delete mode 100644 docs/html/guide/developing/other-ide.html delete mode 100644 docs/html/guide/developing/projects/index.jd delete mode 100644 docs/html/guide/developing/projects/projects-cmdline.jd delete mode 100644 docs/html/guide/developing/projects/projects-eclipse.jd delete mode 100644 docs/html/guide/developing/testing/index.jd delete mode 100644 docs/html/guide/developing/testing/testing_eclipse.jd delete mode 100644 docs/html/guide/developing/testing/testing_otheride.jd delete mode 100644 docs/html/guide/developing/tools/MonkeyDevice.jd delete mode 100644 docs/html/guide/developing/tools/MonkeyImage.jd delete mode 100644 docs/html/guide/developing/tools/MonkeyRunner.jd delete mode 100644 docs/html/guide/developing/tools/aapt.html delete mode 100644 docs/html/guide/developing/tools/adb.jd delete mode 100644 docs/html/guide/developing/tools/adt.jd delete mode 100644 docs/html/guide/developing/tools/aidl.jd delete mode 100644 docs/html/guide/developing/tools/android.jd delete mode 100644 docs/html/guide/developing/tools/avd.html delete mode 100644 docs/html/guide/developing/tools/bmgr.jd delete mode 100644 docs/html/guide/developing/tools/ddms.html delete mode 100644 docs/html/guide/developing/tools/dmtracedump.jd delete mode 100644 docs/html/guide/developing/tools/draw9patch.jd delete mode 100644 docs/html/guide/developing/tools/emulator.jd delete mode 100644 docs/html/guide/developing/tools/etc1tool.jd delete mode 100644 docs/html/guide/developing/tools/hierarchy-viewer.jd delete mode 100644 docs/html/guide/developing/tools/hprof-conv.jd delete mode 100644 docs/html/guide/developing/tools/index.jd delete mode 100644 docs/html/guide/developing/tools/layoutopt.jd delete mode 100644 docs/html/guide/developing/tools/logcat.jd delete mode 100644 docs/html/guide/developing/tools/mksdcard.jd delete mode 100644 docs/html/guide/developing/tools/monkey.jd delete mode 100644 docs/html/guide/developing/tools/monkeyrunner_concepts.jd delete mode 100644 docs/html/guide/developing/tools/othertools.html delete mode 100644 docs/html/guide/developing/tools/proguard.jd delete mode 100644 docs/html/guide/developing/tools/sqlite3.jd delete mode 100644 docs/html/guide/developing/tools/traceview.jd delete mode 100644 docs/html/guide/developing/tools/zipalign.jd create mode 100644 docs/html/guide/google/index.jd create mode 100644 docs/html/guide/google/play/billing/billing_about.html create mode 100755 docs/html/guide/google/play/billing/billing_admin.jd create mode 100755 docs/html/guide/google/play/billing/billing_best_practices.jd create mode 100755 docs/html/guide/google/play/billing/billing_integrate.jd create mode 100755 docs/html/guide/google/play/billing/billing_overview.jd create mode 100755 docs/html/guide/google/play/billing/billing_reference.jd create mode 100755 docs/html/guide/google/play/billing/billing_subscriptions.jd create mode 100755 docs/html/guide/google/play/billing/billing_testing.jd create mode 100755 docs/html/guide/google/play/billing/index.jd create mode 100644 docs/html/guide/google/play/expansion-files.jd create mode 100644 docs/html/guide/google/play/filters.jd create mode 100644 docs/html/guide/google/play/index.jd create mode 100644 docs/html/guide/google/play/licensing/adding-licensing.jd create mode 100644 docs/html/guide/google/play/licensing/index.jd create mode 100644 docs/html/guide/google/play/licensing/licensing-reference.jd create mode 100644 docs/html/guide/google/play/licensing/overview.jd create mode 100644 docs/html/guide/google/play/licensing/setting-up.jd create mode 100644 docs/html/guide/google/play/publishing/multiple-apks.jd delete mode 100644 docs/html/guide/market/billing/billing_about.html delete mode 100755 docs/html/guide/market/billing/billing_admin.jd delete mode 100755 docs/html/guide/market/billing/billing_best_practices.jd delete mode 100755 docs/html/guide/market/billing/billing_integrate.jd delete mode 100755 docs/html/guide/market/billing/billing_overview.jd delete mode 100755 docs/html/guide/market/billing/billing_reference.jd delete mode 100755 docs/html/guide/market/billing/billing_testing.jd delete mode 100755 docs/html/guide/market/billing/index.jd delete mode 100644 docs/html/guide/market/expansion-files.jd delete mode 100644 docs/html/guide/market/licensing/adding-licensing.jd delete mode 100644 docs/html/guide/market/licensing/index.jd delete mode 100644 docs/html/guide/market/licensing/licensing-reference.jd delete mode 100644 docs/html/guide/market/licensing/overview.jd delete mode 100644 docs/html/guide/market/licensing/setting-up.jd delete mode 100644 docs/html/guide/market/publishing/multiple-apks.jd create mode 100644 docs/html/guide/practices/app-design/accessibility.html create mode 100644 docs/html/guide/practices/app-design/index.jd create mode 100644 docs/html/guide/practices/app-design/jni.jd create mode 100644 docs/html/guide/practices/app-design/performance.jd create mode 100644 docs/html/guide/practices/app-design/responsiveness.jd create mode 100644 docs/html/guide/practices/app-design/seamlessness.jd delete mode 100644 docs/html/guide/practices/design/accessibility.html delete mode 100644 docs/html/guide/practices/design/index.jd delete mode 100644 docs/html/guide/practices/design/jni.jd delete mode 100644 docs/html/guide/practices/design/performance.jd delete mode 100644 docs/html/guide/practices/design/responsiveness.jd delete mode 100644 docs/html/guide/practices/design/seamlessness.jd delete mode 100644 docs/html/guide/practices/index.html create mode 100644 docs/html/guide/practices/index.jd create mode 100644 docs/html/guide/practices/jni.jd create mode 100644 docs/html/guide/practices/performance.jd create mode 100644 docs/html/guide/practices/responsiveness.jd create mode 100644 docs/html/guide/practices/seamlessness.jd delete mode 100644 docs/html/guide/publishing/app-signing.jd delete mode 100644 docs/html/guide/publishing/licensing.html delete mode 100644 docs/html/guide/publishing/preparing.jd delete mode 100644 docs/html/guide/publishing/publishing.jd delete mode 100755 docs/html/guide/publishing/publishing_overview.jd delete mode 100644 docs/html/guide/publishing/versioning.jd create mode 100644 docs/html/guide/topics/admin/index.jd create mode 100644 docs/html/guide/topics/admin/keychain.jd delete mode 100644 docs/html/guide/topics/clipboard/copy-paste.jd create mode 100644 docs/html/guide/topics/connectivity/bluetooth.jd create mode 100644 docs/html/guide/topics/connectivity/index.jd create mode 100644 docs/html/guide/topics/connectivity/nfc/advanced-nfc.jd create mode 100644 docs/html/guide/topics/connectivity/nfc/index.jd create mode 100644 docs/html/guide/topics/connectivity/nfc/nfc.jd create mode 100644 docs/html/guide/topics/connectivity/sip.jd create mode 100644 docs/html/guide/topics/connectivity/usb/accessory.jd create mode 100644 docs/html/guide/topics/connectivity/usb/adk.jd create mode 100644 docs/html/guide/topics/connectivity/usb/host.jd create mode 100644 docs/html/guide/topics/connectivity/usb/index.jd create mode 100644 docs/html/guide/topics/connectivity/wifip2p.jd delete mode 100644 docs/html/guide/topics/data/index.html create mode 100644 docs/html/guide/topics/data/index.jd create mode 100644 docs/html/guide/topics/data/install-location.jd delete mode 100644 docs/html/guide/topics/drawing/index.html delete mode 100644 docs/html/guide/topics/drawing/opengl.jd delete mode 100644 docs/html/guide/topics/fundamentals.jd delete mode 100644 docs/html/guide/topics/fundamentals/activities.jd delete mode 100644 docs/html/guide/topics/fundamentals/bound-services.jd delete mode 100644 docs/html/guide/topics/fundamentals/fragments.jd delete mode 100644 docs/html/guide/topics/fundamentals/loaders.jd delete mode 100644 docs/html/guide/topics/fundamentals/processes-and-threads.jd delete mode 100644 docs/html/guide/topics/fundamentals/services.jd delete mode 100644 docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd delete mode 100644 docs/html/guide/topics/graphics/animation.jd create mode 100644 docs/html/guide/topics/graphics/overview.jd create mode 100644 docs/html/guide/topics/graphics/renderscript/compute.jd create mode 100644 docs/html/guide/topics/graphics/renderscript/graphics.jd create mode 100644 docs/html/guide/topics/graphics/renderscript/index.jd create mode 100644 docs/html/guide/topics/graphics/renderscript/reference.jd delete mode 100644 docs/html/guide/topics/intents/index.html delete mode 100644 docs/html/guide/topics/intents/intents-filters.jd delete mode 100644 docs/html/guide/topics/location/obtaining-user-location.jd create mode 100644 docs/html/guide/topics/location/strategies.jd delete mode 100644 docs/html/guide/topics/network/sip.jd delete mode 100644 docs/html/guide/topics/nfc/advanced-nfc.jd delete mode 100644 docs/html/guide/topics/nfc/index.jd delete mode 100644 docs/html/guide/topics/nfc/nfc.jd create mode 100644 docs/html/guide/topics/providers/contacts-provider.jd delete mode 100644 docs/html/guide/topics/renderscript/compute.jd delete mode 100644 docs/html/guide/topics/renderscript/graphics.jd delete mode 100644 docs/html/guide/topics/renderscript/index.jd delete mode 100644 docs/html/guide/topics/renderscript/reference.jd create mode 100644 docs/html/guide/topics/resources/overview.jd create mode 100644 docs/html/guide/topics/security/index.jd create mode 100644 docs/html/guide/topics/security/permissions.jd delete mode 100644 docs/html/guide/topics/testing/activity_testing.jd delete mode 100644 docs/html/guide/topics/testing/contentprovider_testing.jd delete mode 100644 docs/html/guide/topics/testing/index.jd delete mode 100644 docs/html/guide/topics/testing/service_testing.jd delete mode 100755 docs/html/guide/topics/testing/testing_android.jd delete mode 100644 docs/html/guide/topics/testing/what_to_test.jd create mode 100644 docs/html/guide/topics/text/copy-paste.jd create mode 100644 docs/html/guide/topics/text/creating-input-method.jd create mode 100644 docs/html/guide/topics/text/index.jd create mode 100644 docs/html/guide/topics/text/spell-checker-framework.jd create mode 100644 docs/html/guide/topics/ui/controls.jd create mode 100644 docs/html/guide/topics/ui/controls/button.jd create mode 100644 docs/html/guide/topics/ui/controls/checkbox.jd create mode 100644 docs/html/guide/topics/ui/controls/pickers.jd create mode 100644 docs/html/guide/topics/ui/controls/radiobutton.jd create mode 100644 docs/html/guide/topics/ui/controls/spinner.jd create mode 100644 docs/html/guide/topics/ui/controls/text.jd create mode 100644 docs/html/guide/topics/ui/controls/togglebutton.jd create mode 100644 docs/html/guide/topics/ui/images/android_focused.png create mode 100644 docs/html/guide/topics/ui/images/android_normal.png create mode 100644 docs/html/guide/topics/ui/images/android_pressed.png create mode 100755 docs/html/guide/topics/ui/images/hello-gallery.png create mode 100755 docs/html/guide/topics/ui/images/hello-gridview.png create mode 100755 docs/html/guide/topics/ui/images/hello-linearlayout.png create mode 100644 docs/html/guide/topics/ui/images/hello-listview.png create mode 100644 docs/html/guide/topics/ui/images/hello-mapview.png create mode 100755 docs/html/guide/topics/ui/images/hello-relativelayout.png create mode 100755 docs/html/guide/topics/ui/images/hello-tablelayout.png create mode 100644 docs/html/guide/topics/ui/images/hello-tabwidget.png create mode 100644 docs/html/guide/topics/ui/images/hello-webview.png create mode 100644 docs/html/guide/topics/ui/images/ic_tab_artists_grey.png create mode 100644 docs/html/guide/topics/ui/images/ic_tab_artists_white.png create mode 100644 docs/html/guide/topics/ui/layout/grid.jd create mode 100644 docs/html/guide/topics/ui/layout/gridview.jd create mode 100644 docs/html/guide/topics/ui/layout/linear.jd create mode 100644 docs/html/guide/topics/ui/layout/listview.jd create mode 100644 docs/html/guide/topics/ui/layout/relative.jd create mode 100644 docs/html/guide/topics/ui/layout/tabs.jd create mode 100644 docs/html/guide/topics/ui/overview.jd create mode 100644 docs/html/guide/topics/ui/sharables/sample_images.zip delete mode 100644 docs/html/guide/topics/usb/accessory.jd delete mode 100644 docs/html/guide/topics/usb/adk.jd delete mode 100644 docs/html/guide/topics/usb/host.jd delete mode 100644 docs/html/guide/topics/usb/index.jd delete mode 100644 docs/html/guide/topics/views/custom-views.jd delete mode 100644 docs/html/guide/topics/views/intro.jd delete mode 100644 docs/html/guide/topics/views/ui-xml.jd delete mode 100644 docs/html/guide/topics/wireless/bluetooth.jd delete mode 100644 docs/html/guide/topics/wireless/index.jd delete mode 100644 docs/html/guide/topics/wireless/wifi.jd delete mode 100644 docs/html/guide/topics/wireless/wifip2p.jd delete mode 100644 docs/html/guide/tutorials/hello-world.html delete mode 100644 docs/html/guide/tutorials/images/hello_world_0.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_1.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_2.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_3.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_4.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_5.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_8.png delete mode 100644 docs/html/guide/tutorials/images/hello_world_9.png delete mode 100644 docs/html/guide/tutorials/index.html delete mode 100644 docs/html/guide/tutorials/localization/index.html delete mode 100644 docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip delete mode 100644 docs/html/guide/tutorials/notepad/index.html delete mode 100644 docs/html/guide/tutorials/notepad/notepad-ex1.jd delete mode 100644 docs/html/guide/tutorials/notepad/notepad-ex2.jd delete mode 100644 docs/html/guide/tutorials/notepad/notepad-ex3.jd delete mode 100644 docs/html/guide/tutorials/notepad/notepad-extra-credit.jd delete mode 100644 docs/html/guide/tutorials/notepad/notepad-index.jd delete mode 100644 docs/html/guide/tutorials/views/hello-autocomplete.jd delete mode 100644 docs/html/guide/tutorials/views/hello-datepicker.jd delete mode 100644 docs/html/guide/tutorials/views/hello-formstuff.jd delete mode 100644 docs/html/guide/tutorials/views/hello-gallery.jd delete mode 100644 docs/html/guide/tutorials/views/hello-gridview.jd delete mode 100644 docs/html/guide/tutorials/views/hello-linearlayout.jd delete mode 100644 docs/html/guide/tutorials/views/hello-listview.jd delete mode 100644 docs/html/guide/tutorials/views/hello-mapview.jd delete mode 100644 docs/html/guide/tutorials/views/hello-relativelayout.jd delete mode 100644 docs/html/guide/tutorials/views/hello-spinner.jd delete mode 100644 docs/html/guide/tutorials/views/hello-tablelayout.jd delete mode 100644 docs/html/guide/tutorials/views/hello-tabwidget.jd delete mode 100644 docs/html/guide/tutorials/views/hello-timepicker.jd delete mode 100644 docs/html/guide/tutorials/views/hello-webview.jd delete mode 100755 docs/html/guide/tutorials/views/images/android.png delete mode 100755 docs/html/guide/tutorials/views/images/androidmarker.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-autocomplete.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-datepicker.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-formstuff.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-gallery.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-gridview.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-linearlayout.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-listview.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-mapview.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-relativelayout.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-spinner.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-tablelayout.png delete mode 100644 docs/html/guide/tutorials/views/images/hello-tabwidget.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-timepicker.png delete mode 100755 docs/html/guide/tutorials/views/images/hello-webview.png delete mode 100644 docs/html/guide/tutorials/views/index.html create mode 100644 docs/html/guide/webapps/overview.jd create mode 100644 docs/html/images/about/growth-chart.png create mode 100644 docs/html/images/android-logo.png create mode 100644 docs/html/images/billing_subscription_flow.png create mode 100644 docs/html/images/brand/android_app_on_play_logo_large.png create mode 100644 docs/html/images/brand/android_app_on_play_logo_small.png create mode 100644 docs/html/images/brand/droid.gif create mode 100644 docs/html/images/brand/get_it_on_play_logo_large.png create mode 100644 docs/html/images/brand/get_it_on_play_logo_small.png create mode 100644 docs/html/images/brand/google_play_logo_450.png create mode 100644 docs/html/images/brand/learnmore.gif create mode 100644 docs/html/images/brand/logo_android.gif create mode 100644 docs/html/images/brand/mediaplayer.gif create mode 100644 docs/html/images/brand/norad.gif create mode 100644 docs/html/images/dac-design-icon.png create mode 100644 docs/html/images/debugging-tall.png create mode 100644 docs/html/images/develop-placeholder.png create mode 100644 docs/html/images/develop/app_components.png create mode 100644 docs/html/images/develop/auth-code.png create mode 100644 docs/html/images/develop/connectivity.png create mode 100644 docs/html/images/develop/marquee-play.png create mode 100644 docs/html/images/develop/resources.png create mode 100644 docs/html/images/distribute/feature-market.png create mode 100644 docs/html/images/distribute/feature-monetize.png create mode 100644 docs/html/images/distribute/feature-register.png create mode 100644 docs/html/images/distribute/marquee-play.png create mode 100644 docs/html/images/editorschoice_ann.png create mode 100644 docs/html/images/gp-apps-home.png create mode 100644 docs/html/images/gp-buyer-currency.png create mode 100644 docs/html/images/gp-collectibles.png create mode 100644 docs/html/images/gp-dc-countries.png create mode 100644 docs/html/images/gp-dc-details.png create mode 100644 docs/html/images/gp-dc-home.png create mode 100644 docs/html/images/gp-dc-profile.png create mode 100644 docs/html/images/gp-dc-reviews.png create mode 100644 docs/html/images/gp-dc-stats-mini.png create mode 100644 docs/html/images/gp-dc-stats.png create mode 100644 docs/html/images/gp-details-pages-magicpiano.png create mode 100644 docs/html/images/gp-details-ww-purchase.png create mode 100644 docs/html/images/gp-details-ww.png create mode 100644 docs/html/images/gp-devconsole-home.png create mode 100644 docs/html/images/gp-device.png create mode 100644 docs/html/images/gp-games-home.png create mode 100644 docs/html/images/gp-growth-downloads.png create mode 100644 docs/html/images/gp-rating-web.png create mode 100644 docs/html/images/gp-sendto.png create mode 100644 docs/html/images/gp-subs.png create mode 100644 docs/html/images/gp-supported-dev-requirements.png create mode 100644 docs/html/images/gp-tab.png create mode 100644 docs/html/images/gp-top-new-paid.png create mode 100644 docs/html/images/gpp-cat-feature280-photo.png create mode 100644 docs/html/images/gpp-cat-feature280-puzzle.png create mode 100644 docs/html/images/gpp-cat-feature280-sports.png create mode 100644 docs/html/images/home-marquee.jpg create mode 100644 docs/html/images/home/design.png create mode 100644 docs/html/images/home/developers_live.png create mode 100644 docs/html/images/home/google-io.png create mode 100644 docs/html/images/home/google-play.png create mode 100644 docs/html/images/home/ics-android.png create mode 100644 docs/html/images/opengl/ccw-square.png create mode 100644 docs/html/images/opengl/ccw-winding.png delete mode 100644 docs/html/images/opengl/helloopengl-es10-1.png delete mode 100644 docs/html/images/opengl/helloopengl-es10-2.png delete mode 100644 docs/html/images/opengl/helloopengl-es20-1.png delete mode 100644 docs/html/images/opengl/helloopengl-es20-2.png create mode 100644 docs/html/images/opengl/ogl-triangle-projected.png create mode 100644 docs/html/images/opengl/ogl-triangle-touch.png create mode 100644 docs/html/images/opengl/ogl-triangle.png create mode 100644 docs/html/images/play_tableft.png create mode 100644 docs/html/images/providers/ContactsDataFlow.png create mode 100644 docs/html/images/providers/contacts_structure.png create mode 100644 docs/html/images/providers/contacts_tables.png create mode 100644 docs/html/images/providers/data_columns.png delete mode 100755 docs/html/images/publishing/publishing_unknown_sources.png create mode 100644 docs/html/images/publishing/publishing_unknown_sources_sm.png create mode 100644 docs/html/images/robot-sdk.png create mode 100644 docs/html/images/robot-tiny.png create mode 100644 docs/html/images/sdk-cube.png create mode 100644 docs/html/images/tools-home.png create mode 100644 docs/html/images/topdev_ann.png create mode 100644 docs/html/images/training/basics/network-settings1.png create mode 100644 docs/html/images/training/basics/network-settings2.png create mode 100644 docs/html/images/ui/button-types.png create mode 100644 docs/html/images/ui/buttons-holo.png create mode 100644 docs/html/images/ui/checkboxes.png create mode 100644 docs/html/images/ui/edittext-actionlabel.png create mode 100644 docs/html/images/ui/edittext-actionsend.png create mode 100644 docs/html/images/ui/edittext-autocomplete.png create mode 100644 docs/html/images/ui/edittext-email.png create mode 100644 docs/html/images/ui/edittext-noextract.png create mode 100644 docs/html/images/ui/edittext-phone.png create mode 100644 docs/html/images/ui/edittext-text-next.png create mode 100644 docs/html/images/ui/edittext-text.png create mode 100644 docs/html/images/ui/edittext.png create mode 100644 docs/html/images/ui/gridlayout-small.png create mode 100644 docs/html/images/ui/gridlayout.png create mode 100644 docs/html/images/ui/gridview-small.png create mode 100644 docs/html/images/ui/gridview.png create mode 100644 docs/html/images/ui/linearlayout-small.png create mode 100644 docs/html/images/ui/linearlayout.png create mode 100644 docs/html/images/ui/listview-small.png create mode 100644 docs/html/images/ui/listview.png create mode 100644 docs/html/images/ui/pickers.png create mode 100644 docs/html/images/ui/radiobuttons.png create mode 100644 docs/html/images/ui/relativelayout-small.png create mode 100644 docs/html/images/ui/relativelayout.png create mode 100644 docs/html/images/ui/sample-linearlayout.png create mode 100644 docs/html/images/ui/sample-relativelayout.png create mode 100644 docs/html/images/ui/spinner.png create mode 100644 docs/html/images/ui/switch.png create mode 100644 docs/html/images/ui/tabs-small.png create mode 100644 docs/html/images/ui/tabs.png create mode 100644 docs/html/images/ui/togglebutton.png create mode 100644 docs/html/images/ui/ui-controls.png create mode 100644 docs/html/images/ui/ui_index.png create mode 100644 docs/html/images/ui/webview-small.png create mode 100644 docs/html/images/ui/webview.png create mode 100644 docs/html/intl/es/training/monitoring-device-state/battery-monitoring.jd create mode 100644 docs/html/intl/es/training/monitoring-device-state/connectivity-monitoring.jd create mode 100644 docs/html/intl/es/training/monitoring-device-state/docking-monitoring.jd create mode 100644 docs/html/intl/es/training/monitoring-device-state/index.jd create mode 100644 docs/html/intl/es/training/monitoring-device-state/manifest-receivers.jd create mode 100644 docs/html/intl/es/training/multiscreen/adaptui.jd create mode 100644 docs/html/intl/es/training/multiscreen/index.jd create mode 100644 docs/html/intl/es/training/multiscreen/screendensities.jd create mode 100644 docs/html/intl/es/training/multiscreen/screensizes.jd create mode 100644 docs/html/intl/ja/training/monitoring-device-state/battery-monitoring.jd create mode 100644 docs/html/intl/ja/training/monitoring-device-state/connectivity-monitoring.jd create mode 100644 docs/html/intl/ja/training/monitoring-device-state/docking-monitoring.jd create mode 100644 docs/html/intl/ja/training/monitoring-device-state/index.jd create mode 100644 docs/html/intl/ja/training/monitoring-device-state/manifest-receivers.jd create mode 100644 docs/html/intl/ja/training/multiscreen/adaptui.jd create mode 100644 docs/html/intl/ja/training/multiscreen/index.jd create mode 100644 docs/html/intl/ja/training/multiscreen/screendensities.jd create mode 100644 docs/html/intl/ja/training/multiscreen/screensizes.jd create mode 100644 docs/html/intl/ko/training/monitoring-device-state/battery-monitoring.jd create mode 100644 docs/html/intl/ko/training/monitoring-device-state/connectivity-monitoring.jd create mode 100644 docs/html/intl/ko/training/monitoring-device-state/docking-monitoring.jd create mode 100644 docs/html/intl/ko/training/monitoring-device-state/index.jd create mode 100644 docs/html/intl/ko/training/monitoring-device-state/manifest-receivers.jd create mode 100644 docs/html/intl/ko/training/multiscreen/adaptui.jd create mode 100644 docs/html/intl/ko/training/multiscreen/index.jd create mode 100644 docs/html/intl/ko/training/multiscreen/screendensities.jd create mode 100644 docs/html/intl/ko/training/multiscreen/screensizes.jd create mode 100644 docs/html/intl/ru/training/monitoring-device-state/battery-monitoring.jd create mode 100644 docs/html/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd create mode 100644 docs/html/intl/ru/training/monitoring-device-state/docking-monitoring.jd create mode 100644 docs/html/intl/ru/training/monitoring-device-state/index.jd create mode 100644 docs/html/intl/ru/training/monitoring-device-state/manifest-receivers.jd create mode 100644 docs/html/intl/ru/training/multiscreen/adaptui.jd create mode 100644 docs/html/intl/ru/training/multiscreen/index.jd create mode 100644 docs/html/intl/ru/training/multiscreen/screendensities.jd create mode 100644 docs/html/intl/ru/training/multiscreen/screensizes.jd create mode 100644 docs/html/intl/zh-CN/training/monitoring-device-state/battery-monitoring.jd create mode 100644 docs/html/intl/zh-CN/training/monitoring-device-state/connectivity-monitoring.jd create mode 100644 docs/html/intl/zh-CN/training/monitoring-device-state/docking-monitoring.jd create mode 100644 docs/html/intl/zh-CN/training/monitoring-device-state/index.jd create mode 100644 docs/html/intl/zh-CN/training/monitoring-device-state/manifest-receivers.jd create mode 100644 docs/html/intl/zh-CN/training/multiscreen/adaptui.jd create mode 100644 docs/html/intl/zh-CN/training/multiscreen/index.jd create mode 100644 docs/html/intl/zh-CN/training/multiscreen/screendensities.jd create mode 100644 docs/html/intl/zh-CN/training/multiscreen/screensizes.jd create mode 100644 docs/html/legal.jd delete mode 100644 docs/html/mwc2010/index.html delete mode 100644 docs/html/resources/articles/avoiding-memory-leaks.jd delete mode 100644 docs/html/resources/articles/backward-compatibility.jd delete mode 100644 docs/html/resources/articles/can-i-use-this-intent.jd delete mode 100644 docs/html/resources/articles/contacts.jd delete mode 100644 docs/html/resources/articles/creating-input-method.jd delete mode 100644 docs/html/resources/articles/drawable-mutations.jd delete mode 100644 docs/html/resources/articles/faster-screen-orientation-change.jd delete mode 100644 docs/html/resources/articles/future-proofing.jd delete mode 100644 docs/html/resources/articles/gestures.jd delete mode 100644 docs/html/resources/articles/glsurfaceview.jd delete mode 100644 docs/html/resources/articles/images/File.png delete mode 100644 docs/html/resources/articles/images/File_002.png delete mode 100644 docs/html/resources/articles/images/JFlubber.png delete mode 100644 docs/html/resources/articles/images/WikiNotes.png delete mode 100644 docs/html/resources/articles/images/all_drawables_changed.png delete mode 100644 docs/html/resources/articles/images/android.png delete mode 100644 docs/html/resources/articles/images/buttons.png delete mode 100644 docs/html/resources/articles/images/contacts-2.png delete mode 100644 docs/html/resources/articles/images/contacts.png delete mode 100644 docs/html/resources/articles/images/correct_drawables.png delete mode 100644 docs/html/resources/articles/images/ddms_allocation_tracker.png delete mode 100644 docs/html/resources/articles/images/ddms_allocation_trackerl.png delete mode 100644 docs/html/resources/articles/images/device.png delete mode 100644 docs/html/resources/articles/images/device_002.png delete mode 100644 docs/html/resources/articles/images/gestures.png delete mode 100644 docs/html/resources/articles/images/gestures_002.png delete mode 100644 docs/html/resources/articles/images/gestures_003.png delete mode 100644 docs/html/resources/articles/images/gestures_004.png delete mode 100644 docs/html/resources/articles/images/gestures_005.png delete mode 100644 docs/html/resources/articles/images/gestures_006.png delete mode 100644 docs/html/resources/articles/images/grid.png delete mode 100644 docs/html/resources/articles/images/ime.png delete mode 100644 docs/html/resources/articles/images/ime_002.png delete mode 100644 docs/html/resources/articles/images/ime_003.png delete mode 100644 docs/html/resources/articles/images/ime_004.png delete mode 100644 docs/html/resources/articles/images/ime_005.png delete mode 100644 docs/html/resources/articles/images/ime_006.png delete mode 100644 docs/html/resources/articles/images/layouts_comparison_small.png delete mode 100644 docs/html/resources/articles/images/list01.png delete mode 100644 docs/html/resources/articles/images/list02.png delete mode 100644 docs/html/resources/articles/images/list_fade_1.png delete mode 100644 docs/html/resources/articles/images/list_fade_2.png delete mode 100644 docs/html/resources/articles/images/list_fade_3.png delete mode 100644 docs/html/resources/articles/images/list_fade_4.png delete mode 100644 docs/html/resources/articles/images/live_wallpapers_small.png delete mode 100644 docs/html/resources/articles/images/merge1.jpg delete mode 100644 docs/html/resources/articles/images/merge2.png delete mode 100644 docs/html/resources/articles/images/merge3.png delete mode 100644 docs/html/resources/articles/images/merge4.jpg delete mode 100644 docs/html/resources/articles/images/merge5.png delete mode 100644 docs/html/resources/articles/images/mutated_states.png delete mode 100644 docs/html/resources/articles/images/on-screen-inputs.png delete mode 100644 docs/html/resources/articles/images/on-screen-inputs_002.png delete mode 100644 docs/html/resources/articles/images/on-screen-inputs_003.png delete mode 100644 docs/html/resources/articles/images/on-screen-inputs_004.png delete mode 100644 docs/html/resources/articles/images/on-screen-inputs_005.png delete mode 100644 docs/html/resources/articles/images/on-screen-inputs_006.png delete mode 100644 docs/html/resources/articles/images/photostream_landscape.png delete mode 100644 docs/html/resources/articles/images/photostream_portrait.png delete mode 100644 docs/html/resources/articles/images/qsb.png delete mode 100644 docs/html/resources/articles/images/qsb_002.png delete mode 100644 docs/html/resources/articles/images/qsb_003.png delete mode 100644 docs/html/resources/articles/images/relativelayout_1.png delete mode 100644 docs/html/resources/articles/images/relativelayout_2.png delete mode 100644 docs/html/resources/articles/images/relativelayout_3.png delete mode 100644 docs/html/resources/articles/images/relativelayout_wire_1.png delete mode 100644 docs/html/resources/articles/images/relativelayout_wire_2.png delete mode 100644 docs/html/resources/articles/images/relativelayout_wire_3.png delete mode 100644 docs/html/resources/articles/images/search01.png delete mode 100644 docs/html/resources/articles/images/search02.png delete mode 100644 docs/html/resources/articles/images/service-api-changes-starting-with_runningservices.png delete mode 100644 docs/html/resources/articles/images/service-api-changes-starting-with_stopservice.png delete mode 100644 docs/html/resources/articles/images/shared_states.png delete mode 100644 docs/html/resources/articles/images/shelves2.png delete mode 100644 docs/html/resources/articles/images/speech-input.png delete mode 100644 docs/html/resources/articles/images/text_field.png delete mode 100644 docs/html/resources/articles/images/ui-1.6.png delete mode 100644 docs/html/resources/articles/images/ui-1.6_002.png delete mode 100644 docs/html/resources/articles/images/viewstub1.png delete mode 100644 docs/html/resources/articles/images/viewstub2.png delete mode 100644 docs/html/resources/articles/images/viewstub3.png delete mode 100644 docs/html/resources/articles/images/viewstub4.png delete mode 100644 docs/html/resources/articles/images/webview.png delete mode 100644 docs/html/resources/articles/images/window_background.png delete mode 100644 docs/html/resources/articles/images/window_background_null.png delete mode 100644 docs/html/resources/articles/images/window_background_root.png delete mode 100644 docs/html/resources/articles/index.jd delete mode 100644 docs/html/resources/articles/layout-tricks-efficiency.jd delete mode 100644 docs/html/resources/articles/layout-tricks-merge.jd delete mode 100644 docs/html/resources/articles/layout-tricks-reuse.jd delete mode 100644 docs/html/resources/articles/layout-tricks-stubs.jd delete mode 100644 docs/html/resources/articles/listview-backgrounds.jd delete mode 100644 docs/html/resources/articles/live-folders.jd delete mode 100644 docs/html/resources/articles/live-wallpapers.jd delete mode 100644 docs/html/resources/articles/multitasking-android-way.jd delete mode 100644 docs/html/resources/articles/on-screen-inputs.jd delete mode 100644 docs/html/resources/articles/painless-threading.jd delete mode 100644 docs/html/resources/articles/qsb.jd delete mode 100644 docs/html/resources/articles/service-api-changes-starting-with.jd delete mode 100644 docs/html/resources/articles/speech-input.jd delete mode 100644 docs/html/resources/articles/spell-checker-framework.jd delete mode 100644 docs/html/resources/articles/timed-ui-updates.jd delete mode 100644 docs/html/resources/articles/touch-mode.jd delete mode 100644 docs/html/resources/articles/track-mem.jd delete mode 100644 docs/html/resources/articles/tts.jd delete mode 100644 docs/html/resources/articles/ui-1.5.jd delete mode 100644 docs/html/resources/articles/ui-1.6.jd delete mode 100644 docs/html/resources/articles/using-webviews.jd delete mode 100644 docs/html/resources/articles/wikinotes-intents.jd delete mode 100644 docs/html/resources/articles/wikinotes-linkify.jd delete mode 100644 docs/html/resources/articles/window-bg-speed.jd delete mode 100644 docs/html/resources/articles/zipalign.jd delete mode 100644 docs/html/resources/browser.jd delete mode 100644 docs/html/resources/community-groups.jd delete mode 100644 docs/html/resources/community-more.jd delete mode 100644 docs/html/resources/dashboard/opengl.jd delete mode 100644 docs/html/resources/dashboard/platform-versions.jd delete mode 100644 docs/html/resources/dashboard/screens.jd create mode 100644 docs/html/resources/images/ActionBarCompat1.png create mode 100644 docs/html/resources/images/ActionBarCompat2.png create mode 100644 docs/html/resources/images/BluetoothChat1.png create mode 100644 docs/html/resources/images/BluetoothChat2.png create mode 100644 docs/html/resources/images/BluetoothHDP.png create mode 100644 docs/html/resources/images/BusinessCard1.png create mode 100644 docs/html/resources/images/BusinessCard2.png create mode 100644 docs/html/resources/images/ContactManager1.png create mode 100644 docs/html/resources/images/ContactManager2.png create mode 100644 docs/html/resources/images/CubeLiveWallpaper1.png create mode 100644 docs/html/resources/images/CubeLiveWallpaper3.png create mode 100644 docs/html/resources/images/HomeSample.png create mode 100644 docs/html/resources/images/JetBoy.png create mode 100644 docs/html/resources/images/KeyChainDemo1.png create mode 100755 docs/html/resources/images/KeyChainDemo2.png create mode 100755 docs/html/resources/images/KeyChainDemo3.png create mode 100755 docs/html/resources/images/KeyChainDemo4.png create mode 100644 docs/html/resources/images/MultiResolution.png create mode 100644 docs/html/resources/images/NewsReader.png create mode 100644 docs/html/resources/images/NfcDemo.png create mode 100644 docs/html/resources/images/SampleSyncAdapter1.png create mode 100644 docs/html/resources/images/SampleSyncAdapter2.png create mode 100644 docs/html/resources/images/SampleSyncAdapter3.png create mode 100644 docs/html/resources/images/SearchableDictionary1.png create mode 100644 docs/html/resources/images/SearchableDictionary2.png create mode 100755 docs/html/resources/images/SipDemo.png create mode 100644 docs/html/resources/images/Snake.png create mode 100644 docs/html/resources/images/SoftKeyboard.png create mode 100644 docs/html/resources/images/SpinnerTest1.png create mode 100644 docs/html/resources/images/SpinnerTest2.png create mode 100644 docs/html/resources/images/StackWidget.png create mode 100644 docs/html/resources/images/TicTacToeLib.png create mode 100644 docs/html/resources/images/TicTacToeMain.png create mode 100644 docs/html/resources/images/VoicemailProviderDemo.png create mode 100644 docs/html/resources/images/WeatherListWidget.png create mode 100644 docs/html/resources/images/WifiDirect.png create mode 100644 docs/html/resources/images/Wiktionary.png create mode 100644 docs/html/resources/images/WiktionarySimple.png create mode 100644 docs/html/resources/images/XmlPhotosAdapter.png create mode 100644 docs/html/resources/images/XmlRssReader.png create mode 100644 docs/html/resources/images/hcgallery-phone1.png create mode 100644 docs/html/resources/images/hcgallery-phone2.png create mode 100644 docs/html/resources/images/hcgallery.png create mode 100644 docs/html/resources/images/randommusicplayer.png create mode 100644 docs/html/resources/images/sample_lunarlander.png create mode 100644 docs/html/resources/images/sample_note.png create mode 100644 docs/html/resources/images/sample_notepad.png create mode 100644 docs/html/resources/images/sample_notepadtest_junit.png create mode 100755 docs/html/resources/images/vpn-confirmation.png delete mode 100644 docs/html/resources/index.jd delete mode 100644 docs/html/resources/resources-data.js delete mode 100644 docs/html/resources/resources_toc.cs delete mode 100644 docs/html/resources/samples/get.jd delete mode 100644 docs/html/resources/samples/images/ActionBarCompat1.png delete mode 100644 docs/html/resources/samples/images/ActionBarCompat2.png delete mode 100644 docs/html/resources/samples/images/BluetoothChat1.png delete mode 100644 docs/html/resources/samples/images/BluetoothChat2.png delete mode 100644 docs/html/resources/samples/images/BluetoothHDP.png delete mode 100644 docs/html/resources/samples/images/BusinessCard1.png delete mode 100644 docs/html/resources/samples/images/BusinessCard2.png delete mode 100644 docs/html/resources/samples/images/ContactManager1.png delete mode 100644 docs/html/resources/samples/images/ContactManager2.png delete mode 100644 docs/html/resources/samples/images/CubeLiveWallpaper1.png delete mode 100644 docs/html/resources/samples/images/CubeLiveWallpaper3.png delete mode 100644 docs/html/resources/samples/images/HomeSample.png delete mode 100644 docs/html/resources/samples/images/JetBoy.png delete mode 100644 docs/html/resources/samples/images/KeyChainDemo1.png delete mode 100755 docs/html/resources/samples/images/KeyChainDemo2.png delete mode 100755 docs/html/resources/samples/images/KeyChainDemo3.png delete mode 100755 docs/html/resources/samples/images/KeyChainDemo4.png delete mode 100644 docs/html/resources/samples/images/MultiResolution.png delete mode 100644 docs/html/resources/samples/images/NewsReader.png delete mode 100644 docs/html/resources/samples/images/NfcDemo.png delete mode 100644 docs/html/resources/samples/images/SampleSyncAdapter1.png delete mode 100644 docs/html/resources/samples/images/SampleSyncAdapter2.png delete mode 100644 docs/html/resources/samples/images/SampleSyncAdapter3.png delete mode 100644 docs/html/resources/samples/images/SearchableDictionary1.png delete mode 100644 docs/html/resources/samples/images/SearchableDictionary2.png delete mode 100755 docs/html/resources/samples/images/SipDemo.png delete mode 100644 docs/html/resources/samples/images/Snake.png delete mode 100644 docs/html/resources/samples/images/SoftKeyboard.png delete mode 100644 docs/html/resources/samples/images/SpinnerTest1.png delete mode 100644 docs/html/resources/samples/images/SpinnerTest2.png delete mode 100644 docs/html/resources/samples/images/StackWidget.png delete mode 100644 docs/html/resources/samples/images/TicTacToeLib.png delete mode 100644 docs/html/resources/samples/images/TicTacToeMain.png delete mode 100644 docs/html/resources/samples/images/VoicemailProviderDemo.png delete mode 100644 docs/html/resources/samples/images/WeatherListWidget.png delete mode 100644 docs/html/resources/samples/images/WifiDirect.png delete mode 100644 docs/html/resources/samples/images/Wiktionary.png delete mode 100644 docs/html/resources/samples/images/WiktionarySimple.png delete mode 100644 docs/html/resources/samples/images/XmlPhotosAdapter.png delete mode 100644 docs/html/resources/samples/images/XmlRssReader.png delete mode 100644 docs/html/resources/samples/images/hcgallery-phone1.png delete mode 100644 docs/html/resources/samples/images/hcgallery-phone2.png delete mode 100644 docs/html/resources/samples/images/hcgallery.png delete mode 100644 docs/html/resources/samples/images/randommusicplayer.png delete mode 100644 docs/html/resources/samples/images/sample_lunarlander.png delete mode 100644 docs/html/resources/samples/images/sample_note.png delete mode 100644 docs/html/resources/samples/images/sample_notepad.png delete mode 100644 docs/html/resources/samples/images/sample_notepadtest_junit.png delete mode 100755 docs/html/resources/samples/images/vpn-confirmation.png delete mode 100644 docs/html/resources/samples/index.jd delete mode 100644 docs/html/resources/topics.jd delete mode 100644 docs/html/resources/tutorials/hello-world.jd delete mode 100644 docs/html/resources/tutorials/index.html delete mode 100755 docs/html/resources/tutorials/localization/index.jd delete mode 100644 docs/html/resources/tutorials/opengl/opengl-es10.jd delete mode 100644 docs/html/resources/tutorials/opengl/opengl-es20.jd delete mode 100644 docs/html/resources/tutorials/testing/activity_test.jd delete mode 100644 docs/html/resources/tutorials/testing/helloandroid_test.jd delete mode 100644 docs/html/resources/tutorials/views/hello-autocomplete.jd delete mode 100644 docs/html/resources/tutorials/views/hello-datepicker.jd delete mode 100644 docs/html/resources/tutorials/views/hello-formstuff.jd delete mode 100644 docs/html/resources/tutorials/views/hello-gallery.jd delete mode 100644 docs/html/resources/tutorials/views/hello-gridview.jd delete mode 100644 docs/html/resources/tutorials/views/hello-linearlayout.jd delete mode 100644 docs/html/resources/tutorials/views/hello-listview.jd delete mode 100644 docs/html/resources/tutorials/views/hello-mapview.jd delete mode 100644 docs/html/resources/tutorials/views/hello-relativelayout.jd delete mode 100644 docs/html/resources/tutorials/views/hello-spinner.jd delete mode 100644 docs/html/resources/tutorials/views/hello-tablelayout.jd delete mode 100644 docs/html/resources/tutorials/views/hello-tabwidget.jd delete mode 100644 docs/html/resources/tutorials/views/hello-timepicker.jd delete mode 100644 docs/html/resources/tutorials/views/hello-webview.jd delete mode 100755 docs/html/resources/tutorials/views/images/android.png delete mode 100644 docs/html/resources/tutorials/views/images/android_focused.png delete mode 100644 docs/html/resources/tutorials/views/images/android_normal.png delete mode 100644 docs/html/resources/tutorials/views/images/android_pressed.png delete mode 100755 docs/html/resources/tutorials/views/images/androidmarker.png delete mode 100644 docs/html/resources/tutorials/views/images/hello-autocomplete.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-datepicker.png delete mode 100644 docs/html/resources/tutorials/views/images/hello-formstuff.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-gallery.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-gridview.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-linearlayout.png delete mode 100644 docs/html/resources/tutorials/views/images/hello-listview.png delete mode 100644 docs/html/resources/tutorials/views/images/hello-mapview.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-relativelayout.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-spinner.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-tablelayout.png delete mode 100644 docs/html/resources/tutorials/views/images/hello-tabwidget.png delete mode 100755 docs/html/resources/tutorials/views/images/hello-timepicker.png delete mode 100644 docs/html/resources/tutorials/views/images/hello-webview.png delete mode 100644 docs/html/resources/tutorials/views/images/ic_tab_artists_grey.png delete mode 100644 docs/html/resources/tutorials/views/images/ic_tab_artists_white.png delete mode 100644 docs/html/resources/tutorials/views/index.jd delete mode 100644 docs/html/sdk/adding-components.jd delete mode 100644 docs/html/sdk/adt-notes.jd delete mode 100644 docs/html/sdk/adt_download.html delete mode 100644 docs/html/sdk/android-1.1.jd delete mode 100644 docs/html/sdk/android-1.5-highlights.jd delete mode 100644 docs/html/sdk/android-1.5.jd delete mode 100644 docs/html/sdk/android-1.6-highlights.jd delete mode 100644 docs/html/sdk/android-1.6.jd delete mode 100644 docs/html/sdk/android-2.0-highlights.jd delete mode 100644 docs/html/sdk/android-2.0.1.jd delete mode 100644 docs/html/sdk/android-2.0.jd delete mode 100644 docs/html/sdk/android-2.1.jd delete mode 100644 docs/html/sdk/android-2.2-highlights.jd delete mode 100644 docs/html/sdk/android-2.2.jd delete mode 100644 docs/html/sdk/android-2.3-highlights.jd delete mode 100644 docs/html/sdk/android-2.3.3.jd delete mode 100644 docs/html/sdk/android-2.3.4.jd delete mode 100644 docs/html/sdk/android-2.3.jd delete mode 100644 docs/html/sdk/android-3.0-highlights.jd delete mode 100644 docs/html/sdk/android-3.0.jd delete mode 100644 docs/html/sdk/android-3.1-highlights.jd delete mode 100644 docs/html/sdk/android-3.1.jd delete mode 100644 docs/html/sdk/android-3.2.jd delete mode 100644 docs/html/sdk/android-4.0-highlights.jd delete mode 100644 docs/html/sdk/android-4.0.3.jd delete mode 100644 docs/html/sdk/android-4.0.jd delete mode 100644 docs/html/sdk/compatibility-library.jd delete mode 100644 docs/html/sdk/download.jd delete mode 100644 docs/html/sdk/eclipse-adt.jd create mode 100644 docs/html/sdk/exploring.jd delete mode 100644 docs/html/sdk/images/4.0/contact-call.xcf delete mode 100644 docs/html/sdk/installing.jd create mode 100644 docs/html/sdk/installing/adding-packages.jd create mode 100644 docs/html/sdk/installing/index.jd create mode 100644 docs/html/sdk/installing/installing-adt.jd create mode 100644 docs/html/sdk/installing/next.jd delete mode 100644 docs/html/sdk/ndk/1.5_r1/index.jd delete mode 100644 docs/html/sdk/ndk/1.6_r1/index.jd delete mode 100644 docs/html/sdk/ndk/index.jd delete mode 100644 docs/html/sdk/ndk/overview.jd delete mode 100644 docs/html/sdk/oem-usb.jd delete mode 100644 docs/html/sdk/preview/features.jd delete mode 100644 docs/html/sdk/preview/index.jd delete mode 100644 docs/html/sdk/preview/installing.jd delete mode 100644 docs/html/sdk/preview/requirements.jd delete mode 100644 docs/html/sdk/preview/upgrading.jd delete mode 100644 docs/html/sdk/requirements.jd delete mode 100644 docs/html/sdk/sdk_toc.cs delete mode 100644 docs/html/sdk/terms.jd delete mode 100644 docs/html/sdk/terms_body.html delete mode 100644 docs/html/sdk/tools-notes.jd delete mode 100644 docs/html/search.jd create mode 100644 docs/html/shareables/training/CustomView.zip create mode 100644 docs/html/shareables/training/NetworkUsage.zip create mode 100644 docs/html/shareables/training/OpenGLES.zip create mode 100644 docs/html/support.jd create mode 100644 docs/html/tools/aidl.jd create mode 100644 docs/html/tools/avd.html create mode 100644 docs/html/tools/building/building-cmdline.jd create mode 100644 docs/html/tools/building/building-eclipse.jd create mode 100644 docs/html/tools/building/index.jd create mode 100644 docs/html/tools/debug-tasks.html create mode 100644 docs/html/tools/debugging/ddms.jd create mode 100644 docs/html/tools/debugging/debugging-devtools.jd create mode 100644 docs/html/tools/debugging/debugging-log.jd create mode 100644 docs/html/tools/debugging/debugging-projects-cmdline.jd create mode 100644 docs/html/tools/debugging/debugging-projects.jd create mode 100644 docs/html/tools/debugging/debugging-tracing.jd create mode 100644 docs/html/tools/debugging/debugging-ui.jd create mode 100644 docs/html/tools/debugging/index.jd create mode 100644 docs/html/tools/device.jd create mode 100644 docs/html/tools/devices/emulator.jd create mode 100644 docs/html/tools/devices/index.jd create mode 100644 docs/html/tools/devices/managing-avds-cmdline.jd create mode 100644 docs/html/tools/devices/managing-avds.jd create mode 100644 docs/html/tools/eclipse-adt.html create mode 100644 docs/html/tools/extras/index.jd create mode 100644 docs/html/tools/extras/oem-usb.jd create mode 100644 docs/html/tools/extras/support-library.jd create mode 100644 docs/html/tools/help/MonkeyDevice.jd create mode 100644 docs/html/tools/help/MonkeyImage.jd create mode 100644 docs/html/tools/help/MonkeyRunner.jd create mode 100644 docs/html/tools/help/aapt.html create mode 100644 docs/html/tools/help/adb.jd create mode 100644 docs/html/tools/help/adt.jd create mode 100644 docs/html/tools/help/android.jd create mode 100644 docs/html/tools/help/bmgr.jd create mode 100644 docs/html/tools/help/ddms.html create mode 100644 docs/html/tools/help/dmtracedump.jd create mode 100644 docs/html/tools/help/draw9patch.jd create mode 100644 docs/html/tools/help/emulator.jd create mode 100644 docs/html/tools/help/etc1tool.jd create mode 100644 docs/html/tools/help/hierarchy-viewer.jd create mode 100644 docs/html/tools/help/hprof-conv.jd create mode 100644 docs/html/tools/help/index.jd create mode 100644 docs/html/tools/help/layoutopt.jd create mode 100644 docs/html/tools/help/logcat.jd create mode 100644 docs/html/tools/help/mksdcard.jd create mode 100644 docs/html/tools/help/monkey.jd create mode 100644 docs/html/tools/help/monkeyrunner_concepts.jd create mode 100644 docs/html/tools/help/proguard.jd create mode 100644 docs/html/tools/help/sqlite3.jd create mode 100644 docs/html/tools/help/traceview.jd create mode 100644 docs/html/tools/help/zipalign.jd create mode 100644 docs/html/tools/index.jd create mode 100644 docs/html/tools/other-ide.html create mode 100644 docs/html/tools/othertools.html create mode 100644 docs/html/tools/projects/index.jd create mode 100644 docs/html/tools/projects/projects-cmdline.jd create mode 100644 docs/html/tools/projects/projects-eclipse.jd create mode 100644 docs/html/tools/publishing/app-signing.jd create mode 100644 docs/html/tools/publishing/preparing.jd create mode 100755 docs/html/tools/publishing/publishing_overview.jd create mode 100644 docs/html/tools/publishing/versioning.jd create mode 100644 docs/html/tools/revisions/index.jd create mode 100644 docs/html/tools/revisions/platforms.jd create mode 100644 docs/html/tools/samples/index.jd create mode 100644 docs/html/tools/sdk/OLD_RELEASENOTES.jd create mode 100644 docs/html/tools/sdk/RELEASENOTES.jd create mode 100644 docs/html/tools/sdk/addons.jd create mode 100644 docs/html/tools/sdk/adt-notes.jd create mode 100644 docs/html/tools/sdk/adt_download.html create mode 100644 docs/html/tools/sdk/download.jd create mode 100644 docs/html/tools/sdk/eclipse-adt.jd create mode 100644 docs/html/tools/sdk/images/2.0/camera-modes.png create mode 100644 docs/html/tools/sdk/images/2.0/email-inbox.png create mode 100644 docs/html/tools/sdk/images/2.0/mms-search.png create mode 100644 docs/html/tools/sdk/images/2.0/multiple-accounts.png create mode 100644 docs/html/tools/sdk/images/2.0/quick-connect.png create mode 100644 docs/html/tools/sdk/images/2.2/22browser.png create mode 100644 docs/html/tools/sdk/images/2.2/22exchange.png create mode 100644 docs/html/tools/sdk/images/2.2/22gallery.png create mode 100644 docs/html/tools/sdk/images/2.2/22home.png create mode 100644 docs/html/tools/sdk/images/2.2/22hotspot.png create mode 100644 docs/html/tools/sdk/images/2.2/22keyboard.png create mode 100644 docs/html/tools/sdk/images/2.2/jit-graph.png create mode 100644 docs/html/tools/sdk/images/2.3/ffc.png create mode 100644 docs/html/tools/sdk/images/2.3/home-menu.png create mode 100644 docs/html/tools/sdk/images/2.3/home-plain.png create mode 100644 docs/html/tools/sdk/images/2.3/nfc.png create mode 100644 docs/html/tools/sdk/images/2.3/onetouch.png create mode 100644 docs/html/tools/sdk/images/2.3/power.png create mode 100644 docs/html/tools/sdk/images/2.3/running.png create mode 100644 docs/html/tools/sdk/images/2.3/selection.png create mode 100644 docs/html/tools/sdk/images/2.3/sipcall.png create mode 100644 docs/html/tools/sdk/images/3.0/browser.png create mode 100644 docs/html/tools/sdk/images/3.0/browser_full.png create mode 100644 docs/html/tools/sdk/images/3.0/camera.png create mode 100644 docs/html/tools/sdk/images/3.0/camera_full.png create mode 100644 docs/html/tools/sdk/images/3.0/contacts.png create mode 100644 docs/html/tools/sdk/images/3.0/contacts_full.png create mode 100644 docs/html/tools/sdk/images/3.0/copy.png create mode 100644 docs/html/tools/sdk/images/3.0/copy_full.png create mode 100644 docs/html/tools/sdk/images/3.0/home_hero1.png create mode 100644 docs/html/tools/sdk/images/3.0/home_hero1_full.png create mode 100644 docs/html/tools/sdk/images/3.0/homescreen_cust_port.png create mode 100644 docs/html/tools/sdk/images/3.0/homescreen_cust_port_full.png create mode 100644 docs/html/tools/sdk/images/3.0/mail_drag.png create mode 100644 docs/html/tools/sdk/images/3.0/mail_drag_full.png create mode 100644 docs/html/tools/sdk/images/3.0/tasks.png create mode 100644 docs/html/tools/sdk/images/3.0/tasks_full.png create mode 100644 docs/html/tools/sdk/images/3.0/widgets.png create mode 100644 docs/html/tools/sdk/images/3.1/controls.png create mode 100644 docs/html/tools/sdk/images/3.1/home.png create mode 100644 docs/html/tools/sdk/images/3.1/home_full.png create mode 100644 docs/html/tools/sdk/images/3.1/resizeable.png create mode 100644 docs/html/tools/sdk/images/3.1/tasks.png create mode 100644 docs/html/tools/sdk/images/4.0/allapps-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/allapps.png create mode 100644 docs/html/tools/sdk/images/4.0/bbench.png create mode 100644 docs/html/tools/sdk/images/4.0/beam-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/beam-maps-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/beam-maps.png create mode 100644 docs/html/tools/sdk/images/4.0/beam.png create mode 100644 docs/html/tools/sdk/images/4.0/browser-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/browser-tabs-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/browser-tabs.png create mode 100644 docs/html/tools/sdk/images/4.0/browser.png create mode 100644 docs/html/tools/sdk/images/4.0/calendar-widget-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/calendar-widget.png create mode 100644 docs/html/tools/sdk/images/4.0/camera-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/camera.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-call-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-call.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-call.xcf create mode 100644 docs/html/tools/sdk/images/4.0/contact-connect-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-connect.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-email-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-email.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-faves-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/contact-faves.png create mode 100644 docs/html/tools/sdk/images/4.0/face-unlock-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/face-unlock.png create mode 100644 docs/html/tools/sdk/images/4.0/folders.xcf create mode 100644 docs/html/tools/sdk/images/4.0/gallery-edit-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/gallery-edit.png create mode 100644 docs/html/tools/sdk/images/4.0/gallery-share-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/gallery-share.png create mode 100644 docs/html/tools/sdk/images/4.0/gallery-widget.png create mode 100644 docs/html/tools/sdk/images/4.0/home-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/home.png create mode 100644 docs/html/tools/sdk/images/4.0/live-effects.png create mode 100644 docs/html/tools/sdk/images/4.0/lock-camera-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/lock-camera.png create mode 100644 docs/html/tools/sdk/images/4.0/lock-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/lock.png create mode 100644 docs/html/tools/sdk/images/4.0/quick-responses-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/quick-responses.png create mode 100644 docs/html/tools/sdk/images/4.0/screenshot-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/screenshot.png create mode 100644 docs/html/tools/sdk/images/4.0/tasks-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/tasks.png create mode 100644 docs/html/tools/sdk/images/4.0/text-replace-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/text-replace.png create mode 100644 docs/html/tools/sdk/images/4.0/tts-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/tts.png create mode 100644 docs/html/tools/sdk/images/4.0/usage-all-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/usage-all.png create mode 100644 docs/html/tools/sdk/images/4.0/usage-maps-lg.png create mode 100644 docs/html/tools/sdk/images/4.0/usage-maps.png create mode 100644 docs/html/tools/sdk/images/battery.png create mode 100644 docs/html/tools/sdk/images/camera.png create mode 100644 docs/html/tools/sdk/images/donut_small_bg.png create mode 100644 docs/html/tools/sdk/images/market.png create mode 100644 docs/html/tools/sdk/images/search.png create mode 100644 docs/html/tools/sdk/index.jd create mode 100644 docs/html/tools/sdk/installing.jd create mode 100644 docs/html/tools/sdk/libraries.jd create mode 100644 docs/html/tools/sdk/ndk/1.5_r1/index.jd create mode 100644 docs/html/tools/sdk/ndk/1.6_r1/index.jd create mode 100644 docs/html/tools/sdk/ndk/index.jd create mode 100644 docs/html/tools/sdk/ndk/overview.jd create mode 100644 docs/html/tools/sdk/older_releases.jd create mode 100644 docs/html/tools/sdk/platforms.jd create mode 100644 docs/html/tools/sdk/preview/features.jd create mode 100644 docs/html/tools/sdk/preview/index.jd create mode 100644 docs/html/tools/sdk/preview/installing.jd create mode 100644 docs/html/tools/sdk/preview/requirements.jd create mode 100644 docs/html/tools/sdk/preview/upgrading.jd create mode 100644 docs/html/tools/sdk/tools-notes.jd create mode 100644 docs/html/tools/sdk/usb-drivers.jd create mode 100644 docs/html/tools/sdk/win-usb.jd create mode 100644 docs/html/tools/testing/activity_test.jd create mode 100644 docs/html/tools/testing/activity_testing.jd create mode 100644 docs/html/tools/testing/contentprovider_testing.jd create mode 100644 docs/html/tools/testing/index.jd create mode 100644 docs/html/tools/testing/service_testing.jd create mode 100755 docs/html/tools/testing/testing_android.jd create mode 100644 docs/html/tools/testing/testing_eclipse.jd create mode 100644 docs/html/tools/testing/testing_otheride.jd create mode 100644 docs/html/tools/testing/what_to_test.jd create mode 100644 docs/html/tools/tools_toc.cs create mode 100644 docs/html/tools/workflow.jd create mode 100644 docs/html/tools/workflow/app-signing.jd create mode 100644 docs/html/tools/workflow/index.jd create mode 100644 docs/html/tools/workflow/publishing/app-signing.jd create mode 100644 docs/html/tools/workflow/publishing/preparing.jd create mode 100644 docs/html/tools/workflow/publishing/publishing.jd create mode 100755 docs/html/tools/workflow/publishing/publishing_overview.jd create mode 100644 docs/html/tools/workflow/publishing/versioning.jd create mode 100755 docs/html/tools/workflow/publishing_overview.jd create mode 100644 docs/html/tools/workflow/versioning.jd create mode 100644 docs/html/training/advanced.jd create mode 100644 docs/html/training/basics/network-ops/connecting.jd create mode 100644 docs/html/training/basics/network-ops/index.jd create mode 100644 docs/html/training/basics/network-ops/managing.jd create mode 100644 docs/html/training/basics/network-ops/xml.jd create mode 100644 docs/html/training/custom-views/create-view.jd create mode 100644 docs/html/training/custom-views/custom-drawing.jd create mode 100644 docs/html/training/custom-views/index.jd create mode 100644 docs/html/training/custom-views/making-interactive.jd create mode 100644 docs/html/training/custom-views/optimizing-view.jd create mode 100644 docs/html/training/graphics/opengl/draw.jd create mode 100644 docs/html/training/graphics/opengl/environment.jd create mode 100644 docs/html/training/graphics/opengl/index.jd create mode 100644 docs/html/training/graphics/opengl/motion.jd create mode 100644 docs/html/training/graphics/opengl/projection.jd create mode 100644 docs/html/training/graphics/opengl/shapes.jd create mode 100644 docs/html/training/graphics/opengl/touch.jd create mode 100644 docs/html/training/training_toc.cs delete mode 100644 docs/html/videos/index.jd (limited to 'docs') diff --git a/docs/html/about/about_toc.cs b/docs/html/about/about_toc.cs new file mode 100644 index 000000000000..04cc5a39f661 --- /dev/null +++ b/docs/html/about/about_toc.cs @@ -0,0 +1,44 @@ + \ No newline at end of file diff --git a/docs/html/about/dashboards/index.jd b/docs/html/about/dashboards/index.jd new file mode 100644 index 000000000000..c18d398b22ce --- /dev/null +++ b/docs/html/about/dashboards/index.jd @@ -0,0 +1,235 @@ +page.title=Dashboards +header.hide=1 +@jd:body + + + +

Platform Versions

+ +

This page provides data about the relative number of active devices +running a given version of the Android platform. This can help you +understand the landscape of device distribution and decide how to prioritize +the development of your application features for the devices currently in +the hands of users. For information about how to target your application to devices based on +platform version, read about API levels.

+ + +

Current Distribution

+ +

The following pie chart and table is based on the number of Android devices that have accessed +Google Play within a 14-day period ending on the data collection date noted below.

+ +
+ + + + + + + + + + + + + + + + + + + + + +
VersionCodenameAPI LevelDistribution
1.5Cupcake 30.3%
1.6Donut 40.6%
2.1Eclair 75.2%
2.2Froyo 819.1%
2.3 - 2.3.2 + Gingerbread 90.4%
2.3.3 - 2.3.7 + 1064.6%
3.1Honeycomb 120.7%
3.2132%
4.0 - 4.0.2Ice Cream Sandwich140.4%
4.0.3 - 4.0.4 156.7%
+ + +
+ +
+ + +
+ +

Data collected during a 14-day period ending on June 1, 2012

+ + +

Historical Distribution

+ +

The following stacked line graph provides a history of the relative number of +active Android devices running different versions of the Android platform. It also provides a +valuable perspective of how many devices your application is compatible with, based on the +platform version.

+ +

Notice that the platform versions are stacked on top of each other with the oldest active +version at the top. This format indicates the total percent of active devices that are compatible +with a given version of Android. For example, if you develop your application for +the version that is at the very top of the chart, then your application is +compatible with 100% of active devices (and all future versions), because all Android APIs are +forward compatible. Or, if you develop your application for a version lower on the chart, +then it is currently compatible with the percentage of devices indicated on the y-axis, where the +line for that version meets the y-axis on the right.

+ +

Each dataset in the timeline is based on the number of Android devices that accessed +Google Play within a 14-day period ending on the date indicated on the x-axis.

+ + + +

Last historical dataset collected during a 14-day period ending on June 1, 2012

+ + + + + + + + + + + + + + + + + + + + + + + + +

Screen Sizes and Densities

+ +

This section provides data about the relative number of active devices that have a particular +screen configuration, defined by a combination of screen size and density. To simplify the way that +you design your user interfaces for different screen configurations, Android divides the range of +actual screen sizes and densities into:

+ + + +

For information about how you can support multiple screen configurations in your +application, see Supporting Multiple +Screens.

+ +

Note: This data is based on the number +of Android devices that have accessed Google Play within a 7-day period +ending on the data collection date noted below.

+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ldpimdpihdpixhdpi
small2.3% 2.4%
normal0.7% 26.2% 57.8% 0.9%
large0.3% 2%
xlarge 7.4%
+ + +
+ +
+ + +
+ +

Data collected during a 7-day period ending on May 1, 2012

+ + + + + + + + + + + +

Open GL Version

+ +

This section provides data about the relative number of active devices that support a particular +version of OpenGL ES. Note that support for one particular version of OpenGL ES also implies +support for any lower version (for example, support for version 2.0 also implies support for +1.1).

+ +

To declare which version of OpenGL ES your application requires, you should use the {@code +android:glEsVersion} attribute of the {@code <uses-feature>} +element. You can also use the {@code +<supports-gl-texture>} element to declare the GL compression formats that your application +uses.

+ +

Note: This data is based on the number +of Android devices that have accessed Google Play within a 7-day period +ending on the data collection date noted below.

+ + +
+ + + + + + + + + + + +
OpenGL ES VersionDistribution
1.1 only +9.9%
2.0 & 1.1 +90.1%
+
+ +
+ + +
+ + +

Data collected during a 7-day period ending on June 4, 2012

diff --git a/docs/html/about/flexible.jd b/docs/html/about/flexible.jd new file mode 100644 index 000000000000..ec3a44ccd2a2 --- /dev/null +++ b/docs/html/about/flexible.jd @@ -0,0 +1,34 @@ +page.title=Flexible Framework +walkthru=1 + +@jd:body + + + +
Android's flexible framework means it runs on more devices and reaches more +users
+ +

Android powers millions of devices around the world and in a variety of form-factors. The Android +framework is specially built to run apps on more than just one screen size and hardware +configuration. As an app developer, Android's scale and variety offers you the potential to quickly +reach millions of users.

+ +

Android apps are flexible and easily adapt to the device on which they are running. Although the +system scales your assets when necessary, you can provide alternative app resources that are +optimized for specific device categories, such as the screen size and density. Android applies the +appropriate resources when running your app, based on the current device’s configuration.

+ +
You're in control of which devices can install your app
+ +

Some devices provide a different user experience when using apps, but you’re always in control of +how your app behaves on each device. If you publish your app on Google Play, you also have +control over which kinds of devices are allowed to install your app and you can closely control how +your app is distributed.

+ +

Every device that includes Google Play has been certified compatible. This means that +the device has passed a rigorous test suite to ensure that the device uses a version of Android that +supports all the platform APIs and will successfully run your app.

\ No newline at end of file diff --git a/docs/html/about/index.jd b/docs/html/about/index.jd new file mode 100644 index 000000000000..c2d642628c71 --- /dev/null +++ b/docs/html/about/index.jd @@ -0,0 +1,157 @@ +page.title=Android, the world's most popular mobile platform +walkthru=0 +header.hide=0 + +@jd:body + +
+

Android powers hundreds of millions of mobile devices in more than 190 +countries around the world. It's the largest installed base of any mobile platform +and growing fast—every day another 900,000 users power up their +Android devices for the first time and start looking for apps, games, +and other digital content.

+ +
+

Android gives you a world-class platform for creating apps and games for +Android users everywhere, as well as an open marketplace for distributing +to them instantly.

+
+
+ + +
+ Android growth in device activations
+ + +

Global partnerships and large installed base

+ +

Building on the contributions of the open-source Linux community and more +than 300 hardware, software, and carrier partners, Android has rapidly become +the fastest-growing mobile OS.

+ +
Every day more than 900,000 new Android devices are activated worldwide.
+ +

Android’s openness has made it a favorite for consumers and developers alike, +driving strong growth in app consumption. Android users download more than +1 billion apps and games from Google Play each month.

+ +

With it's partners, Android is continuously pushing the boundaries of hardware and software +forward to bring new capabilities to users and developers. For developers, +Android innovation lets you build powerful, differentiated applications +that use the latest mobile technologies.

+ + + +

Powerful development framework

+ +
Easily optimize a single binary for phones, tablets, and other devices.
+ +

Android gives you everything you need to build best-in-class app experiences. +It gives you a single application model that lets you deploy +your apps broadly to hundreds of millions of users across a wide range of +devices—from phones to tablets and beyond.

+ +

Android also gives you tools for creating apps that look great and take +advantage of the hardware capabilities available on each device. It +automatically adapts your UI to look it's best on each device, while giving you +as much control as you want over your UI on different device +types.

+ +

For example, you can create a single app binary that's optimized for +both phone and tablet form factors. You declare your UI in lightweight sets of XML +resources, one set for parts of the UI that are common to all form factors and +other sets for optimzations specific to phones or tablets. +At runtime, Android applies the correct resource sets based on its screen size, +density, locale, +and so on.

+ + +

To help you develop efficiently, the Android + Developer Tools +offers a full Java IDE with advanced features for developing, debugging, and +packaging Android apps. Using the IDE, you can develop on any available Android +device or create virtual devices that emulate any hardware configuration.

+ +
A billion downloads a month and growing. Get your apps in front +of millions of users at Google's scale.
+ +

Open marketplace for distributing your apps

+ +

Google Play is the premier marketplace for selling and distributing Android apps. +When you publish an app on Google Play, you reach the huge installed base of +Android.

+ +
+ +
+ +

As an open marketplace, Google Play puts you in control of how you sell your +products. You can publish whenever you want, as often as you want, and to the +customers you want. You can distribute broadly to all markets and +devices or focus on specific segments, devices, or ranges of hardware +capabilities.

+ +

You can monetize in the way that works best for your business—priced or +free, with in-app products or subscriptions—for highest engagement and +revenues. You also have complete control of the pricing for your apps +and in-app products and can set or change prices in any supported currency at +any time.

+ +

Beyond growing your customer base, Google Play helps you build visibility and +engagement across your apps and brand. As your apps rise in popularity, Google +Play gives them higher placement in weekly "top" charts and rankings, and for +the best apps promotional slots in curated collections. +

+ +

Preinstalled on hundreds of millions of Android devices around the world, +Google Play can be a growth engine for your business.

+ +

GET STARTED

+ +
+
+

Developer Story: Robot Invader

+ +
+

Robot Invader chose + Android as the launch platform for their first game, + Wind-up + Knight. +

+

+ Hear from the developers themselves how Android helped them reach more + than 100 devices with a single app binary, then iterate rapidly to ensure + a great experience for users. +

+
+ +
+
\ No newline at end of file diff --git a/docs/html/about/marketplace.jd b/docs/html/about/marketplace.jd new file mode 100644 index 000000000000..34f57a5588b5 --- /dev/null +++ b/docs/html/about/marketplace.jd @@ -0,0 +1,62 @@ +page.title=Open Marketplace +walkthru=1 + +@jd:body + + + +

Android offers an open distribution model, not a walled garden. Once you’ve developed an +app for Android and want to distribute it, you have choice.

+ +

Your final application is contained in an APK file that you can make available to users any +way you want. For example, you can upload it to your own web site to allow visitors to +install it onto their devices. More often, you’ll want to use a trusted +marketplace where users can discover and search for your apps.

+ +

How you choose to distribute your app affects precisely how many users your app will reach. Which +distribution provider you choose also affects the kinds of services available to you as a publisher, +such as licensing and in-app billing APIs, user bug reports, installation analytics, marketing +services, and more.

+ +

Among your choices is Google Play, the premier marketplace for selling and distributing apps +to Android users around the world. When you publish an app on Google Play, you reach hundreds of +millions of customers in over 130 countries.

+ + +

Your business, your customers

+ +
Google Play makes your apps available to your customers +immediately
+ +

As an open marketplace, Google Play puts you in control of your business and makes it easy for +you to manage how you sell your products. You can publish whenever you want, as often as you want, +and to the exact set of customers you want.

+ + +

Visibility for your apps

+ +

Beyond growing your customer base, Google Play helps you build visibility and engagement across +your apps and brand. As your apps rise in popularity, Google Play gives you higher placement in +weekly "top" lists and offers promotional slots in curated collections. You can engage customers +using rich, colorful product pages that feature app screenshots, videos, and user reviews, as well +as cross-marketing links to your other products.

+ +

Flexible monetizing and distribution

+ +
You can distribute +your apps free or priced and you can sell in-app products for additional revenue
+ +

Google Play offers a choice of monetizing options to meet your business needs. You control the +pricing of your apps and in-app products—you can set and change prices at any time, even +individually in local currencies around the world. On purchase, Google Play handles transactions in +the buyer’s currency and makes payouts in your own currency.

+ + +

After publishing, you can manage the distribution of your app. You can distribute broadly to all +markets and devices or focus on specific segments, devices, or ranges of hardware capabilities. +Google Play provides the tools for controlling distribution and ensures that your app is available +only to the users who you are targeting.

diff --git a/docs/html/about/start.jd b/docs/html/about/start.jd new file mode 100644 index 000000000000..af8344d0bb72 --- /dev/null +++ b/docs/html/about/start.jd @@ -0,0 +1,63 @@ +page.title=Get Started +walkthru=0 + +@jd:body + +

Everything you need to start developing apps for Android is available here on +developer.android.com. You'll find everything from the developer SDK, API documentation, and design +guidelines, to information about the current device landscape and how you can distribute and +monetize your app.

+ +

No two apps are built in the same way, but we've structured the information you need to build an +app into the following three sections that represent the general order for app development. + + + + +

+

1. Design

+ +

Before you write a single line of code, you need to design the user interface and make it fit +the Android user experience. Although you may know what a user will do with your app, you +should pause to focus on how a user will interact with it. Your design should be sleek, +simple, powereful, and tailored to the Android experience.

+ +

So whether your a one-man shop or a large team, you should study the Design guidelines first.

+
+ +
+

2. Develop

+

Once your design is finalized, all you need are the tools to turn your app ideas into reality. +Android's framework provides you the APIs to build apps that take full advantage of +device hardware, connected accessory devices, the Internet, software features, and more. +With the power of Android, there's no limit to the power of your apps.

+ +

Everything you need to learn about the app framework and developer tools is in the Develop documentation.

+ +
+ + +
+

3. Distribute

+

Now your app is complete. You've built it to support a variety of screen sizes and +densities, and tested it on the Android emulator and on real devices. You're ready to ship your app.

+ +

How you proceed depends on a variety of factors, such as your monetization strategy and which +types of devices your app supports. Everything you need to get started with this process is +available in the Distribute section.

+
+ + +

Now that you know what's available, get started by installing the Android SDK.

\ No newline at end of file diff --git a/docs/html/about/versions/android-1.1.jd b/docs/html/about/versions/android-1.1.jd new file mode 100644 index 000000000000..b61f18615c75 --- /dev/null +++ b/docs/html/about/versions/android-1.1.jd @@ -0,0 +1,246 @@ +page.title=Android 1.1 Version Notes +sdk.version=1.1_r1 +sys.date=February 2009 +@jd:body + +

+Date: February 2009
+API Level: 2

+ + +

This document provides version notes for the Android 1.1 system image included in the SDK. + +

+ +

Overview

+ +

The Android 1.1 system image delivered in the SDK is the development +counterpart to the Android 1.1 production system image, deployable to +Android-powered handsets starting in February 2009.

+ +

The Android 1.1 system image delivers an updated version of the framework +API. As with the Android 1.0 API, the Android 1.1 API +is assigned an integer identifier — 2 — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

+ +

Applications indicate the lowest system API Level that they are compatible with by adding +a value to the android:minSdkVersion attribute. +The value of the attribute is an integer corresponding to an API Level +identifier. Prior to installing an application, the system checks the value of +android:minSdkVersion and allows the install only +if the referenced integer is less than or equal to the API Level integer stored +in the system itself.

+ +

If you use the Android 1.1 system image to build an application +compatible with Android-powered devices running the Android 1.1 +platform, you must set the +android:minSdkVersion attribute to "2" in order to specify that your application +is compatible only with devices using the Android 1.1 (or greater) system image. +

+ +

Specifically, you specify the android:minSdkVersion +attribute in a <uses-sdk> element as a child of +<manifest> in the manifest file. When set, the +attribute looks like this:

+ +
<manifest>
+  ...
+  <uses-sdk android:minSdkVersion="2" />
+  ...
+</manifest>
+
+ +

By setting android:minSdkVersion in this way, you ensure +that users will only be able to install your application if their +devices are running the Android 1.1 platform. In turn, this ensures that +your application will function properly on their devices, especially if +it uses APIs introduced in Android 1.1.

+ +

If your application uses APIs introduced in Android 1.1 but does not +declare <uses-sdk android:minSdkVersion="2" />, then it will +run properly on Android 1.1 devices but not on Android 1.0 +devices. In the latter case, the application will crash at runtime when +it tries to use the Android 1.1 APIs.

+ +

If your application does not use any new APIs introduced in Android +1.1, you can indicate Android 1.0 compatibility by removing +android:minSdkVersion or setting the attribute to "1". However, +before publishing your application, you must make sure to compile your +application against the Android 1.0 system image (available in the +Android 1.0 SDK), to ensure that it builds and functions properly for +Android 1.0 devices. You should test the application against system +images corresponding to the API Levels that the application is designed +to be compatible with.

+ +

If you are sure your application is not using Android 1.1 APIs and +has no need to use them, you might find it easier to keep working in the +Android 1.0 SDK, rather than migrating to the Android 1.1 SDK and having +to do additional testing.

+ + +

External Libraries

+ +

The system image includes these external libraries, which you can +access from your application by adding a +<uses-library>.

+ + +

Device Compatibility

+ +

The Android 1.1 system image was tested for compatability with the +Android-powered devices listed below:

+ + +

Built-in Applications

+ +

The system image includes these built-in applications:

+ + +

UI Localizations

+ +

The system image provides localized UI strings for the languages +listed below.

+ + +

Localized UI strings match the locales that are displayable in +the emulator, accessible through the device Settings application.

+ +

Resolved Issues

+ + +

New Features

+ + + +

API Changes

+ +

Overview

+ + + +

API Change Details

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Module or FeatureChange Description
Annotations for test systems
Added {@link android.test.suitebuilder.annotation.LargeTest LargeTest} annotation.
Added {@link android.test.suitebuilder.annotation.MediumTest MediumTest} annotation.
Added {@link android.test.suitebuilder.annotation.SmallTest SmallTest} annotation.
Allow a process to easily know its UID.
Added public method {@link android.os.Process#myUid} to class {@link android.os.Process android.os.Process}
Padding in views
Added public method {@link android.view.View#getBottomPaddingOffset} to class {@link android.view.View android.view.View}.
Added public method {@link android.view.View#getLeftPaddingOffset} to class {@link android.view.View android.view.View}.
Added public method {@link android.view.View#getRightPaddingOffset} to class {@link android.view.View android.view.View}.
Added public method {@link android.view.View#getTopPaddingOffset} to class {@link android.view.View android.view.View}.
Added public method {@link android.view.View#isPaddingOffsetRequired} to class {@link android.view.View android.view.View}.
Marquee support
Added public method {@link android.widget.TextView#setMarqueeRepeatLimit} to class {@link android.widget.TextView}
Added public field {@link android.R.attr#marqueeRepeatLimit android.R.attr.marqueeRepeatLimit}
New permissions
Added public field {@link android.Manifest.permission#BROADCAST_SMS android.Manifest.permission.BROADCAST_SMS}
Added public field {@link android.Manifest.permission#BROADCAST_WAP_PUSH android.Manifest.permission.BROADCAST_WAP_PUSH}
API cleanup
Removed protected constructor java.net.ServerSocket.ServerSocket(java.net.SocketImpl).
+ + + + + + diff --git a/docs/html/about/versions/android-1.5-highlights.jd b/docs/html/about/versions/android-1.5-highlights.jd new file mode 100644 index 000000000000..ff64e8c28cf9 --- /dev/null +++ b/docs/html/about/versions/android-1.5-highlights.jd @@ -0,0 +1,208 @@ +page.title=Android 1.5 Platform Highlights +@jd:body + +

+April 2009 +

+ + +

The Android 1.5 platform introduces many new features for users and developers. +The list below provides an overview of the changes.

+ + + +

User Interface Refinements

+ + +

Performance Improvements

+ + + +

New Features

+ + + +

New APIs and Manifest Elements

+ + diff --git a/docs/html/about/versions/android-1.5.jd b/docs/html/about/versions/android-1.5.jd new file mode 100644 index 000000000000..78dcbd761040 --- /dev/null +++ b/docs/html/about/versions/android-1.5.jd @@ -0,0 +1,375 @@ +page.title=Android 1.5 Platform +sdk.platform.version=1.5 +sdk.platform.apiLevel=3 +sdk.platform.majorMinor=major + +@jd:body + +
+ +
+ +

+API Level: {@sdkPlatformApiLevel}

+ +

Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in May 2009. +The release includes new features for users and developers, as well as changes +in the Android framework API.

+ +

For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform is fully +compliant and includes no external libraries.

+ +

To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your Android 1.6 or later SDK. For more information, +see Exploring the +SDK.

+ + +

Platform Highlights

+ +

For a list of new user features and platform highlights, see the Android +{@sdkPlatformVersion} Platform Highlights document.

+ +

Revisions

+ +

The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

+ + + + +
+ + + Android 1.5, Revision 4 (May 2010) +
+
+
Dependencies:
+
+

Requires SDK Tools r6 or higher.

+
+ +
Tools:
+
+
    +
  • Adds support for library projects in the Ant build system.
  • +
  • Fixes test project build in the Ant build system.
  • +
+
+ +
+
+
+ +
+ + + Android 1.5, Revision 3 (July 2009) +
+
+
Dependencies:
+
+

Requires SDK Tools r3 or higher.

+
+
+
+
+ +
+ + + Android 1.5, Revision 2 (May 2009) +
+

Not available as an SDK component — please use Android 1.5, r3 instead.

+
+
+ +
+ + + Android 1.5, Revision 1 (April 2009) +
+

Not available as an SDK component — please use Android 1.5, r3 instead.

+
+
+ + +

API Level

+ +

The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

+ +

To use APIs introduced in Android {@sdkPlatformVersion} in your +application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the +android:minSdkVersion attributes of the <uses-sdk> +element in your application's manifest.

+ +

For more information about how to use API Level, see the API Levels document.

+ + +

Framework API Changes

+ +

The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.

+ +

UI framework

+ + +

AppWidget framework

+ + +

Media framework

+ + +

Input Method framework

+ + +

Application-defined hardware requirements

+ +

Applications can now use a new element in their manifest files, <uses-configuration> + to indicate to the Android system what hardware features +they require in order to function properly. For example, an application might +use the element to specify that it requires a physical keyboard or a particular +navigation device, such as a trackball. Prior to installing the application, the +Android system checks the attributes defined for the +<uses-configuration> element and allows the installation to +continue only if the required hardware is present.

+ +

Speech recognition framework

+ + +

Miscellaneous API additions

+ + + +

API differences report

+ +

For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +the previous version, see the API +Differences Report.

+ + +

Built-in Applications

+ +

The system image included in the downloadable platform provides these +built-in applications:

+ + + + + + +
+
    +
  • Alarm Clock
  • +
  • Browser
  • +
  • Calculator
  • +
  • Camcorder
  • +
  • Camera
  • +
  • Contacts
  • +
  • Custom Locale (developer app)
  • +
  • Dev Tools (developer app)
  • +
+
+
    +
  • Dialer
  • +
  • Email
  • +
  • Gallery
  • +
  • IME for Japanese text input
  • +
  • Messaging
  • +
  • Music
  • +
  • Settings
  • +
  • Spare Parts (developer app)
  • +
+
+ +

Locales

+ +

The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region +locale descriptor).

+ + + + + + +
+
    +
  • Chinese, PRC (zh_CN)
  • +
  • Chinese, Taiwan (zh_TW)
  • +
  • Czech (cs_CZ)
  • +
  • Dutch, Netherlands (nl_NL)
  • +
  • Dutch, Belgium (nl_BE)
  • +
  • English, US (en_US)
  • +
  • English, Britain (en_GB)
  • +
  • English, Canada (en_CA)
  • +
  • English, Australia (en_AU)
  • +
  • English, New Zealand (en_NZ)
  • +
  • English, Singapore(en_SG)
  • +
  • French, France (fr_FR)
  • +
  • French, Belgium (fr_BE)
  • +
+
+
  • French, Canada (fr_CA)
  • +
  • French, Switzerland (fr_CH)
  • +
  • German, Germany (de_DE)
  • +
  • German, Austria (de_AT)
  • +
  • German, Switzerland (de_CH)
  • +
  • German, Liechtenstein (de_LI)
  • +
  • Italian, Italy (it_IT)
  • +
  • Italian, Switzerland (it_CH)
  • +
  • Japanese (ja_JP)
  • +
  • Korean (ko_KR)
  • +
  • Polish (pl_PL)
  • +
  • Russian (ru_RU)
  • +
  • Spanish (es_ES)
  • +
    + +

    Localized UI strings match the locales that are accessible +through Settings.

    + +

    Emulator Skins

    + +

    The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

    + + + +

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    diff --git a/docs/html/about/versions/android-1.6-highlights.jd b/docs/html/about/versions/android-1.6-highlights.jd new file mode 100644 index 000000000000..2ee1d807029b --- /dev/null +++ b/docs/html/about/versions/android-1.6-highlights.jd @@ -0,0 +1,213 @@ +page.title=Android 1.6 Platform Highlights +sdk.date=September 2009 + +@jd:body + + + + +
    + + + + + +
    + + +

    The Android 1.6 platform introduces new features for users and developers. +This page provides an overview of some new features and technologies.

    + + + + + +

    New User Features

    + + + +
    +
    +Quick Search Box +
    + +
    +
    +New Camera/Camcorder UI +
    + +
    +
    +Battery Usage Indicator +
    + + +

    Quick Search Box for Android

    + +

    Android 1.6 includes a redesigned search framework that provides a quick, +effective, and consistent way for users to search across multiple sources—such as +browser bookmarks & history, contacts, and the web—directly from +the home screen.

    + +

    The system constantly learns which search results are more relevant based on what is +clicked. So popular contacts or apps that have previously been picked will bubble up to +the top when a user types the first few letters of a relevant query.

    + +

    The search framework also provides developers a way to easily expose relevant +content from their applications in Quick Search Box.

    + +

    Camera, Camcorder, and Gallery

    + +

    An updated user interface provides an integrated camera, camcorder, and gallery experience. +Users can quickly toggle between still and video capture modes. Additionally, the gallery +enables users to select multiple photos for deletion.

    + +

    Android 1.6 also provides a much faster camera experience. +Compared to the previous release, launching the camera is now 39% faster, +and there is a 28% improvement in the time from completing one shot to the next.

    + + +

    VPN, 802.1x

    + +

    A new Virtual Private Network (VPN) control panel in Settings allows users +to configure and connect to the following types of VPNs:

    + + + + +

    Battery usage indicator

    + +

    A new battery usage screen lets users see which apps and services are consuming +battery power. If the user determines that a particular service or application is +using too much power, they can take action to save the battery by +adjusting settings, stopping the application, or uninstalling the application.

    + + +

    Accessibility

    + +

    Users will be able to download new accessibility services built +on the new accessibility framework and enable them in Settings.

    + + + + +

    Google Play Updates

    + +
    +
    +New Google Play UI +
    + +

    For devices with Google Play, the latest version improves the overall user experience and makes +it easier for users to discover great apps and games from developers.

    + + + + + + +

    New Platform Technologies

    + +

    Expanded Search Framework

    + +

    The Android search framework has been redesigned and expanded to provide +third-party applications the opportunity to surface +content from their applications in Quick Search Box, the global search tool. +To do this, developers will need to make their app "searchable" and provide +suggestions in response to user queries. +To enable application search suggestions, users simply select each application from which +they'd like to receive suggestions, under Searchable items in the Search settings.

    + + +

    Text-to-speech engine

    + +

    Android 1.6 features a multi-lingual speech synthesis engine called Pico. +It allows any Android application to "speak" a string of text with an accent that matches the language. +The engine supports the following languages: English (American and British accents), French, +Italian, German and Spanish. If you're using a T-Mobile G1 or Dream device, you'll need to download the +SpeechSynthesis Data Installer from Google Play, which includes the "voices" needed by the +text-to-speech engine.

    + + +

    Gestures

    + +

    A new gestures framework provides application developers with a framework for creating, storing, +loading, and recognizing gestures and associating them with specific actions.

    + +

    Developers can use the new GestureBuilder tool included in the Android 1.6 SDK to generate libraries +of gestures to include with their application.

    + + +

    Accessibility

    + +

    Android 1.6 provides a new accessibility framework. +With this framework, developers can create accessibility plugins that respond to user input, +such as making a sound when a new window is shown, vibrating when navigating to the top of +a list, and providing spoken feedback.

    + + +

    Expanded support for screen densities and resolutions

    + +

    Android 1.6 adds screen support that enables applications to be rendered properly on different +display resolutions and densities. Developers can also specify the types of screens supported by their +application.

    + + +

    Telephony support for CDMA

    + +

    Android 1.6 includes support for CDMA in the telephony stack.

    + + +

    New version of OpenCore

    + +

    Android 1.6 includes the updated OpenCore 2 media engine, which has:

    + + + +

    2.6.29 Linux kernel

    + +

    Android 1.6 upgrades the Linux kernel from 2.6.27 to 2.6.29.

    + + +

    New Framework APIs

    + +

    For a detailed overview of new APIs, see the +Version Notes. +For a complete report of all API changes, see the +API Differences Report. diff --git a/docs/html/about/versions/android-1.6.jd b/docs/html/about/versions/android-1.6.jd new file mode 100644 index 000000000000..2a66cd3e7e5a --- /dev/null +++ b/docs/html/about/versions/android-1.6.jd @@ -0,0 +1,505 @@ +page.title=Android 1.6 Platform +sdk.platform.version=1.6 +sdk.platform.apiLevel=4 +sdk.platform.majorMinor=minor + +@jd:body + +

    + +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets since October 2009. +The platform includes new features for users and developers, as well as changes +in the Android framework API.

    + +

    For developers, a new release of the Android {@sdkPlatformVersion} platform +is available as a downloadable component for the Android SDK. The platform +— Android 1.6 r2 — includes a fully compliant Android library and +system image, as well as a set of emulator skins, sample applications, and minor +development updates. The downloadable platform is fully compliant (API Level 4) +and includes no external libraries.

    + +

    To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the latest Android 1.6 platform into your Android 1.6 or later SDK. For +more information, see Exploring the +SDK.

    + + +

    Platform Highlights

    + +

    For a list of new user features and platform highlights, see the Android +{@sdkPlatformVersion} Platform Highlights document.

    + + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

    + + + + +
    + + + Android 1.6, Revision 3 (May 2010) +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r6 or higher.

    +
    +
    Tools:
    +
    +
      +
    • Adds support for library projects in the Ant build system.
    • +
    +
    +
    +
    +
    + +
    + + + Android 1.6, Revision 2 (December 2009) +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r4 or higher.

    +
    + +
    API related:
    +
    +
      +
    • Properly exposes CDMA-related constants in android.telephony.TelephonyManager: DATA_ACTIVITY_DORMANT, +PHONE_TYPE_CDMA, NETWORK_TYPE_CDMA, +NETWORK_TYPE_EVDO_0, NETWORK_TYPE_EVDO_A, and +NETWORK_TYPE_1xRTT.
    • +
    +
    +
    System image:
    +
    +
      +
    • Fixes bug so that Bitmap's density is now propagated through Parcelable.
    • +
    • Fixes NinePatchDrawable to properly scale its reported padding for compatibility mode.
    • +
    • Fixes TextView to properly compute styled font metrics based on the screen density.
    • +
    • Updates kernel to 2.6.29, to match kernel on commercially +available Android-powered devices.
    • +
    +
    +
    Tools:
    +
    +
      +
    • Adds new Ant build system with support for Emma instrumentation projects +(code coverage).
    • +
    • Fixes emulator skins to properly emulate d-pad in landscape mode.
    • +
    • Fixes density rendering in the layout editor in ADT.
    • +
    +
    +
    +
    +
    + +
    + + + Android 1.6, Revision 1 (September 2009) +
    +
    +
    Dependencies
    +
    +

    Requires SDK Tools r3 or higher.

    +
    +
    +
    +
    + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your +application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the +android:minSdkVersion attributes of the <uses-sdk> +element in your application's manifest.

    + +

    For more information about how to use API Level, see the API Levels document.

    + + +

    Framework API Changes

    + +

    The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.

    + +

    UI framework

    + + +

    Search framework

    + + +

    Accessibility framework

    + + +

    Gesture input

    + + +

    Text-to-speech

    + + +

    Graphics

    + + +

    Telephony

    + + +

    Utilities

    + + +

    Android Manifest elements

    + + + +

    New permissions

    + + + + +

    API differences report

    + +

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +the previous version, see the API +Differences Report.

    + +

    Built-in Applications

    + +

    The system image included in the downloadable platform provides these +built-in applications:

    + + + + + + +
    +
      +
    • Alarm Clock
    • +
    • Browser
    • +
    • Calculator
    • +
    • Camcorder
    • +
    • Camera
    • +
    • Contacts
    • +
    • Custom Locale (developer app)
    • +
    • Dev Tools (developer app)
    • +
    • Dialer
    • +
    +
    +
      +
    • Email
    • +
    • Gallery
    • +
    • Gestures Builder
    • +
    • IME for Japanese text input
    • +
    • Messaging
    • +
    • Music
    • +
    • Settings
    • +
    • Spare Parts (developer app)
    • +
    +
    + +

    Locales

    + +

    The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region +locale descriptor).

    + + + + + + +
    +
      +
    • Chinese, PRC (zh_CN)
    • +
    • Chinese, Taiwan (zh_TW)
    • +
    • Czech (cs_CZ)
    • +
    • Dutch, Netherlands (nl_NL)
    • +
    • Dutch, Belgium (nl_BE)
    • +
    • English, US (en_US)
    • +
    • English, Britain (en_GB)
    • +
    • English, Canada (en_CA)
    • +
    • English, Australia (en_AU)
    • +
    • English, New Zealand (en_NZ)
    • +
    • English, Singapore(en_SG)
    • +
    • French, France (fr_FR)
    • +
    • French, Belgium (fr_BE)
    • +
    +
    +
  • French, Canada (fr_CA)
  • +
  • French, Switzerland (fr_CH)
  • +
  • German, Germany (de_DE)
  • +
  • German, Austria (de_AT)
  • +
  • German, Switzerland (de_CH)
  • +
  • German, Liechtenstein (de_LI)
  • +
  • Italian, Italy (it_IT)
  • +
  • Italian, Switzerland (it_CH)
  • +
  • Japanese (ja_JP)
  • +
  • Korean (ko_KR)
  • +
  • Polish (pl_PL)
  • +
  • Russian (ru_RU)
  • +
  • Spanish (es_ES)
  • +
    + +

    Localized UI strings match the locales that are accessible +through Settings.

    + +

    Emulator Skins

    + +

    The downloadable platform includes a set of emulator skins that you can +use for modeling your application in different screen sizes and resolutions. +The emulator skins are:

    + + + +

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    diff --git a/docs/html/about/versions/android-2.0-highlights.jd b/docs/html/about/versions/android-2.0-highlights.jd new file mode 100644 index 000000000000..2ba9ac76f6f9 --- /dev/null +++ b/docs/html/about/versions/android-2.0-highlights.jd @@ -0,0 +1,201 @@ +page.title=Android 2.0 Platform Highlights +sdk.date=October 2009 + +@jd:body + + + + +
    + + + + + +
    + + +

    The Android 2.0 platform introduces many new and exciting features for +users and developers. This document provides a glimpse at some of the new features +and technologies in Android 2.0.

    + + + + + +

    New User Features

    + + + +
    +
    + Quick Contact for Android +
    + +
    +
    + Multiple Accounts +
    + +
    +
    + Messaging Search +
    + +
    +
    + Email Combined Inbox +
    + +
    +
    + Camera Modes +
    + + + +

    Contacts and accounts

    + + + + + + +

    Email

    + + + + +

    Messaging

    + + + + +

    Camera

    + + + +

    Android virtual keyboard

    + + + + +

    Browser

    + + + + +

    Calendar

    + + + +

    New Platform Technologies

    + +

    Media Framework

    + +

    Revamped graphics architecture for improved performance that enables better +hardware acceleration.

    + + +

    Bluetooth

    + + + + +

    New Framework APIs

    + +

    Android 2.0 includes several new developer APIs. +For an overview of new APIs, see the +Android 2.0 version notes.

    + +

    For a complete report of all API changes, see the +API Differences Report.

    + + + diff --git a/docs/html/about/versions/android-2.0.1.jd b/docs/html/about/versions/android-2.0.1.jd new file mode 100644 index 000000000000..bcba7177b684 --- /dev/null +++ b/docs/html/about/versions/android-2.0.1.jd @@ -0,0 +1,361 @@ +page.title=Android 2.0.1, Release 1 +sdk.platform.version=2.0.1 +sdk.platform.apiLevel=6 +sdk.platform.majorMinor=minor + +@jd:body + +
    + +
    + +

    + +API Level: {@sdkPlatformApiLevel}

    + +

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in December 2009. +This release includes minor API +changes, bug fixes and framework behavioral changes. For information on changes +and fixes, see the Framework API section.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform +includes no external libraries.

    + +

    To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your Android 1.6 or later SDK. For more information, +see Exploring the +SDK.

    + + +

    Platform Highlights

    + +

    For a list of new user features and platform highlights, see the Android +2.0 Platform Highlights document.

    + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

    + + + + +
    + + + Android 2.0.1, Revision 1 (December 2009) +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r4 or higher.

    +
    +
    +
    +
    + +

    Built-in Applications

    + +

    The system image included in the downloadable platform provides these +built-in applications:

    + + + + + + +
    +
      +
    • Alarm Clock
    • +
    • Browser
    • +
    • Calculator
    • +
    • Camcorder
    • +
    • Camera
    • +
    • Contacts
    • +
    • Custom Locale (developer app)
    • +
    • Dev Tools (developer app)
    • +
    • Dialer
    • +
    +
    +
      +
    • Email
    • +
    • Gallery
    • +
    • Gestures Builder
    • +
    • IME for Japanese text input
    • +
    • Messaging
    • +
    • Music
    • +
    • Settings
    • +
    • Spare Parts (developer app)
    • +
    +
    + +

    New with 2.0.1 The Dev Tools app now +includes a "Sync Tester" application to provide quick and easy testing of +third-party sync adapters.

    + +

    Locales

    + +

    The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region locale +descriptor).

    + + + + + + +
    +
      +
    • Chinese, PRC (zh_CN)
    • +
    • Chinese, Taiwan (zh_TW)
    • +
    • Czech (cs_CZ)
    • +
    • Dutch, Netherlands (nl_NL)
    • +
    • Dutch, Belgium (nl_BE)
    • +
    • English, US (en_US)
    • +
    • English, Britain (en_GB)
    • +
    • English, Canada (en_CA)
    • +
    • English, Australia (en_AU)
    • +
    • English, New Zealand (en_NZ)
    • +
    • English, Singapore(en_SG)
    • +
    • French, France (fr_FR)
    • +
    • French, Belgium (fr_BE)
    • +
    +
    +
  • French, Canada (fr_CA)
  • +
  • French, Switzerland (fr_CH)
  • +
  • German, Germany (de_DE)
  • +
  • German, Austria (de_AT)
  • +
  • German, Switzerland (de_CH)
  • +
  • German, Liechtenstein (de_LI)
  • +
  • Italian, Italy (it_IT)
  • +
  • Italian, Switzerland (it_CH)
  • +
  • Japanese (ja_JP)
  • +
  • Korean (ko_KR)
  • +
  • Polish (pl_PL)
  • +
  • Russian (ru_RU)
  • +
  • Spanish (es_ES)
  • +
    + +

    Localized UI strings match the locales that are accessible +through Settings.

    + +

    Emulator Skins

    + +

    The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

    + + + +

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    + +

    Developer Features

    + +

    The sections below provide information about new developer features offered by the downloadable Android 2.0 platform component.

    + +

    Ant Support

    + + + +

    Framework API

    + +

    The sections below provide information about changes made to the application +framework API provided by the Android {@sdkPlatformVersion} platform. Note, +however, that Android 2.0.1 is a minor release to Android 2.0, so for more +information about the changes made to in Android 2.0, please refer to the +Android 2.0 version notes.

    + + +

    API level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of the framework +API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — {@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to +set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk> +element in your application's manifest.

    + +

    For more information about how to use API Level, see the API Levels document.

    + + +

    API changes summary

    + +

    The following is a summary of changes to the framework APIs.

    + + + +

    Behavior changes

    + +

    The following is a summary of changes that affect the behavior of some +framework APIs but do not add or remove API functionality.

    + +

    Bluetooth

    + +

    Changes to the values returned by {@link +android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} and +{@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE}:

    + + + +

    Contacts

    + +

    The {@link android.content.Intent#ACTION_INSERT} Intent now returns {@link +android.app.Activity#RESULT_CANCELED} in cases where the contact was not +persisted (for example, if the save was trimmed to a no-op).

    + + +

    Bug fixes

    + +

    The following is a summary of bug fixes that affect some framework APIs.

    + +

    Resources

    + +

    The framework now correctly selects application resources in project +folders that use the API Level qualifier. For example, {@code drawable-v4/} is a +folder of drawable resources for API Level 4 (or higher) devices. This version +matching did not work properly and has been fixed.

    + +

    Contacts

    + +

    The {@link android.content.Intent#ACTION_INSERT} Intent now returns the +appropriate kind of URI when the request is made using the (now +deprecated) {@link android.provider.Contacts} APIs.

    + +

    Other Framework fixes

    + + + + +

    API differences report

    + +

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +API Level 5, see the API +Differences Report. There are very few API changes in API Level 6, +so you might also be interested in reviewing the API +differences between 4 and 5.

    + diff --git a/docs/html/about/versions/android-2.0.jd b/docs/html/about/versions/android-2.0.jd new file mode 100644 index 000000000000..7a12e48672e3 --- /dev/null +++ b/docs/html/about/versions/android-2.0.jd @@ -0,0 +1,384 @@ +page.title=Android 2.0, Release 1 +sdk.platform.version=2.0 +sdk.platform.apiLevel=5 +sdk.platform.majorMinor=major + +@jd:body + +
    + +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in November 2009. +The release includes new features for users and developers, as well as changes +in the Android framework API.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform is fully +compliant and includes no external libraries.

    + +

    To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your SDK. For more information, +see Exploring the +SDK.

    + + +

    Platform Highlights

    + +

    For a list of new user features and platform highlights, see the Android +{@sdkPlatformVersion} Platform Highlights document.

    + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

    + + + + +
    + + + Android 2.0, Revision 1 (October 2009) +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r3 or higher.

    +
    +
    +
    +
    + +

    Built-in Applications

    + +

    The system image included in the downloadable platform provides these +built-in applications:

    + + + + + + +
    +
      +
    • Alarm Clock
    • +
    • Browser
    • +
    • Calculator
    • +
    • Camcorder
    • +
    • Camera
    • +
    • Contacts
    • +
    • Custom Locale (developer app)
    • +
    • Dev Tools (developer app)
    • +
    • Dialer
    • +
    +
    +
      +
    • Email
    • +
    • Gallery
    • +
    • Gestures Builder
    • +
    • IME for Japanese text input
    • +
    • Messaging
    • +
    • Music
    • +
    • Settings
    • +
    • Spare Parts (developer app)
    • +
    +
    + +

    Locales

    + +

    The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region locale +descriptor).

    + + + + + + +
    +
      +
    • Chinese, PRC (zh_CN)
    • +
    • Chinese, Taiwan (zh_TW)
    • +
    • Czech (cs_CZ)
    • +
    • Dutch, Netherlands (nl_NL)
    • +
    • Dutch, Belgium (nl_BE)
    • +
    • English, US (en_US)
    • +
    • English, Britain (en_GB)
    • +
    • English, Canada (en_CA)
    • +
    • English, Australia (en_AU)
    • +
    • English, New Zealand (en_NZ)
    • +
    • English, Singapore(en_SG)
    • +
    • French, France (fr_FR)
    • +
    • French, Belgium (fr_BE)
    • +
    +
    +
  • French, Canada (fr_CA)
  • +
  • French, Switzerland (fr_CH)
  • +
  • German, Germany (de_DE)
  • +
  • German, Austria (de_AT)
  • +
  • German, Switzerland (de_CH)
  • +
  • German, Liechtenstein (de_LI)
  • +
  • Italian, Italy (it_IT)
  • +
  • Italian, Switzerland (it_CH)
  • +
  • Japanese (ja_JP)
  • +
  • Korean (ko_KR)
  • +
  • Polish (pl_PL)
  • +
  • Russian (ru_RU)
  • +
  • Spanish (es_ES)
  • +
    + +

    Localized UI strings match the locales that are accessible +through Settings.

    + +

    Emulator Skins

    + +

    The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

    + + + +

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    + +

    Developer Features

    + +

    The sections below provide information about new developer features offered by the downloadable Android 2.0 platform component.

    + +

    Ant Support

    + + + +

    Framework API

    + +

    The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.

    + + +

    API level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of the framework +API. As with previous versions, the Android {@sdkPlatformVersion} API +is assigned an integer identifier — {@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to +set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk> +element in your application's manifest.

    + +

    For more information about how to use API Level, see the API Levels document.

    + + +

    API changes summary

    + +

    Bluetooth

    + + +

    Sync adapters

    + + +

    Account Manager

    + + +

    Contacts

    + + +

    WebView

    + + +

    Camera

    + + +

    Media

    + + +

    Other Framework

    + + +

    Key events executed on key-up

    + +

    Android 2.0 is designed to run on devices that use virtual keys for HOME, +MENU, BACK, and SEARCH, rather than physical keys. To support the best user +experience on those devices, the Android platform now executes these buttons at +key-up, for a key-down/key-up pair, rather than key-down. This helps prevent +accidental button events and lets the user press the button area and then drag +out of it without generating an event.

    + +

    This change in behavior should only affect your application if it is +intercepting button events and taking an action on key-down, rather than on +key-up. Especially if your application is intercepting the BACK key, you should +make sure that your application is handling the key events properly.

    + +

    In general, intercepting the BACK key in an application is not recommended, +however, if your application is doing so and it invokes some action on +key-down, rather than key-up, you should modify your code.

    + +

    If your application will use APIs introduced in Android 2.0 (API Level 5), +you can take advantage of new APIs for managing key-event pairs:

    + + + +

    If you want to update a legacy application so that its handling of the BACK +key works properly for both Android 2.0 and older platform versions, you +can use an approach similar to that shown above. Your code can catch the +target button event on key-down, set a flag to track the key event, and +then also catch the event on key-up, executing the desired action if the tracking +flag is set. You'll also want to watch for focus changes and clear the tracking +flag when gaining/losing focus.

    + +

    API differences report

    + +

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to +the previous version, see the API Differences Report.

    + diff --git a/docs/html/about/versions/android-2.1.jd b/docs/html/about/versions/android-2.1.jd new file mode 100644 index 000000000000..3cb0708ec42a --- /dev/null +++ b/docs/html/about/versions/android-2.1.jd @@ -0,0 +1,373 @@ +page.title=Android 2.1 Platform +sdk.platform.version=2.1 +sdk.platform.apiLevel=7 +sdk.platform.majorMinor=minor + +@jd:body + +
    + +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release +deployable to Android-powered handsets starting in January 2010. +This release includes new API +changes and bug fixes. For information on changes, see the Framework API +section.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes a +fully compliant Android library and system image, as well as a set of emulator +skins, sample applications, and more. The downloadable platform +includes no external libraries.

    + +

    To get started developing or testing against the Android +{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to +download the platform into your SDK. For more information, +see Exploring the +SDK.

    + + +

    Platform Highlights

    + +

    Android {@sdkPlatformVersion} does not add significant user features, see the Android +2.0 Platform Highlights document for the latest user features.

    + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

    + + +
    + +

    + + Android {@sdkPlatformVersion}, Revision 3 (July 2011) +

    + +
    + +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r12 or +higher.

    +
    +
    Notes:
    +
    +

    Improvements to the platform's rendering library to support the visual layout editor in the ADT +Eclipse plugin. This revision allows for more drawing features in ADT and fixes several +bugs in the previous rendering library. It also unlocks several editor features that were added in +ADT 12.

    +
    +
    + +
    +
    + +
    + +

    + + Android {@sdkPlatformVersion}, Revision 2 (May 2010) +

    + +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r6 or higher.

    +
    + +
    Tools:
    +
    +
      +
    • Adds support for library projects in the Ant build system.
    • +
    • Adds improved layout rendering in ADT’s visual layout editor.
    • +
    +
    + +
    +
    +
    + +
    + +

    + + Android {@sdkPlatformVersion}, Revision 1 (January 2010) +

    + +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r4 or higher.

    +
    +
    +
    +
    + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your +application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the +android:minSdkVersion attributes of the <uses-sdk> +element in your application's manifest.

    + +

    For more information about how to use API Level, see the API Levels document.

    + + +

    Framework API Changes

    + +

    The sections below provide information about changes made to the application +framework API provided by the Android {@sdkPlatformVersion} platform.

    + +

    Live Wallpapers

    + +

    The following additions provide APIs for you to develop animated wallpapers:

    + + +

    Additionally, if your application uses or provides Live Wallpapers, you must +remember to add a <uses-feature> + element to the application's manifest, declaring the attribute +android:name="android.software.live_wallpaper". For example:

    + +
    +<uses-feature android:name="android.software.live_wallpaper" />
    +
    + +

    When you've published your application, Google Play checks for the +presence of this element and uses it as a filter, ensuring that your application +is not made available to users whose devices do not support Live Wallpapers. +

    + +

    Telephony

    + + + +

    Views

    + + + +

    WebKit

    + + + + + + + +

    API differences report

    + +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level {@sdkPlatformApiLevel}), as compared to API Level 6, see the API +Differences Report.

    + +

    Built-in Applications

    + +

    The system image included in the downloadable platform provides these +built-in applications:

    + + + + + + +
    +
      +
    • Alarm Clock
    • +
    • Browser
    • +
    • Calculator
    • +
    • Camera
    • +
    • Contacts
    • +
    • Custom Locale (developer app)
    • +
    • Dev Tools (developer app)
    • +
    • Email
    • +
    +
    +
      + +
    • Gallery
    • +
    • IMEs for Japanese, Chinese, and Latin text input
    • +
    • Messaging
    • +
    • Music
    • +
    • Phone
    • +
    • Settings
    • +
    • Spare Parts (developer app)
    • +
    +
    + + +

    Locales

    + +

    The system image included in the downloadable platform provides a variety of +built-in locales. In some cases, region-specific strings are available for the +locales. In other cases, a default version of the language is used. The +languages that are available in the Android {@sdkPlatformVersion} system +image are listed below (with language_country/region locale +descriptor).

    + + + + + + +
    +
      +
    • Chinese, PRC (zh_CN)
    • +
    • Chinese, Taiwan (zh_TW)
    • +
    • Czech (cs_CZ)
    • +
    • Dutch, Netherlands (nl_NL)
    • +
    • Dutch, Belgium (nl_BE)
    • +
    • English, US (en_US)
    • +
    • English, Britain (en_GB)
    • +
    • English, Canada (en_CA)
    • +
    • English, Australia (en_AU)
    • +
    • English, New Zealand (en_NZ)
    • +
    • English, Singapore(en_SG)
    • +
    • French, France (fr_FR)
    • +
    • French, Belgium (fr_BE)
    • +
    +
    +
  • French, Canada (fr_CA)
  • +
  • French, Switzerland (fr_CH)
  • +
  • German, Germany (de_DE)
  • +
  • German, Austria (de_AT)
  • +
  • German, Switzerland (de_CH)
  • +
  • German, Liechtenstein (de_LI)
  • +
  • Italian, Italy (it_IT)
  • +
  • Italian, Switzerland (it_CH)
  • +
  • Japanese (ja_JP)
  • +
  • Korean (ko_KR)
  • +
  • Polish (pl_PL)
  • +
  • Russian (ru_RU)
  • +
  • Spanish (es_ES)
  • +
    + +

    Localized UI strings match the locales that are accessible +through Settings.

    + +

    Emulator Skins

    + +

    The downloadable platform includes a set of emulator skins that you can use +for modeling your application in different screen sizes and resolutions. The +emulator skins are:

    + + + +

    For more information about how to develop an application that displays +and functions properly on all Android-powered devices, see Supporting Multiple +Screens.

    diff --git a/docs/html/about/versions/android-2.2-highlights.jd b/docs/html/about/versions/android-2.2-highlights.jd new file mode 100644 index 000000000000..37a20d506512 --- /dev/null +++ b/docs/html/about/versions/android-2.2-highlights.jd @@ -0,0 +1,298 @@ +page.title=Android 2.2 Platform Highlights + +@jd:body + + + + + +
    + + + + + +
    + + +

    The Android 2.2 platform introduces many new and exciting features for +users and developers. This document provides a glimpse at some of the new user features +and technologies in Android 2.2. For more information about the new developer APIs, see the Android 2.2 version notes.

    + + + + + +

    New User Features

    + +

    Home

    + + + + + + +
    + + +

    New Home screen tips widget assists new users on +how to configure the +home screen with shortcuts and widgets and how to make use of multiple home screens.

    +

    The Phone, applications Launcher, and Browser now have dedicated +shortcuts on the Home screen, making it easy to access them from any of the 5 home screen +panels.

    +
    + + + +

    Exchange support

    + + + + + + +
    +

    Improved security with the addition of numeric pin or alpha-numeric +password options to unlock device. Exchange administrators can enforce password policy across +devices.

    +

    Remote wipe: Exchange administrators can remotely reset the device to +factory defaults to secure data in case device is lost or stolen.

    +

    Exchange Calendars are now supported in the Calendar application.

    +

    Auto-discovery: you just need to know your user-name and password to +easily set up and sync an Exchange account (available for Exchange 2007 and higher).

    +

    Global Address Lists look-up is now available in the Email +application, enabling users to auto-complete recipient names from the directory.

    +
    + +
    + + +

    Camera and Gallery

    + + + + + + +
    + + +

    Gallery allows you to peek into picture stacks using a zoom +gesture.

    +

    Camera onscreen buttons provide easy access to a new UI for +controling zoom, flash, white balance, geo-tagging, focus and exposure. Camcorder also provides +an easy way to set video size/quality for MMS and YouTube.

    +

    With the LED flash now enabled for the Camcorder, videos can be shot +at night or in low light settings.

    +
    + + +

    Portable hotspot

    + + + + + + +
    +

    Certain devices like the Nexus One can be turned into a portable Wi-Fi +hotspot that can be shared with up to 8 devices.

    +

    You can use your Android-powered phone as a 3G connection for a Windows or Linux laptop by +connecting their phone to the computer with a USB cable. The connection is then shared between the +two devices.

    +
    + +
    + + +

    Multiple keyboard languages

    + + + + + + +
    + + +

    Multi-lingual users can add multiple languages to the keyboard and switch +between multiple Latin-based input languages by swiping across the space bar. This changes +the keys as well as the auto-suggest dictionary.

    +
    + + +

    Improved performance

    + + + + + + +
    +

    Performance of the browser has been enhanced using the V8 engine, +which enables faster loading of JavaScript-heavy pages.

    +

    Dalvik Performance Boost: 2x-5x performance speedup for CPU-heavy code +over Android 2.1 with Dalvik JIT.

    +

    The graph to the right shows the performance speedup from Android 2.1 +to Android 2.2 using various benchmark tests. For example, LinPack is now more than 5 times +faster.

    +

    Kernel Memory Management Boost: Improved memory reclaim by up to 20x, +which results in faster app switching and smoother performance on memory-constrained devices.

    +
    + +
    + + + + + +

    New Platform Technologies

    + + +

    Media framework

    + + + + +

    Bluetooth

    + + + + +

    2.6.32 kernel upgrade

    + + + + + + +

    New Developer Services

    + + +

    Android Cloud to Device Messaging

    + +

    Apps can utilize Android Cloud to Device Messaging to enable mobile alert, send to phone, and +two-way push sync functionality.

    + + +

    Android Application Error Reports

    + +

    New bug reporting feature for Google Play apps enables developers to receive crash and freeze +reports from their users. The reports will be available when they log into their publisher +account.

    + + + + +

    New Developer APIs

    + + +

    Apps on external storage

    + +

    Applications can now request installation on the shared external storage (such as an SD +card).

    + + +

    Media framework

    + +

    Provides new APIs for audio focus, routing audio to SCO, and auto-scan of files to media +database. Also provides APIs to let applications detect completion of sound loading and auto-pause +and auto-resume audio playback.

    + + +

    Camera and Camcorder

    + +

    New preview API doubles the frame rate from ~10FPS to ~20FPS. Camera now supports portrait +orientation, zoom controls, access to exposure data, and a thumbnail utility. A new camcorder +profile enables apps to determine device hardware capablities.

    + + +

    Graphics

    + +

    New APIs for OpenGL ES 2.0, working with YUV image format, and ETC1 for texture +compression.

    + + +

    Data backup

    + +

    Apps can participate in data backup and restore, to ensure that users maintain their data +after performing a factory reset or when switching devices.

    + + +

    Device policy manager

    + +

    New device policy management APIs allow developers to write "device administrator" applications +that can control security features on the device, such as the minimum password strength, data wipe, +and so on. Users can select the administrators that are enabled on their devices.

    + + +

    UI framework

    + +

    New "car mode" and "night mode" controls and configurations allow applications to adjust their UI +for these situations. A scale gesture detector API provides improved definition of multi-touch +events. Applications can now customize the bottom strip of a TabWidget.

    + + + +

    For more information about the new developer APIs, see the Android 2.2 version notes and the API Differences Report.

    + + + + + diff --git a/docs/html/about/versions/android-2.2.jd b/docs/html/about/versions/android-2.2.jd new file mode 100644 index 000000000000..361e8b695d55 --- /dev/null +++ b/docs/html/about/versions/android-2.2.jd @@ -0,0 +1,252 @@ +page.title=Android 2.2 Platform +sdk.platform.version=2.2 +sdk.platform.apiLevel=8 +sdk.platform.majorMinor=minor + +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. Platform Highlights
    2. +
    3. API Level
    4. +
    5. Framework API Changes + +
    + + + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +

    See Also

    +
      +
    1. Exploring the SDK
    2. +
    + +
    +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release including user +features, developer features, API changes, and bug +fixes. For information on developer features and API changes, see the +Framework API section.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + +

    Platform Highlights

    + +

    For a list of new user features and platform highlights, see the Android +2.2 Platform Highlights document.

    + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your +application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the +android:minSdkVersion attributes of the <uses-sdk> +element in your application's manifest.

    + +

    For more information about how to use API Level, see the API Levels document.

    + + +

    Framework API Changes

    + +

    The sections below provide information about changes made to the application +framework API provided by the Android {@sdkPlatformVersion} platform.

    + +

    App installation on external storage media

    + +

    The Android platform now allows applications to request installation onto the +device's external storage media (such as the SD card), as an alternative to +installation onto the device's internal memory.

    + +

    Application developers can express the preferred installation location for +their applications by means of a new attribute of <manifest> +in the manifest file, +android:installLocation. The attribute supports three values: +"internalOnly", "preferExternal", and +"auto". At install time, the system checks the value of +android:installLocation and installs the application +.apk according to the preferred location, if possible. If the +application has requested external installation, the system installs it into a +private, encrypted partition in the external media. Once an application .apk is +installed externally, the system lets the user change the storage location of +the .apk and move it onto the device's internal memory if needed (and vice +versa), through Manage Applications in the user settings.

    + +

    By default, the system installs all applications onto the device's internal +memory, except for those that explicitly request external installation. This +means that the system will always install legacy applications onto internal +memory, since they do not have access to the +android:installLocation attribute. However, it is possible to +configure and compile a legacy application such that it is installed internally +on older versions of the platform and externally on Android 2.2 and later +platforms, if necessary.

    + +

    Note that requesting installation onto the device's external media is not +suitable for all applications, particularly because the external media may be +removable and unmounting/remounting may disrupt the user experience and system +settings.

    + +

    For more information about setting a preferred install location for your +application, including a discussion of what types of applications should and +should not request external installation, please read the App Install Location +document.

    + +

    Data backup

    + +

    The platform now provides a generalized backup service that +applications can use to backup and restore user data, to ensure that users can +maintain their data when switching devices or reinstalling the application. The +Backup Manager handles the work of transporting the application data to and from +the backup storage area in the cloud. The Backup Manager can store any type of +data, from arbitrary data to files, and manages backup and restore operations +in an atomic manner. For more information, see Data Backup.

    + +

    Graphics

    + + + +

    Media

    + + + +

    Speech recognition and third-party recognition engines

    + + + +

    Camera and camcorder

    + + + +

    Device policy manager

    + +

    New device policy management APIs allow developers to write "device +administrator" applications that can control security features of the device, +such as the minimum password strength, data wipe, and so on. Users can select +the administrators that are enabled on their devices. For more information, see +the {@link android.app.admin android.app.admin} classees or the example +application code in DeviceAdminSample.java.

    + +

    UI Framework

    + + + +

    Accounts and sync

    + + + +

    New manifest elements and attributes

    + + + +

    Permissions

    + + + +

    API differences report

    + +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level {@sdkPlatformApiLevel}), see the API +Differences Report.

    + + + diff --git a/docs/html/about/versions/android-2.3-highlights.jd b/docs/html/about/versions/android-2.3-highlights.jd new file mode 100644 index 000000000000..582bce9f81fd --- /dev/null +++ b/docs/html/about/versions/android-2.3-highlights.jd @@ -0,0 +1,444 @@ +page.title=Gingerbread + +@jd:body + + + + +

    The Android 2.3 platform introduces many new and exciting features for +users and developers. This document provides a glimpse at some of the new features +and technologies in Android 2.3. For detailed information about the new developer APIs, see the Android 2.3 version notes.

    + + + + +

    New User Features

    + +
    + + + +

    UI refinements for simplicity and speed

    + +

    The user interface is refined in many ways across the system, making it +easier to learn, faster to use, and more power-efficient. A simplified +visual theme of colors against black brings vividness and contrast to the +notification bar, menus, and other parts of the UI. Changes in menus and +settings make it easier for the user to navigate and control the features +of the system and device.

    + +

    Faster, more intuitive text input

    + +

    The Android soft keyboard is redesigned and optimized for faster text input +and editing. The keys themselves are reshaped and repositioned for improved +targeting, making them easier to see and press accurately, even at high speeds. +The keyboard also displays the current character and dictionary suggestions in a +larger, more vivid style that is easier to read.

    + +

    The keyboard adds the capability to correct entered words from suggestions in +the dictionary. As the user selects a word already entered, the keyboard +displays suggestions that the user can choose from, to replace the selection. +The user can also switch to voice input mode to replace the selection. Smart +suggestions let the user accept a suggestion and then return to correct it +later, if needed, from the original set of suggestions.

    + +

    New multitouch key-chording lets the user quickly enter numbers and symbols +by pressing Shift+<letter> and ?123+<symbol>, +without needing to manually switch input modes. From certain keys, users can +also access a popup menu of accented characters, numbers, and symbols by holding +the key and sliding to select a character.

    +
    + +
    +
    +
    + + +

    One-touch word selection and copy/paste

    + +

    When entering text or viewing a web page, the user can quickly select a word +by press-hold, then copy to the clipboard and paste. Pressing on a word enters a +free-selection mode — the user can adjust the selection area as needed by +dragging a set of bounding arrows to new positions, then copy the bounded area +by pressing anywhere in the selection area. For text entry, the user can +slide-press to enter a cursor mode, then reposition the cursor easily and +accurately by dragging the cursor arrow. With both the selection and cursor +modes, no use of a trackball is needed.

    + +
    + +
    +
    +
    + +

    Improved power management

    + +

    The Android system takes a more active role in managing apps that are keeping +the device awake for too long or that are consuming CPU while running in the +background. By managing such apps — closing them if appropriate — +the system helps ensure best possible performance and maximum battery life.

    + +

    The system also gives the user more visibility over the power being consumed +by system components and running apps. The Application settings provides an +accurate overview of how the battery is being used, with details of the usage +and relative power consumed by each component or application.

    + +

    Control over applications

    + +

    A shortcut to the Manage Applications control now appears in the Options Menu +in the Home screen and Launcher, making it much easier to check and manage +application activity. Once the user enters Manage Applications, a new Running +tab displays a list of active applications and the storage and memory being used +by each. The user can read further details about each application and if +necessary stop an application or report feedback to its developer.

    +
    + +

    New ways of communicating, organizing

    + +

    An updated set of standard applications lets the user take new approaches to +managing information and relationships.

    + +
    +

    +
    +
    + +

    Internet calling

    + +

    The user can make voice calls over the internet to other users who have SIP +accounts. The user can add an internet calling number (a SIP address) to any +Contact and can initiate a call from Quick Contact or Dialer. To use internet +calling, the user must create an account at the SIP provider of their choice +— SIP accounts are not provided as part of the internet calling feature. +Additionally, support for the platform's SIP and internet calling features on +specific devices is determined by their manufacturers and associated carriers. +

    + +
    + +

    Near-field communications

    + +

    An NFC Reader application lets the user read and interact with near-field +communication (NFC) tags. For example, the user can “touch” or “swipe” an NFC +tag that might be embedded in a poster, sticker, or advertisement, then act on +the data read from the tag. A typical use would be to read a tag at a +restaurant, store, or event and then rate or register by jumping to a web site +whose URL is included in the tag data. NFC communication relies on wireless +technology in the device hardware, so support for the platform's NFC features on +specific devices is determined by their manufacturers. +

    +
    + +

    Downloads management

    + +

    The Downloads application gives the user easy access to any file downloaded from +the browser, email, or another application. Downloads is built on an completely new +download manager facility in the system that any other applications can use, to +more easily manage and store their downloads.

    + +

    Camera

    + +

    The application now lets the user access multiple cameras on the device, +including a front-facing camera, if available.

    + + +

    New Developer Features

    + +

    Android 2.3 delivers a variety of features and APIs that +let developers bring new types of applications to the Android +platform.

    + + + +

    Enhancements for gaming

    + +

    Performance

    + +

    Android 2.3 includes a variety of improvements across the system that make +common operations faster and more efficient for all applications. Of particular +interest to game developers are:

    + + + + +

    Native input and +sensor events

    + +

    Applications that use native code can now receive and process input and +sensor events directly in their native code, which dramatically improves +efficiency and responsiveness.

    + +

    Native libraries exposed by the platform let applications handle the same +types of input events as those available through the framework. Applications +can receive events from all supported sensor types and can enable/disable +specific sensors and manage event delivery rate and queueing.

    + + +

    Gyroscope and other +new sensors, for improved 3D motion processing

    + +

    Android 2.3 adds API support for several new sensor types, including +gyroscope, rotation vector, linear acceleration, gravity, and barometer sensors. +Applications can use the new sensors in combination with any other sensors +available on the device, to track three-dimensional device motion and +orientation change with high precision and accuracy. For example, a game +application could use readings from a gyroscope and accelerometer on the device +to recognize complex user gestures and motions, such as tilt, spin, thrust, and +slice.

    + + +

    Open API for native +audio

    + +

    The platform provides a software implementation of Khronos OpenSL ES, a standard API +that gives applications access to powerful audio controls and effects from +native code. Applications can use the API to manage audio devices and control +audio input, output, and processing directly from native code.

    + +

    Native graphics +management

    + +

    The platform provides an interface to its Khronos EGL library, which lets +applications manage graphics contexts and create and manage OpenGL ES textures +and surfaces from native code.

    + + +

    Native access to +Activity lifecycle, window management

    + +

    Native applications can declare a new type of Activity class, +NativeActivity whose lifecycle callbacks are implemented directly +in native code. The NativeActivity and its underlying native code +run in the system just as do other Activities — they run in the +application's system process and execute on the application's main UI thread, +and they receive the same lifecycle callbacks as do other Activities.

    + +

    The platform also exposes native APIs for managing windows, including the +ability to lock/unlock the pixel buffer to draw directly into it. Through the +API, applications can obtain a native window object associated with a framework +Surface object and interact with it directly in native code.

    + + +

    Native access to +assets, storage

    + +

    Applications can now access a native Asset Manager API to retrieve +application assets directly from native code without needing to go through JNI. +If the assets are compressed, the platform does streaming decompression as the +application reads the asset data. There is no longer a limit on the size of +compressed .apk assets that can be read.

    + +

    Additionally, applications can access a native Storage Manager API to work +directly with OBB files downloaded and managed by the system. Note that although +platform support for OBB is available in Android 2.3, development tools for +creating and managing OBB files will not be available until early 2011.

    + + +

    Robust native +development environment

    + +

    The Android NDK (r5 or higher) provides a complete set of tools, toolchains, +and libraries for developing applications that use the rich native environment +offered by the Android 2.3 platform. For more information or to download the +NDK, please see the Android NDK +page.

    + + +

    New forms of communication

    + +

    Internet +telephony

    + +

    Developers can now add SIP-based internet telephony features to their +applications. Android 2.3 includes a full SIP protocol stack and integrated call +management services that let applications easily set up outgoing and incoming +voice calls, without having to manage sessions, transport-level communication, +or audio record or playback directly.

    + +

    Support for the platform's SIP and internet calling features on specific +devices is determined by their manufacturers and associated carriers.

    + + +

    Near Field +Communications (NFC)

    + +

    The platform's support for Near Field Communications (NFC) lets developers +get started creating a whole new class of applications for Android. Developers +can create new applications that offer proximity-based information and services +to users, organizations, merchants, and advertisers.

    + +

    Using the NFC API, +applications can read and respond to NFC tags “discovered” as the user “touches” an +NFC-enabled device to elements embedded in stickers, smart posters, and even +other devices. When a tag of interest is collected, applications can respond to +the tag, read messages from it, and then store the messages, prompting +the user as needed.

    + +

    Starting from Android 2.3.3, applications can also write to tags and +set up peer-to-peer connections with other NFC devices.

    + +

    NFC communication relies on wireless technology in the device hardware, so +support for the platform's NFC features on specific devices is determined by +their manufacturers.

    + + +

    Rich multimedia

    + +

    Mixable audio +effects

    + +

    A new audio effects API lets developers easily create rich audio environments +by adding equalization, bass boost, headphone virtualization (widened +soundstage), and reverb to audio tracks and sounds. Developers can mix multiple +audio effects in a local track or apply effects globally, across multiple +tracks.

    + +

    Support for new media +formats

    + +

    The platform now offers built-in support for the VP8 open video compression +format and the WebM open container format. The platform also adds support for +AAC encoding and AMR wideband encoding (in software), so that applications can +capture higher quality audio than narrowband.

    + +

    Access to multiple +cameras

    + +

    The Camera API now lets developers access any cameras that are available on a +device, including a front-facing camera. Applications can query the platform for +the number of cameras on the device and their types and characteristics, then +open the camera needed. For example, a video chat application might want to access a +front-facing camera that offers lower-resolution, while a photo application +might prefer a back-facing camera that offers higher-resolution.

    + + +

    New Platform Technologies

    + +

    Media Framework

    + + + +

    Linux Kernel

    + + +

    Networking

    + + +

    Dalvik runtime

    + + + +

    For more information about the new developer APIs, see the Android 2.3 version notes and the API Differences Report.

    diff --git a/docs/html/about/versions/android-2.3.3.jd b/docs/html/about/versions/android-2.3.3.jd new file mode 100644 index 000000000000..55ff346ac242 --- /dev/null +++ b/docs/html/about/versions/android-2.3.3.jd @@ -0,0 +1,192 @@ +page.title=Android 2.3.3 Platform +sdk.platform.version=2.3.3 +sdk.platform.apiLevel=10 + + +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. API Level
    4. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    Android 2.3.3 is a small feature release that adds several improvements +and APIs to the Android 2.3 platform.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + + +

    API Overview

    + +

    The sections below provide a technical overview of what's new for developers +in {@sdkPlatformVersion}, including new features and changes in the framework +API since the previous version.

    + +

    Near Field Communications (NFC)

    + +

    Android 2.3.3 provides improved and extended support for NFC, to allow +applications to interact with more types of tags in new ways.

    + +

    A new, comprehensive set of APIs give applications read and write access +to a wider range of standard tag technologies, including:

    + + + +

    The platform also provides a limited peer-to-peer communication protocol +and API. Foreground Activities can use the API to register an NDEF +message that will get pushed to other NFC devices when they connect.

    + +

    Advanced tag dispatching now gives applications more control over how and +when they are launched, when an NFC tag is discovered. Previously, the platform +used a single-step intent dispatch to notify interested applications that a tag +was discovered. The platform now uses a four-step process that enables the +foreground application to take control of a tag event before it is passed to any +other applications (android.nfc.NfcAdapter.enableForegroundDispatch()). + +The new dispatch process also lets apps listen for specific tag content and +tag technologies, based on two new intent actions — +android.nfc.action.NDEF_DISCOVERED and +android.nfc.action.TECH_DISCOVERED.

    + +

    The NFC API is available in the {@link android.nfc} and +{@link android.nfc.tech} packages. The key classes are:

    + + + +

    NFC communication relies on wireless technology in the device hardware, and +is not present in all Android devices. Android devices that do not support +NFC will return a null object when +{@link android.nfc.NfcAdapter#getDefaultAdapter(android.content.Context) +getDefaultAdapter(Context)} is called, and +context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC) +will return false. The NFC API is always present, however, regardless of +underlying hardware support.

    + +

    To use the NFC API, applications must request permission from the user by +declaring <uses-permission +android:name="android.permission.NFC"> in their manifest files.

    + +

    Additionally, developers can request filtering on Google Play, such that +their applications are not discoverable to users whose devices do not support +NFC. To request filtering, add +<uses-feature android:name="android.hardware.nfc" +android:required="true"> to the application's manifest.

    + +

    To look at sample code for NFC, see +NFCDemo app, filtering by tag technology, using foreground dispatch, and foreground NDEF push (P2P).

    + +

    Bluetooth

    + +

    Android 2.3.3 adds platform and API support for Bluetooth nonsecure socket +connections. This lets applications communicate with simple devices that may not +offer a UI for authentication. See +{@link android.bluetooth.BluetoothDevice#createInsecureRfcommSocketToServiceRecord(java.util.UUID)} and +{@link android.bluetooth.BluetoothAdapter#listenUsingInsecureRfcommWithServiceRecord(java.lang.String, java.util.UUID)} +for more information.

    + +

    Graphics

    + + + + +

    Media framework

    + + + + +

    Speech recognition

    + +

    The speech-recognition API includes new constants to let you manage voice +search results in new ways. Although the new constants are not needed for normal +use of speech recognition, you could use them to offer a different view of voice +search results in your application. For information, see {@link +android.speech.RecognizerResultsIntent}.

    + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, +you need compile the application against the Android library that is provided in +the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might +also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" +attribute to the <uses-sdk> element in the application's +manifest. If your application is designed to run only on Android 2.3 and higher, +declaring the attribute prevents the application from being installed on earlier +versions of the platform.

    + +

    For more information, read What is API +Level?

    \ No newline at end of file diff --git a/docs/html/about/versions/android-2.3.4.jd b/docs/html/about/versions/android-2.3.4.jd new file mode 100644 index 000000000000..bb4feecae287 --- /dev/null +++ b/docs/html/about/versions/android-2.3.4.jd @@ -0,0 +1,148 @@ +page.title=Android 2.3.4 Platform +sdk.platform.version=2.3.4 +sdk.platform.apiLevel=10 + + +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. Open Accessory Library
    4. +
    5. API Level
    6. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    Android 2.3.4 is a maintenance release that adds several bug fixes and patches +to the Android 2.3 platform, without any API changes from Android 2.3.3. Additionally, +Android 2.3.4 brings support for the Open Accessory API to mobile devices, +through the optional Open Accessory Library.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + + +

    API Overview

    + +

    Android 2.3.4 provides the same framework API to applications as Android 2.3.3 +(API level 10). For a summary of the API, see the +Android 2.3.3 version notes.

    + + +

    Open Accessory Library

    + +

    Open Accessory is a new capability for integrating +connected peripherals with applications running on the platform. The capability +is based on a USB (Universal Serial Bus) stack built into the platform and an +API exposed to applications. Peripherals that attach to Android-powered devices +as accessories connect as USB hosts.

    + +

    Open Accessory is introduced in Android 3.1 (API level 12), but is +made available to devices running Android 2.3.4 by means of an optional external +library, the Open Accessory Library. The library exposes a framework API that +lets applications discover, communicate with, and manage a variety of device +types connected over USB. It also provides the implementation of the API against +parts of the Android platform that are not directly exposed to applications in +Android 2.3.4.

    + +

    The Open Accessory Library is optional on any given device. Device +manufacturers may choose whether to include the Open Accessory Library in their +products or exclude it. The library is forward-compatible with Android 3.1, so +applications developed against Android 2.3.4 will run properly on devices +running Android 3.1, if those devices support USB accessories.

    + +

    The API provided by the Open Accessory Library is based on the Open Accessory +API provided in Android 3.1. In most areas, you can use the same techniques and +APIs. However, developing for the Open Accessory Library on Android 2.3.4 differs +from the standard USB API in these ways: + +

    + +

    To develop apps using the Open Accessory Library, you need:

    + + + +

    For a full discussion of how to develop applications that interact with USB +accessories, please see the related developer documentation.

    + +

    Additionally, developers can request filtering on Google Play, such that +their applications are not available to users whose devices do not provide the +appropriate accessory support. To request filtering, add the element below +to the application manifest:

    + +
    <uses-feature
    +  android:name="android.hardware.usb.accessory"
    +  android:required="true">
    + + +

    API Level

    + +

    The Android 2.3.4 platform does not increment the API level — +it uses the same API level as Android 2.3.3, API level 10. + +

    To use APIs introduced in API level 10 in your application, +you need compile the application against the Android library that is provided in +the latest version of the Google APIs Add-On, which also includes the Open +Accessory Library.

    + +

    Depending on your needs, you might +also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" +attribute to the <uses-sdk> element in the application's +manifest. If your application is designed to run only on Android 2.3.3 and higher, +declaring the attribute prevents the application from being installed on earlier +versions of the platform.

    + +

    For more information, read What is API +Level?

    diff --git a/docs/html/about/versions/android-2.3.jd b/docs/html/about/versions/android-2.3.jd new file mode 100644 index 000000000000..2afa564ffc20 --- /dev/null +++ b/docs/html/about/versions/android-2.3.jd @@ -0,0 +1,710 @@ +page.title=Android 2.3 Platform +sdk.platform.version=2.3 +sdk.platform.apiLevel=9 + + +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. API Level
    4. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + +

    +API Level: {@sdkPlatformApiLevel}

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + + + +

    API Overview

    + +

    The sections below provide a technical overview of what's new for developers +in {@sdkPlatformVersion}, including new features and changes in the framework +API since the previous version.

    + + +

    SIP-based VoIP

    + +

    The platform now includes a SIP protocol stack and framework API that lets +developers build internet telephony applications. Using the API, applications can offer +voice calling features without having to manage sessions, transport-level +communication, or audio — these are handled +transparently by the platform's SIP API and services.

    + +

    The SIP API is available in the {@link android.net.sip android.net.sip} +package. The key class is {@link android.net.sip.SipManager}, which applications +use to set up and manage SIP profiles, then initiate audio calls and receive +audio calls. Once an audio call is established, applications can mute calls, +turn on speaker mode, send DTMF tones, and more. Applications can also use the +{@link android.net.sip.SipManager} to create generic SIP connections.

    + +

    The platform’s underlying SIP stack and services are available on devices at +the discretion of the manufacturer and associated carrier. For this reason, +applications should use the {@link android.net.sip.SipManager#isApiSupported +isApiSupported()} method to check whether SIP support is available, before +exposing calling functionality to users.

    + +

    To use the SIP API, applications must request permission from the user by +declaring <uses-permission +android:name="android.permission.INTERNET"> and <uses-permission +android:name="android.permission.USE_SIP"> in their manifest files.

    + +

    Additionally, developers can request filtering on Google Play, such that +their applications are not discoverable to users whose devices do not include +the platform’s SIP stack and services. To request filtering, add <uses-feature +android:name="android.software.sip" +android:required="true"> and <uses-feature +android:name="android.software.sip.voip"> to the application manifest.

    + +

    To look at a sample application that uses the SIP API, see SIP Demo.

    + +

    Near Field Communications (NFC)

    + +

    Android 2.3 includes an NFC stack and framework API that lets developers +read NDEF tags that are discovered as a user touches an NFC-enabled device +to tag elements embedded in stickers, smart posters, and even other devices.

    + +

    The platform provides the underlying NFC services that work with the device +hardware to discover tags when they come into range. On discovering a tag, the +platform notifies applications by broadcasting an Intent, appending the tag's +NDEF messages to the Intent as extras. Applications can create Intent filters to +recognize and handle targeted tags and messages. For example, after receiving a +tag by Intent, applications extract the NDEF messages, store them, alert the +user, or handle them in other ways.

    + +

    The NFC API is available in the {@link android.nfc} package. The key classes are:

    + + + +

    NFC communication relies on wireless technology in the device hardware, so +support for the platform's NFC features on specific devices is determined by +their manufacturers. To determine the NFC support on the current device, +applications can call {@link android.nfc.NfcAdapter#isEnabled isEnabled()} to +query the {@link android.nfc.NfcAdapter}. The NFC API is always present, +however, regardless of underlying hardware support.

    + +

    To use the NFC API, applications must request permission from the user by +declaring <uses-permission +android:name="android.permission.NFC"> in their manifest files.

    + +

    Additionally, developers can request filtering on Google Play, such that +their applications are not discoverable to users whose devices do not support +NFC. To request filtering, add +<uses-feature android:name="android.hardware.nfc" +android:required="true"> to the application's manifest.

    + +

    To look at a sample application that uses the NFC API, see +NFCDemo.

    + +

    Gyroscope and other sensors

    + +

    Android 2.3 adds platform and API support for several new sensor reading +types — gyroscope, rotation vector, linear acceleration, gravity, and barometer. +Developers can use the new sensor readings to create applications that respond +quickly and smoothly to precise changes in device position and motion. The +Sensor API reports gyroscope and other sensor changes to interested +applications, whether they are running on the application framework or in native +code.

    + +

    Note that the specific set of hardware sensors available on any given device +varies at the discretion of the device manufacturer.

    + +

    Developers can request filtering on Google Play, such that their +applications are not discoverable to users whose devices do not offer a +gyroscope sensor. To do so, add <uses-feature +android:name="android.hardware.sensor.gyroscope" +android:required="true"> to the application manifest.

    + +

    For API details, see {@link android.hardware.Sensor}.

    + + +

    Multiple cameras support

    + +

    Applications can now make use of any cameras that are available on a device, +for either photo or video capture. The {@link android.hardware.Camera} lets +applications query for the number of cameras available and the unique +characteristics of each.

    + + + +

    To look at sample code for accessing a front-facing camera, see CameraPreview.java +in the ApiDemos sample application.

    + +

    The Camera API also adds:

    + + +

    Mixable audio effects

    + +

    The platform's media framework adds support for new per-track or global audio effects, +including bass boost, headphone virtualization, equalization, and reverb.

    + + +

    To look at sample code for audio effects, see +AudioFxDemo.java +in the ApiDemos sample application.

    + +

    The media framework also adds:

    + + +

    Download manager

    + +

    The platform includes a new {@link android.app.DownloadManager} system service +that handles long-running HTTP downloads. Applications can request that a URI be +downloaded to a particular destination file. The DownloadManager +will conduct the download in the background, taking care of HTTP interactions +and retrying downloads after failures or across connectivity changes and system +reboots.

    + + +

    StrictMode

    + +

    To help developers monitor and improve the performance of their applications, +the platform offers a new system facility called {@link android.os.StrictMode}. +When implemented in an application, StrictMode catches and notifies the +developer of accidental disk or network activity that could degrade application +performance, such as activity taking place on the application's main thread +(where UI operations are received and animations are also taking place). +Developers can evaluate the network and disk usages issues raised in StrictMode +and correct them if needed, keeping the main thread more responsive and +preventing ANR dialogs from being shown to users. + +

    + +

    For more information about how to use StrictMode to optimize your +application, see the class documentation and sample code at {@link +android.os.StrictMode android.os.StrictMode}.

    + +

    UI Framework

    + + + +

    Extra Large Screens

    + +

    The platform now supports extra large screen sizes, such as those that might +be found on tablet devices. Developers can indicate that their applications are +designed to support extra large screen sizes by adding a <supports +screens ... android:xlargeScreens="true"> element to their manifest +files. Applications can use a new resource qualifier, xlarge, to +tag resources that are specific to extra large screens. For +details on how to support extra large and other screen sizes, see Supporting Multiple +Screens.

    + +

    Graphics

    + + + +

    Content Providers

    + + + +

    Location

    + + + +

    Storage

    + + + +

    Package Manager

    + + + +

    Telephony

    + + + +

    Native access to Activity lifecycle, windows

    + +

    Android 2.3 exposes a broad set of APIs to applications that use native +code. Framework classes of interest to such applications include:

    + + + +

    For full information on working with native code or to download the NDK, +see the Android NDK page.

    + + +

    Dalvik Runtime

    + + + +

    New manifest elements and attributes

    + + + +

    New Permissions

    + + + +

    New Feature Constants

    + +

    The platform adds several new hardware features that developers can declare +in their application manifests as being required by their applications. This +lets developers control how their application is filtered, when published on +Google Play.

    + + + +

    For full information about how to declare features and use them for +filtering, see the documentation for <uses-feature>.

    + +

    API differences report

    + +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level {@sdkPlatformApiLevel}), see the API +Differences Report.

    + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, +you need compile the application against the Android library that is provided in +the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might +also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" +attribute to the <uses-sdk> element in the application's +manifest. If your application is designed to run only on Android 2.3 and higher, +declaring the attribute prevents the application from being installed on earlier +versions of the platform.

    + +

    For more information, read What is API +Level?

    \ No newline at end of file diff --git a/docs/html/about/versions/android-3.0-highlights.jd b/docs/html/about/versions/android-3.0-highlights.jd new file mode 100644 index 000000000000..21dbda6af4ce --- /dev/null +++ b/docs/html/about/versions/android-3.0-highlights.jd @@ -0,0 +1,261 @@ +page.title=Honeycomb + +@jd:body + + + + + +

    Welcome to Android 3.0!

    + +

    The Android 3.0 platform introduces many new and exciting features for users and developers. +This document provides a glimpse of some of the new features and technologies, as delivered in +Android 3.0. For a more detailed look at new developer APIs, see the Android 3.0 Platform document.

    + + + +

    New User Features

    + +
    +
    + +

    New UI designed from the ground up for tablets

    + +

    Android 3.0 is a new version of the Android platform that is specifically optimized for devices with larger screen sizes, particularly tablets. It introduces a brand new, truly virtual and “holographic” UI design, as well as an elegant, content-focused interaction model.

    + +

    Android 3.0 builds on the things people love most about Android — refined multitasking, rich notifications, Home screen customization, widgets, and more — and transforms them with a vibrant, 3D experience and deeper interactivity, making them familiar but even better than before.

    + +

    The new UI brings fresh paradigms for interaction, navigation, and customization and makes them available to all applications — even those built for earlier versions of the platform. Applications written for Android 3.0 are able to use an extended set of UI objects, powerful graphics, and media capabilities to engage users in new ways.

    + +

    System Bar, for global status and notifications

    + +

    Across the system and in all applications, users have quick access to notifications, system status, and soft navigation buttons in a System Bar, available at the bottom of the screen. The System Bar is always present and is a key touchpoint for users, but in a new "lights out mode" can also be dimmed for full-screen viewing, such as for videos.

    + +

    Action Bar, for application control

    + +

    In every application, users have access to contextual options, navigation, widgets, or other types of content in an Action Bar, displayed at the top of the screen. The Action Bar is always present when an application is in use, although its content, theme, and other properties are managed by the application rather than the system. The Action Bar is another key touchpoint for users, especially with action items and an overflow dropdown menu, which users frequently access in a similar manner in most applications.

    + +
    + +
    +
    + +

    Customizable Home screens

    + +

    Five customizable Home screens give users instant access to all parts of the system from any context. Each screen offers a large grid that maintains spatial arrangement in all orientations. Users can select and manipulate Home screen widgets, app shortcuts, and wallpapers using a dedicated visual layout mode. Visual cues and drop shadows improve visibility when adjusting the layout of shortcuts and widgets. Each Home screen also offers a familiar launcher for access to all installed applications, as well as a Search box for universal search of apps, contacts, media files, web content, and more.

    + +
    + +
    +
    + +
    + +

    Recent Apps, for easy visual multitasking

    + +

    Multitasking is a key strength of Android and it is central to the Android 3.0 experience. As users launch applications to handle various tasks, they can use the Recent Apps list in the System Bar to see the tasks underway and quickly jump from one application context to another. To help users rapidly identify the task associated with each app, the list shows a snapshot of its actual state when the user last viewed it.

    + +
    + + +

    Redesigned keyboard

    + +

    The Android soft keyboard is redesigned to make entering text fast and accurate on larger screen sizes. The keys are reshaped and repositioned for improved targeting, and new keys have been added, such as a Tab key, to provide richer and more efficient text input. Users can touch-hold keys to access menus of special characters and switch text/voice input modes from a button in the System Bar.

    + +
    +
    + + +

    Improved text selection, copy and paste

    + +

    When entering or viewing text, a new UI lets users quickly select a word by press-hold and then adjust the selection area as needed by dragging a set of bounding arrows to new positions. Users can then select an action from the Action Bar, such as copy to the clipboard, share, paste, web search, or find.

    + + +

    New connectivity options

    + +

    Android 3.0 includes new connectivity features that add versatility and convenience for users. Built-in support for Media/Picture Transfer Protocol lets users instantly sync media files with a USB-connected camera or desktop computer, without needing to mount a USB mass-storage device. Users can also connect full keyboards over either USB or Bluetooth, for a familiar text-input environment. For improved wi-fi connectivity, a new combo scan reduces scan times across bands and filters. New support for Bluetooth tethering means that more types of devices can share the network connection of an Android-powered device.

    + + +

    Updated set of standard apps

    + +
    +

    +
    + +

    The Android 3.0 platform includes an updated set of standard applications that are designed for use on larger screen devices. The sections below highlight some of the new features.

    + +Browser

    + +

    The browser includes new features that let users navigate and organize more efficiently. Multiple tabs replace browser windows and a new “incognito” mode allows anonymous browsing. Bookmarks and history are presented and managed in a single unified view. Users can now choose to automatically sign into Google sites on the browser with a supplied account and sync bookmarks with Google Chrome. New multitouch support is now available to JavaScript and plugins. Users can enjoy a better browsing experience at non-mobile sites through an improved zoom and viewport model, overflow scrolling, support for fixed positioning, and more.

    + +

    Camera and Gallery

    + +

    The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. The Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection.

    + +

    Contacts

    + +

    The Contacts app uses a new two-pane UI and Fast Scroll to let users easily organize and locate contacts. The application offers improved formatting of international phone numbers as user types, based on home country and an international number parsing library. Contact information is presented in a card-like UI, making it easier for users to read and edit contacts.

    + +

    Email

    + +

    The Email application uses a new two-pane UI to make viewing and organizing messages more efficient. The app lets users select one or more messages, then select an action from the Action Bar, such as moving them to a folder. Users can sync attachments for later viewing and keep track of email using a home screen Widget.

    + +
    + + +

    New Developer Features

    + +

    The Android 3.0 platform is designed specially to meet the unique needs of applications on devices with larger screen sizes. It offers all of the tools developers need to create incredible visual and interaction experiences on these devices.

    + + + +

    New UI Framework for creating great tablet apps

    + +
    +
    + + +

    Activity fragments, for greater control of content and design flexibility

    + +

    Starting with Android 3.0, developers can break the Activities of their applications into subcomponents called Fragments, then combine them in a variety of ways to create a richer, more interactive experience. For example, an application can use a set of Fragments to create a true multipane UI, with the user being able to interact with each pane independently. Fragments can be added, removed, replaced, and animated inside an Activity dynamically, and they are modular and reusable across multiple Activities. Because they are modular, Fragments also offer an efficient way for developers to write applications that can run properly on both larger screen as well as smaller screen devices.

    + +
    + +

    Redesigned UI widgets

    + +

    Android 3.0 offers an updated set of UI widgets that developers can use to quickly add new types of content to their applications. The new UI widgets are redesigned for use on larger screens such as tablets and incorporate the new holographic UI theme. Several new widget types are available, including a 3D stack, search box, a date/time picker, number picker, calendar, popup menu, and others. Most of the redesigned UI widgets can now be used as remote views in application widgets displayed on the home screen. Applications written for earlier versions can inherit the new Widget designs and themes.

    + + +
    +
    + +

    Expanded Home screen widgets

    + +

    Home screen widgets are popular with users because they offer fast access to application-specific data directly from the home screen. Android 3.0 lets developers take home screen widgets to the next level, offering more types of content and new modes of interaction with users. Developers can now use more standard UI widget types home screen widgets, including widgets that let users flip through collections of content as 3D stacks, grids, or lists. Users can interact with the home screen widgets in new ways, such as by using touch gestures to scroll and flip the content displayed in a widget.

    + +
    + +

    Persistent Action Bar

    + +

    The platform provides each application with its own instance of the Action Bar at the top of the screen, which the application can use to give the user quick access to contextual options, widgets, status, navigation, and more. The application can also customize the display theme of its Action Bar instance. The Action Bar lets developers expose more features of their applications to users in a familiar location, while also unifying the experience of using an application that spans multiple Activities or states.

    + +

    Richer notifications

    + +

    Notifications are a key part of the Android user experience because they let applications show key updates and status information to users in real time. Android 3.0 extends this capability, letting developers include richer content and control more properties. A new builder class lets developers quickly create notifications that include large and small icons, a title, a priority flag, and any properties already available in previous versions. Notifications can offer more types of content by building on the expanded set of UI Widgets that are now available as remote Views.

    + +
    +
    + +

    Multiselect, clipboard, and drag-and-drop

    + +

    The platform offers convenient new interaction modes that developers can use. For managing collections of items in lists or grids, developers can offer a new multiselect mode that lets users choose multiple items for an action. Developers can also use a new system-wide Clipboard to let users easily copy any type of data into and out of their applications. To make it easier for users to manage and organize files, developers can now add drag-and-drop interaction through a DragEvent framework.

    + +
    + + +

    High-performance 2D and 3D graphics

    + +

    New animation framework

    + +

    The platform includes a flexible new animation framework that lets developers easily animate the properties of UI elements such as Views, Widgets, Fragments, Drawables, or any arbitrary object. Animations can create fades or movement between states, loop an animated image or an existing animation, change colors, and much more. Adding animation to UI elements can add visual interest to an application and refine the user experience, to keep users engaged.

    + +

    Hardware-accelerated 2D graphics

    + +

    Android 3.0 offers a new hardware-accelerated OpenGL renderer that gives a performance boost to many common graphics operations for applications running in the Android framework. When the renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. Developers can control how hardware-acceleration is applied at every level, from enabling it globally in an application to enabling it in specific Activities and Views inside the application.

    + +

    Renderscript 3D graphics engine

    + +

    Renderscript is a runtime 3D framework that provides both an API for building 3D scenes as well as a special, platform-independent shader language for maximum performance. Using Renderscript, you can accelerate graphics operations and data processing. Renderscript is an ideal way to create high-performance 3D effects for applications, wallpapers, carousels, and more.

    + + +

    Support for multicore processor architectures

    + +

    Android 3.0 is the first version of the platform designed to run on either single or multicore processor architectures. A variety of changes in the Dalvik VM, Bionic library, and elsewhere add support for symmetric multiprocessing in multicore environments. These optimizations can benefit all applications, even those that are single-threaded. For example, with two active cores, a single-threaded application might still see a performance boost if the Dalvik garbage collector runs on the second core. The system will arrange for this automatically.

    + + +

    Rich multimedia and connectivity

    + +

    HTTP Live streaming

    + +

    Applications can now pass an M3U playlist URL to the media framework to begin an HTTP Live streaming session. The media framework supports most of the HTTP Live streaming specification, including adaptive bit rate.

    + +

    Pluggable DRM framework

    + +

    Android 3.0 includes an extensible DRM framework that lets applications manage protected content according to a variety of DRM mechanisms that may be available on the device. For application developers, the framework API offers an consistent, unified API that simplifies the management of protected content, regardless of the underlying DRM engines.

    + +

    Digital media file transfer

    + +

    The platform includes built-in support for Media/Picture Transfer Protocol (MTP/PTP) over USB, which lets users easily transfer any type of media files between devices and to a host computer. Developers can build on this support, creating applications that let users create or manage media files that they may want to transfer or share across devices.

    + +

    More types of connectivity

    + +

    The platform offers new connectivity that developers can build on. API support for Bluetooth A2DP and HSP profiles lets applications query Bluetooth profiles for connected devices, audio state, and more, then notify the user. For example, a music application can check connectivity and status and let the user know that music is playing through a stereo headset. Applications can also register to receive system broadcasts of pre-defined vendor-specific AT commands, such as Platronics Xevent. For example, an application could receive broadcasts that indicate a connected device's battery level and could notify the user or take other action as needed. Applications can also take advantage of the platform's new support for full keyboards connected by USB or Bluetooth.

    + + +

    Enhancements for enterprise

    + +

    In Android 3.0, developers of device administration applications can support new types of policies, including policies for encrypted storage, password expiration, password history, and password complex characters required.

    + +

    Compatibility with existing apps

    + +

    Android 3.0 brings a new UI designed for tablets and other larger screen devices, but it also is fully compatible with applications developed for earlier versions of the platform, or for smaller screen sizes. Existing applications can seamlessly participate in the new holographic UI theme without code changes, by adding a single attribute in their manifest files. The platform emulates the Menu key, which is replaced by the overflow menu in the Action Bar in the new UI. Developers wanting to take fuller advantage of larger screen sizes can also create dedicated layouts and assets for larger screens and add them to their existing applications.

    + diff --git a/docs/html/about/versions/android-3.0.jd b/docs/html/about/versions/android-3.0.jd new file mode 100644 index 000000000000..76e07959135e --- /dev/null +++ b/docs/html/about/versions/android-3.0.jd @@ -0,0 +1,976 @@ +page.title=Android 3.0 Platform +sdk.platform.version=3.0 +sdk.platform.apiLevel=11 +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. API Level
    4. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + + +

    API Level: {@sdkPlatformApiLevel}

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a downloadable +component for the Android SDK. The downloadable platform includes an Android library and system +image, as well as a set of emulator skins and more. The downloadable platform includes no external +libraries.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + + + + + +

    API Overview

    + +

    The sections below provide a technical overview of what's new for developers in Android 3.0, +including new features and changes in the framework API since the previous version.

    + + + + + +

    Fragments

    + +

    A fragment is a new framework component that allows you to separate distinct elements of an +activity into self-contained modules that define their own UI and lifecycle. To create a +fragment, you must extend the {@link android.app.Fragment} class and implement several lifecycle +callback methods, similar to an {@link android.app.Activity}. You can then combine multiple +fragments in a single activity to build a multi-pane UI in which each +pane manages its own lifecycle and user inputs.

    + +

    You can also use a fragment without providing a UI and instead use the fragment as a worker +for the activity, such as to manage the progress of a download that occurs only while the +activity is running.

    + +

    Additionally:

    + + + +

    To manage the fragments in your activity, you must use the {@link +android.app.FragmentManager}, which provides several APIs for interacting with fragments, such +as finding fragments in the activity and popping fragments off the back stack to restore their +previous state.

    + +

    To perform a transaction, such as add or remove a fragment, you must create a {@link +android.app.FragmentTransaction}. You can then call methods such as {@link +android.app.FragmentTransaction#add add()} {@link android.app.FragmentTransaction#remove +remove()}, or {@link android.app.FragmentTransaction#replace replace()}. Once you've applied all +the changes you want to perform for the transaction, you must call {@link +android.app.FragmentTransaction#commit commit()} and the system applies the fragment transaction to +the activity.

    + +

    For more information about using fragments, read the Fragments documentation. Several +samples are also available in the +API Demos application.

    + + + + +

    Action Bar

    + +

    The Action Bar is a replacement for the traditional title bar at the top of the activity window. +It includes the application logo in the left corner and provides a new interface for items in the +Options Menu. Additionally, the +Action Bar allows you to:

    + + + +

    The Action Bar is standard for all applications that use the new holographic theme, which is +also standard when you set either the {@code +android:minSdkVersion} or {@code +android:targetSdkVersion} to {@code "11"}.

    + +

    For more information about the Action Bar, read the Action Bar documentation. Several +samples are also available in the +API Demos application.

    + + + + +

    System clipboard

    + +

    Applications can now copy and paste data (beyond mere text) to and from the system-wide +clipboard. Clipped data can be plain text, a URI, or an intent.

    + +

    By providing the system access to the data you want the user to copy, through a content provider, +the user can copy complex content (such as an image or data structure) from your application and +paste it into another application that supports that type of content.

    + +

    To start using the clipboard, get the global {@link android.content.ClipboardManager} object +by calling {@link android.content.Context#getSystemService getSystemService(CLIPBOARD_SERVICE)}.

    + +

    To copy an item to the clipboard, you need to create a new {@link +android.content.ClipData} object, which holds one or more {@link android.content.ClipData.Item} +objects, each describing a single entity. To create a {@link android.content.ClipData} object +containing just one {@link android.content.ClipData.Item}, you can use one of the helper methods, +such as {@link android.content.ClipData#newPlainText newPlainText()}, {@link +android.content.ClipData#newUri newUri()}, and {@link android.content.ClipData#newIntent +newIntent()}, which each return a {@link android.content.ClipData} object pre-loaded with the +{@link android.content.ClipData.Item} you provide.

    + +

    To add the {@link android.content.ClipData} to the clipboard, pass it to {@link +android.content.ClipboardManager#setPrimaryClip setPrimaryClip()} for your instance of {@link +android.content.ClipboardManager}.

    + +

    You can then read a file from the clipboard (in order to paste it) by calling {@link +android.content.ClipboardManager#getPrimaryClip()} on the {@link +android.content.ClipboardManager}. Handling the {@link android.content.ClipData} you receive can +be complicated and you need to be sure you can actually handle the data type in the clipboard +before attempting to paste it.

    + +

    The clipboard holds only one piece of clipped data (a {@link android.content.ClipData} +object) at a time, but one {@link android.content.ClipData} can contain multiple {@link +android.content.ClipData.Item}s.

    + +

    For more information, read the Copy +and Paste documentation. You can also see a simple implementation of copy and paste in the API Demos +sample and a more complete implementation in the Note Pad sample.

    + + + + +

    Drag and drop

    + +

    New APIs simplify drag and drop operations in your application's user interface. A drag +operation is the transfer of some kind of data—carried in a {@link android.content.ClipData} +object—from one place to another. The start and end point for the drag operation is a {@link +android.view.View}, so the APIs that directly handle the drag and drop operations are +in the {@link android.view.View} class.

    + +

    A drag and drop operation has a lifecycle that's defined by several drag actions—each +defined by a {@link android.view.DragEvent} object—such as {@link +android.view.DragEvent#ACTION_DRAG_STARTED}, {@link android.view.DragEvent#ACTION_DRAG_ENTERED}, and +{@link android.view.DragEvent#ACTION_DROP}. Each view that wants to participate in a drag +operation can listen for these actions.

    + +

    To begin dragging content in your activity, call {@link android.view.View#startDrag startDrag()} +on a {@link android.view.View}, providing a {@link android.content.ClipData} object that represents +the data to drag, a {@link android.view.View.DragShadowBuilder} to facilitate the "shadow" +that users see under their fingers while dragging, and an {@link java.lang.Object} that can share +information about the drag object with views that may receive the object.

    + +

    To accept a drag object in a {@link android.view.View} (receive the "drop"), register the view +with an {@link android.view.View.OnDragListener OnDragListener} by calling {@link +android.view.View#setOnDragListener setOnDragListener()}. When a drag event occurs on the view, the +system calls {@link android.view.View.OnDragListener#onDrag onDrag()} for the {@link +android.view.View.OnDragListener OnDragListener}, which receives a {@link android.view.DragEvent} +describing the type of drag action has occurred (such as {@link +android.view.DragEvent#ACTION_DRAG_STARTED}, {@link android.view.DragEvent#ACTION_DRAG_ENTERED}, and +{@link android.view.DragEvent#ACTION_DROP}). During a drag, the system repeatedly calls {@link +android.view.View.OnDragListener#onDrag onDrag()} for the view underneath the drag, to deliver a +stream of drag events. The receiving view can inquire the event type delivered to {@link +android.view.View#onDragEvent onDragEvent()} by calling {@link android.view.DragEvent#getAction +getAction()} on the {@link android.view.DragEvent}.

    + +

    Note: Although a drag event may carry a {@link +android.content.ClipData} object, this is not related to the system clipboard. A drag and drop +operation should never put the dragged data in the system clipboard.

    + +

    For more information, read the Dragging and +Dropping documentation. You can also see an implementation of drag and drop in the +API Demos application and the Honeycomb Gallery +application.

    + + + +

    App widgets

    + +

    Android 3.0 supports several new widget classes for more interactive app widgets on the users +Home screen, including: {@link android.widget.GridView}, {@link android.widget.ListView}, {@link +android.widget.StackView}, {@link android.widget.ViewFlipper}, and {@link +android.widget.AdapterViewFlipper}.

    + +

    More importantly, you can use the new {@link android.widget.RemoteViewsService} to create app +widgets with collections, using widgets such as {@link android.widget.GridView}, {@link +android.widget.ListView}, and {@link android.widget.StackView} that are backed by remote data, +such as from a content provider.

    + +

    The {@link android.appwidget.AppWidgetProviderInfo} class (defined in XML with an {@code +<appwidget-provider>} element) also supports two new fields: {@link +android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} and {@link +android.appwidget.AppWidgetProviderInfo#previewImage}. The {@link +android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} field lets you specify the view ID of the +app widget subview that should be auto-advanced by the app widget’s host. The +{@link android.appwidget.AppWidgetProviderInfo#previewImage} field specifies a preview of what the +app widget looks like and is shown to the user from the widget picker. If this field is not +supplied, the app widget's icon is used for the preview.

    + +

    To help create a preview image for your app widget (to specify in the {@link +android.appwidget.AppWidgetProviderInfo#previewImage} field), the Android emulator includes an +application called "Widget Preview." To create a preview image, launch this application, select the +app widget for your application and set it up how you'd like your preview image to appear, then save +it and place it in your application's drawable resources.

    + +

    You can see an implementation of the new app widget features in the StackView App Widget and Weather List Widget +applications.

    + + + +

    Status bar notifications

    + +

    The {@link android.app.Notification} APIs have been extended to support more content-rich status +bar notifications, plus a new {@link android.app.Notification.Builder} class allows you to easily +create {@link android.app.Notification} objects.

    +

    New features include:

    + + + + +

    Content loaders

    + +

    New framework APIs facilitate asynchronous loading of data using the {@link +android.content.Loader} class. You can use it in combination with UI components such as views and +fragments to dynamically load data from worker threads. The {@link +android.content.CursorLoader} subclass is specially designed to help you do so for data backed by +a {@link android.content.ContentProvider}.

    + +

    All you need to do is implement the {@link android.app.LoaderManager.LoaderCallbacks +LoaderCallbacks} interface to receive callbacks when a new loader is requested or the data has +changed, then call {@link android.app.LoaderManager#initLoader initLoader()} to initialize the +loader for your activity or fragment.

    + +

    For more information, read the Loaders documentation. You can also see +example code using loaders in the LoaderCursor +and +LoaderThrottle samples.

    + + + +

    Bluetooth A2DP and headset APIs

    + +

    Android now includes APIs for applications to verify the state of connected Bluetooth A2DP and +headset profile devices. For example, applications can identify when a Bluetooth headset is +connected for listening to music and notify the user as appropriate. Applications can also receive +broadcasts for vendor specific AT commands and notify the user about the state of the connected +device, such as when the connected device's battery is low.

    + +

    You can initialize the respective {@link android.bluetooth.BluetoothProfile} by calling {@link +android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()} with either the {@link +android.bluetooth.BluetoothProfile#A2DP} or {@link android.bluetooth.BluetoothProfile#HEADSET} +profile constant and a {@link android.bluetooth.BluetoothProfile.ServiceListener} to receive +callbacks when the Bluetooth client is connected or disconnected.

    + + + + +

    Animation framework

    + +

    An all new flexible animation framework allows you to animate arbitrary properties of any object +(View, Drawable, Fragment, Object, or anything else). It allows you to define several aspects of an +animation, such as:

    + + +

    You can define these animation aspects, and others, for an object's int, float, and hexadecimal +color values, by default. That is, when an object has a property field for one of these types, you +can change its value over time to affect an animation. To animate any other type of value, you tell +the system how to calculate the values for that given type, by implementing the {@link +android.animation.TypeEvaluator} interface.

    + +

    There are two animators you can use to animate the values of a property: {@link +android.animation.ValueAnimator} and {@link android.animation.ObjectAnimator}. The {@link +android.animation.ValueAnimator} computes the animation values, but is not aware of the specific +object or property that is animated as a result. It simply performs the calculations, and you must +listen for the updates and process the data with your own logic. The {@link +android.animation.ObjectAnimator} is a subclass of {@link android.animation.ValueAnimator} and +allows you to set the object and property to animate, and it handles all animation work. +That is, you give the {@link android.animation.ObjectAnimator} the object to animate, the +property of the object to change over time, and a set of values to apply to the property over +time, then start the animation.

    + +

    Additionally, the {@link android.animation.LayoutTransition} class enables automatic transition +animations for changes you make to your activity layout. To enable transitions for part of the +layout, create a {@link android.animation.LayoutTransition} object and set it on +any {@link android.view.ViewGroup} by calling {@link +android.view.ViewGroup#setLayoutTransition setLayoutTransition()}. This causes default +animations to run whenever items are added to or removed from the group. To specify custom +animations, call {@link android.animation.LayoutTransition#setAnimator setAnimator()} on the {@link +android.animation.LayoutTransition} and provide a custom {@link android.animation.Animator}, +such as a {@link android.animation.ValueAnimator} or {@link android.animation.ObjectAnimator} +discussed above.

    + +

    For more information, see the Property Animation documentation. You can +also see several samples using the animation APIs in the API +Demos application.

    + + + + +

    Extended UI framework

    + + + + + +

    Graphics

    + +
    + + + + +

    Media

    + + + + + + +

    Keyboard support

    + + + + + + +

    Split touch events

    + +

    Previously, only a single view could accept touch events at one time. Android 3.0 +adds support for splitting touch events across views and even windows, so different views can accept +simultaneous touch events.

    + +

    Split touch events is enabled by default when an application targets +Android 3.0. That is, when the application has set either the {@code android:minSdkVersion} +or {@code +android:targetSdkVersion} attribute's value to {@code "11"}.

    + +

    However, the following properties allow you to disable split touch events across views inside +specific view groups and across windows.

    + + + + + +

    WebKit

    + + + + + +

    Browser

    + +

    The Browser application adds the following features to support web applications:

    + + + + + +

    JSON utilities

    + +

    New classes, {@link android.util.JsonReader} and {@link android.util.JsonWriter}, help you +read and write JSON streams. The new APIs complement the {@link org.json} classes, which manipulate +a document in memory.

    + +

    You can create an instance of {@link android.util.JsonReader} by calling +its constructor method and passing the {@link java.io.InputStreamReader} that feeds the JSON string. +Then begin reading an object by calling {@link android.util.JsonReader#beginObject()}, read a +key name with {@link android.util.JsonReader#nextName()}, read the value using methods +respective to the type, such as {@link android.util.JsonReader#nextString()} and {@link +android.util.JsonReader#nextInt()}, and continue doing so while {@link +android.util.JsonReader#hasNext()} is true.

    + +

    You can create an instance of {@link android.util.JsonWriter} by calling its constructor and +passing the appropriate {@link java.io.OutputStreamWriter}. Then write the JSON data in a manner +similar to the reader, using {@link android.util.JsonWriter#name name()} to add a property name +and an appropriate {@link android.util.JsonWriter#value value()} method to add the respective +value.

    + +

    These classes are strict by default. The {@link android.util.JsonReader#setLenient setLenient()} +method in each class configures them to be more liberal in what they accept. This lenient +parse mode is also compatible with the {@link org.json}'s default parser.

    + + + + +

    New feature constants

    + +

    The {@code <uses-feature>} +manfest element should be used to inform external entities (such as Google Play) of the set of +hardware and software features on which your application depends. In this release, Android adds the +following new constants that applications can declare with this element:

    + + + + + + +

    New permissions

    + + + + + +

    New platform technologies

    + + + + + +

    API differences report

    + +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level +{@sdkPlatformApiLevel}), see the API Differences Report.

    + + + + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, +you need compile the application against the Android library that is provided in +the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might +also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" +attribute to the <uses-sdk> element in the application's +manifest. If your application is designed to run only on Android 2.3 and higher, +declaring the attribute prevents the application from being installed on earlier +versions of the platform.

    + +

    For more information, read What is API +Level?

    diff --git a/docs/html/about/versions/android-3.1-highlights.jd b/docs/html/about/versions/android-3.1-highlights.jd new file mode 100644 index 000000000000..5283c2a45861 --- /dev/null +++ b/docs/html/about/versions/android-3.1-highlights.jd @@ -0,0 +1,381 @@ +page.title=Honeycomb MR1 + +@jd:body + + + + +

    Welcome to Android 3.1!

    + +

    Android 3.1 is an incremental platform release that refines many of the +features introduced in Android 3.0. It builds on the same tablet-optimized UI +and features offered in Android 3.0 and adds several new capabilities for +users and developers. This document provides an overview of the new features and +technologies introduced in Android 3.1. For a more detailed look at new +developer APIs, see the API +Overview document.

    + +

    For a high-level introduction to Android 3.0, please see the Android 3.0 Platform +Highlights.

    + + + +

    New User Features

    + +
    +
    +
    Figure 1. An Android 3.1 Home screen.
    +
    + +

    UI refinements

    + +

    The Android 3.1 platform adds a variety of refinements to make the user +interface more intuitive and more efficient to use.

    + +

    UI transitions are improved throughout the system and across the standard +apps. The Launcher animation is optimized for faster, smoother transition to and +from the Apps list. Adjustments in color, positioning, and text make UI elements +easier to see, understand, and use. Accessibility is improved with consistent +audible feedback throughout the UI and a new setting to let users customize the +touch-hold interval to meet their needs.

    + +

    Navigation to and from the five home screens is now easier — touching +the Home button in the system bar now takes you to the home screen most recently +used. Settings offers an improved view of internal storage, +showing the storage used by a larger set of file types.

    + +

    Connectivity for USB accessories

    + +

    Android 3.1 adds broad platform support for a variety of USB-connected +peripherals and accessories. Users can attach many types of input devices +(keyboards, mice, game controllers) and digital cameras. Applications can build +on the platform’s USB support to extend connectivity to almost any type of USB +device.

    + +

    The platform also adds new support for USB accessories — external +hardware devices designed to attach to Android-powered devices as USB hosts. When an +accessory is attached, the framework will look for a corresponding application +and offer to launch it for the user. The accessory can also present a URL +to the user, for downloading an appropriate application if one is not already +installed. Users can interact with the application to control powered accessories such +as robotics controllers; docking stations; diagnostic and musical equipment; +kiosks; card readers; and much more.

    + +

    The platform’s USB capabilities rely on components in device hardware, so +support for USB on specific devices may vary and is determined by device +manufacturers.

    + +
    +
    +
    Figure 2. The Recent Apps menu is now expandable and scrollable.
    +
    + +

    Expanded Recent Apps list

    + +

    For improved multitasking and instant visual access to a much larger number +of apps, the Recent Apps list is now expandable. Users can now scroll the list +of recent apps vertically to see thumbnail images all of the tasks in progress +and recently used apps, then touch a thumbnail to jump back into that task.

    + +

    Resizeable Home screen widgets

    + +

    For more flexible Home screen customization, users can now resize their Home +screen widgets using drag bars provided by the system. Users can expand widgets +both horizontally and/or vertically to include more content, where supported by +each widget.

    + + +

    Support for external keyboards +and pointing devices

    + +

    Users can now attach almost any type of external keyboard or mouse to their +Android-powered devices, to create a familiar environment and work more +efficiently. One or more input devices can be attached to the system simultaneously +over USB and/or Bluetooth HID, in any combination. No special configuration or +driver is needed, in most cases. When multiple devices are connected, users can +conveniently manage the active keyboard and IME using the keyboard settings that +are available from the System bar.

    + +

    For pointing devices, the platform supports most types of mouse with a single +button and optionally a scroll wheel, as well as similar devices such as +trackballs. When these are connected, users can interact with the UI using +point, select, drag, scroll, hover, and other standard actions.

    + +

    Support for joysticks and gamepads

    + +

    To make the platform even better for gaming, Android 3.1 adds support for +most PC joysticks and gamepads that are connected over USB or Bluetooth HID.

    + +

    For example, users can connect PlayStation®3 and Xbox 360® +game controllers over USB (but not Bluetooth), Logitech Dual Action™ gamepads and +flight sticks, or a car racing controller. Game controllers that use proprietary +networking or pairing are not supported by default, but in general, the platform +supports most PC-connectible joysticks and gamepads.

    + +

    Robust Wi-Fi networking

    + +

    Android 3.1 adds robust Wi-Fi features, to make sure that users and their +apps can take full advantage of higher-speed Wi-Fi access at home, at work, and +while away.

    + +

    A new high-performance Wi-Fi lock lets applications maintain +high-performance Wi-Fi connections even when the device screen is off. Users can +take advantage of this to play continuous streamed music, video, and voice +services for long periods, even when the device is otherwise idle and the screen +is off.

    + +

    Users can now configure an HTTP proxy for each individual Wi-Fi access +point, by touch-hold of the access point in Settings. The browser uses the HTTP +proxy when communicating with the network over the access point and other apps +may also choose to do so. The platform also provides backup and restore of the +user-defined IP and proxy settings.

    +

    The platform adds support for Preferred Network Offload (PNO), a background +scanning capability that conserves battery power savings in cases where Wi-Fi +needs to be available continuously for long periods of time.

    + +

    Updated set of standard apps

    + +

    The Android 3.1 platform includes an updated set of standard applications +that are optimized for use on larger screen devices. The sections below +highlight some of the new features.

    + +
    +
    +
    Figure 3. Quick Controls menu in the Browser.
    +
    +
    + +

    Browser

    + +

    The Browser app includes a variety of new features and UI improvements that +make viewing web content simpler, faster, and more convenient.

    + +

    The Quick Controls UI, accessible from Browser Settings, is extended and +redesigned. Users can now use the controls to view thumbnails of open tabs and +close the active tab, as well as access the overflow menu for instant access to +Settings and other controls.

    + +

    To ensure a consistent viewing experience, the Browser extends it's support +for popular web standards such as CSS 3D, animations, and CSS fixed +positioning to all sites, mobile or desktop. It also adds support for embedded +playback of HTML5 video content. To make it easier to manage favorite +content, users can now save a web page locally for offline viewing, including +all styling and images. For convenience when visiting Google sites, an improved +auto-login UI lets users sign in quickly and manage access when multiple users +are sharing a device.

    + +

    For best performance, the Browser adds support for plugins that use hardware +accelerated rendering. Page zoom performance is also dramatically improved, +making it faster to navigate and view web pages.

    + +

    Gallery

    + +

    The Gallery app now supports Picture Transfer Protocol (PTP), so that users +can connect their cameras over USB and import their pictures to Gallery with a +single touch. The app also copies the pictures to local storage and provides an +indicator to let users see how much space is available.

    + +
    +
    +
    Figure +4. Home screen widgets can now be resized.
    + +

    Calendar

    + +

    Calendar grids are larger, for better readability and more accurate +touch-targeting. Additionally, users can create a larger viewing area for grids +by hiding the calendar list controls. Controls in the date picker are +redesigned, making them easier to see and use. + + +

    Contacts

    + +

    The Contacts app now lets you locate contacts more easily using full text +search. Search returns matching results from all fields that are stored for a +contact. +

    + +

    Email

    + +

    When replying or forwarding an HTML message, The Email app now sends both +plain text and HTML bodies as a multi-part mime message. This ensures that the +message will be formatted properly for all recipients. Folder prefixes for IMAP +accounts are now easier to define and manage. To conserve battery power and +minimize cell data usage, the application now prefetches email from the server +only when the device is connected to a Wi-Fi access point.

    + +

    An updated Home screen widget give users quick access to more email. Users +can touch Email icon at the top of the widget to cycle through labels such as +Inbox, Unread, and Starred. The widget itself is now resizable, both +horizontally and vertically.

    + +

    Enterprise support

    + +

    Users can now configure an HTTP proxy for each connected Wi-Fi access point. +This lets administrators work with users to set a proxy hostname, port, and any +bypass subdomains. This proxy configuration is automatically used by the Browser +when the Wi-Fi access point is connected, and may optionally be used by other +apps. The proxy and IP configuration is now backed up and restored across system +updates and resets.

    + +

    To meet the needs of tablet users, the platform now allows a "encrypted +storage card" device policy to be accepted on devices with emulated storage +cards and encrypted primary storage.

    + + +

    New Developer Features

    + +

    The Android 3.1 platform adds refinements and new capabilities that +developers can build on, to create powerful and engaging application experiences +on tablets and other large-screen devices.

    + +

    Open Accessory API for rich interaction with +peripherals

    + +

    Android 3.1 introduces a new API for integrating hardware accessories with +applications running on the platform. The API provides a way to interact across +a wide range of peripherals, from robotics controllers to musical equipment, +exercise bicycles, and more.

    + +

    The API is based on a new USB (Universal Serial Bus) stack and services +that are built into the platform. The platform provides services for discovering +and identifying connected hardware, as well as for notifying interested +applications that the hardware is available.

    + +

    When a user plugs in a USB accessory, the platform receives +identifying information such as product name, accessory type, manufacturer, and +version. The platform sets up communication with the accessory and uses its +information to notify and launch a targeted app, if one is available. Optionally, +an accessory can provide a URL that lets users find and download an +app that works with the accessory. These discovery features make +first-time setup easier for the user and ensure that an appropriate application +is available for interacting with the connected hardware.

    + +

    For application developers and accessory manufacturers, accessory mode offers +many new ways to engage users and build powerful interaction experiences with +connected hardware.

    + +

    To learn more about how to develop applications that interact with +accessories, see the USB +Accessory documentation.

    + +

    USB host API

    + +

    Android 3.1 provides built-in platform support for USB host mode and exposes +an API that lets applications manage connected peripherals. On devices that +support host mode, applications can use the API to identify and communicate with +connected devices such as audio devices. input devices, communications devices, +hubs, cameras, and more.

    + +

    To learn more about how to develop applications that interact with +USB devices, see the USB +Host documentation.

    + +

    Input from mice, joysticks, and gamepads

    + +

    Android 3.1 extends the input event system to support a variety of new input +sources and motion events, across all views and windows. Developers can build on +these capabilities to let users interact with their applications using mice, +trackballs, joysticks, gamepads, and other devices, in addition to keyboards and +touchscreens.

    + +

    For mouse and trackball input, the platform supports two new motion event +actions: scroll (horizontal or vertical) such as from a scrollwheel; and hover, +which reports the location of the mouse when no buttons are pressed. +Applications can handle these events in any way needed.

    + +

    For joysticks and gamepads, the platform provides a large number of motion +axes that applications can use from a given input source, such as X, Y, Hat X, +Hat Y, rotation, throttle, pressure, size, touch, tool, orientation, and others. +Developers can also define custom axes if needed, to capture motion in +additional ways. The platform provides motion events to applications as a batch, +and applications can query the details of the movements included in the batch, +for more efficient and precise handling of events.

    + +

    Applications can query for the list of connected input devices and the motion +ranges (axes) supported by each device. Applications can also handle multiple +input and motion events from a single input device. For example, an application +can use mouse and joystick and mouse event sources from a single input +device.

    + +

    Resizable Home screen widgets

    + +

    Developers can now create Home screen widgets that users can resize +horizontally, vertically, or both. By simply adding an attribute to the +declaration of a widget, the widget becomes resizable horizontally, vertically, +or both. This lets users customize the display of the widget content and display +more of it on their Home screens.

    + +

    MTP API for integrating with external cameras

    + +

    In Android 3.1, a new MTP (Media Transfer Protocol) API lets developers write +apps that interact directly with connected cameras and other PTP devices. The +new API makes it easy for applications to receive notifications when devices are +attached and removed, manage files and storage on those devices, and transfer +files and metadata to and from them. The MTP API implements the PTP (Picture +Transfer Protocol) subset of the MTP specification.

    + +

    RTP API, for control over audio streaming sessions

    + +

    Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) +stack, which applications can use to directly manage on-demand or interactive +data streaming. In particular, apps that provide VOIP, push-to-talk, +conferencing, and audio streaming can use the API to initiate sessions and +transmit or receive data streams over any available network.

    + +

    Performance optimizations

    + +

    Android 3.1 includes a variety of performance optimizations that help make +applications faster and more responsive. Some of the optimizations include:

    + +
      +
    • A new LRU cache class lets applications benefit from efficient caching. +Applications can use the class to reduce the time spent computing or downloading +data from the network, while maintaining a sensible memory footprint for the +cached data.
    • +
    • The UI framework now supports partial invalidates in hardware-accelerated +Views, which makes drawing operations in those Views more efficient.
    • +
    • A new graphics method, {@link android.graphics.Bitmap#setHasAlpha(boolean) +setHasAlpha()}, allows apps to hint that a given bitmap is opaque. This provides +an extra performance boost for some types of blits and is especially useful for +applications that use ARGB_8888 bitmaps.
    • +
    + diff --git a/docs/html/about/versions/android-3.1.jd b/docs/html/about/versions/android-3.1.jd new file mode 100644 index 000000000000..2a845f0e4b51 --- /dev/null +++ b/docs/html/about/versions/android-3.1.jd @@ -0,0 +1,863 @@ +page.title=Android 3.1 Platform +sdk.platform.version=3.1 +sdk.platform.apiLevel=12 +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. API Level
    4. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + + +

    API Level: {@sdkPlatformApiLevel}

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. The downloadable platform includes no external libraries.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + + +

    API Overview

    + +

    The sections below provide a technical overview of what's new for developers +in Android 3.1, including new features and changes in the framework API since +the previous version.

    + +

    USB APIs

    + +

    Android 3.1 introduces powerful new APIs for +integrating connected peripherals with applications running on the platform. +The APIs are based on a USB (Universal Serial Bus) stack and services that are +built into the platform, including support for both USB host and device +interactions. Using the APIs, developers can create applications that are able to +discover, communicate with, and manage a variety of device types connected over +USB.

    + +

    The stack and APIs distinguish two basic types of USB hardware, based on +whether the Android-powered device is acting as host or the external hardware +is acting as host:

    + +
      +
    • A USB device is a piece of connected hardware that depends on the +Android-powered device to serve as host. For example, most input devices, mice, +and joysticks are USB devices, as are many cameras, hubs, and so on.
    • +
    • A USB accessory is a piece of connected hardware that has a USB +host controller, provides power, and is designed to communicate with +Android-powered devices over USB, A variety of peripherals can connect as +accessories, from robotics controllers to musical equipment, exercise bicycles, +and more.
    • +
    + +

    For both types — USB devices and USB accessories — the +platform's USB APIs support discovery by intent broadcast when attached or +detached, as well as standard interfaces, endpoints, and transfer modes +(control, bulk, and interrupt).

    + +

    The USB APIs are available in the package {@link android.hardware.usb}. The +central class is {@link android.hardware.usb.UsbManager}, which provides +helper methods for identifying and communicating with +both USB devices and USB accessories. Applications can acquire an instance of +{@link android.hardware.usb.UsbManager} and then query for the list of attached +devices or accessories and then communicate with or manage them. +{@link android.hardware.usb.UsbManager} also declares intent actions that the +system broadcasts, to announce when a USB device or accessory is attached or +detached.

    + +

    Other classes include:

    + +
      +
    • {@link android.hardware.usb.UsbDevice}, a class representing external +hardware connected as a USB device (with the Android-powered device acting as +host).
    • +
    • {@link android.hardware.usb.UsbAccessory}, representing external hardware +connected as the USB host (with the Android-powered device acting as a USB +device).
    • +
    • {@link android.hardware.usb.UsbInterface} and {@link +android.hardware.usb.UsbEndpoint}, which provide access to standard USB +interfaces and endpoints for a device.
    • +
    • {@link android.hardware.usb.UsbDeviceConnection} and {@link +android.hardware.usb.UsbRequest}, for sending and receiving data and control +messages to or from a USB device, sychronously and asynchronously. +
    • {@link android.hardware.usb.UsbConstants}, which provides constants for +declaring endpoint types, device classes, and so on.
    • +
    + +

    Note that although the USB stack is built into the platform, actual support +for USB host and open accessory modes on specific devices is determined by +their manufacturers. In particular, host mode relies on appropriate USB +controller hardware in the Android-powered device.

    + +

    Additionally, developers can request filtering on Google Play, such that +their applications are not availabe to users whose devices do not provide the +appropriate USB support. To request filtering, add one or both of the elements +below to the application manifest, as appropriate:

    + +
      +
    • If the application should only be visible to devices that support USB +host mode (connection of USB devices), declare this element: +

      <uses-feature + android:name="android.hardware.usb.host" + android:required="true">

      +
    • +
    • If the application should only be visible to devices that support USB +accessories (connection of USB hosts), declare this element: +

      <uses-feature + android:name="android.hardware.usb.accessory" + android:required="true">

      +
    • +
    + +

    For complete information about how to develop applications that interact with +USB accessories, please see the +developer documentation.

    + +

    To look at sample applications that use the USB host API, see ADB Test and Missile +Launcher

    + +

    MTP/PTP API

    + +

    Android 3.1 exposes a new MTP API that lets applications interact directly +with connected cameras and other PTP devices. The new API makes it easy for an +application to receive notifications when devices are attached and removed, +manage files and storage on those devices, and transfer files and metadata to +and from them. The MTP API implements the PTP (Picture Transfer Protocol) subset +of the MTP (Media Transfer Protocol) specification.

    + +

    The MTP API is available in the {@link android.mtp} package and provides +these classes:

    + +
      +
    • The {@link android.mtp.MtpDevice} encapsulates an MTP device that is +connected over the USB host bus. An application can instantiate an object of +this type and then use its methods to get information about the device and +objects stored on it, as well as opening the connection and transferring data. +Some of the methods include: +
        +
      • {@link android.mtp.MtpDevice#getObjectHandles(int, int, int) +getObjectHandles()} returns a list of handles for all objects on the device that +match a specified format and parent. To get information about an object, an +application can pass a handle to {@link android.mtp.MtpDevice#getObjectInfo(int) +getObjectInfo()}.
      • +
      • {@link android.mtp.MtpDevice#importFile(int, java.lang.String) +importFile()} lets an application copy data for an object to a file in external +storage. This call may block for an arbitrary amount of time depending on the +size of the data and speed of the devices, so should be made from a spearate +thread.
      • +
      • {@link +android.mtp.MtpDevice#open(android.hardware.usb.UsbDeviceConnection) open()} +lets an application open a connected MTP/PTP device.
      • +
      • {@link android.mtp.MtpDevice#getThumbnail(int) getThumbnail()} returns +the thumbnail of the object as a byte array.
      • +
      +
    • +
    • {@link android.mtp.MtpStorageInfo} holds information about about a storage +unit on an MTP device, corresponding to the StorageInfo Dataset described in +section 5.2.2 of the MTP specification. Methods in the class let an application +get a storage unit’s description string, free space, maximum storage capacity, +storage ID, and volume identifier.
    • +
    • {@link android.mtp.MtpDeviceInfo} holds information about an MTP device +corresponding to the DeviceInfo Dataset described in section 5.1.1 of the MTP +specification. Methods in the class let applications get a device’s +manufacturer, model, serial number, and version.
    • +
    • {@link android.mtp.MtpObjectInfo} holds information about an object stored +on an MTP device, corresponding to the ObjectInfo Dataset described in section +5.3.1 of the MTP specification. Methods in the class let applications get an +object’s size, data format, association type, creation date, and thumbnail +information.
    • +
    • {@link android.mtp.MtpConstants} provides constants for declaring MTP file +format codes, association type, and protection status.
    • +
    + +

    Support for new input devices and motion events

    + +

    Android 3.1 extends the input subsystem to support new input devices and new +types of motion events, across all views and windows. Developers can build on +these capabilities to let users interact with their applications using mice, +trackballs, joysticks, gamepads, and other devices, in addition to keyboards and +touchscreens.

    + +

    For handling mouse, scrollwheel, and trackball input, the platform supports +two new motion event actions:

    +
      +
    • {@link android.view.MotionEvent#ACTION_SCROLL}, which describes the pointer +location at which a non-touch scroll motion, such as from a mouse scroll wheel, +took place. In the MotionEvent, the value of the {@link +android.view.MotionEvent#AXIS_HSCROLL} and {@link +android.view.MotionEvent#AXIS_VSCROLL} axes specify the relative scroll +movement.
    • +
    • {@link android.view.MotionEvent#ACTION_HOVER_MOVE}, reports the current +position of the mouse when no buttons are pressed, as well as any intermediate +points since the last HOVER_MOVE event. Hover enter and exit +notifications are not yet supported.
    • +
    + +

    To support joysticks and gamepads, the {@link android.view.InputDevice} class +includes these new input device sources:

    +
      +
    • {@link android.view.InputDevice#SOURCE_CLASS_JOYSTICK} — the source +device has joystick axes.
    • +
    • {@link android.view.InputDevice#SOURCE_CLASS_BUTTON} — the source +device has buttons or keys.
    • +
    • {@link android.view.InputDevice#SOURCE_GAMEPAD} — the source device +has gamepad buttons such as {@link android.view.KeyEvent#KEYCODE_BUTTON_A} +or {@link android.view.KeyEvent#KEYCODE_BUTTON_B}. Implies +{@link android.view.InputDevice#SOURCE_CLASS_BUTTON}
    • +
    • {@link android.view.InputDevice#SOURCE_JOYSTICK} — the source device +has joystick axes. Implies SOURCE_CLASS_JOYSTICK.
    • +
    + +

    To describe motion events from these new sources, as well as those from mice +and trackballs, the platform now defines axis codes on {@link +android.view.MotionEvent}, similar to how it defines key codes on {@link +android.view.KeyEvent}. New axis codes for joysticks +and game controllers include +{@link android.view.MotionEvent#AXIS_HAT_X}, {@link +android.view.MotionEvent#AXIS_HAT_Y}, {@link +android.view.MotionEvent#AXIS_RTRIGGER}, {@link +android.view.MotionEvent#AXIS_ORIENTATION}, {@link +android.view.MotionEvent#AXIS_THROTTLE}, and many others. +Existing {@link android.view.MotionEvent} axes are represented by {@link +android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, +{@link android.view.MotionEvent#AXIS_PRESSURE}, {@link +android.view.MotionEvent#AXIS_SIZE}, {@link +android.view.MotionEvent#AXIS_TOUCH_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOUCH_MINOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MINOR}, and {@link +android.view.MotionEvent#AXIS_ORIENTATION}.

    + +

    Additionally, {@link android.view.MotionEvent} defines a number of generic +axis codes that are used when the framework does not know how to map a +particular axis. Specific devices can use the generic axis codes to pass custom +motion data to applications. For a full list of axes and their intended +interpretations, see the {@link android.view.MotionEvent} class documentation. +

    + +

    The platform provides motion events to applications in batches, so a single +event may contain a current position and multiple so-called historical movements. +Applications should use {@link android.view.MotionEvent#getHistorySize()} to get +the number of historical samples, then retrieve and process all historical +samples in order using {@link +android.view.MotionEvent#getHistoricalAxisValue(int, int, int) +getHistoricalAxisValue()}. After that, applications should process the current +sample using {@link android.view.MotionEvent#getAxisValue(int) getAxisValue()}. +

    + +

    Some axes can be retrieved using special accessor methods. For example, +instead of calling {@link android.view.MotionEvent#getAxisValue(int) +getAxisValue()}, applications can call {@link android.view.MotionEvent#getX(int) +getX()}. Axes that have built-in accessors include {@link +android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, +{@link android.view.MotionEvent#AXIS_PRESSURE}, {@link +android.view.MotionEvent#AXIS_SIZE}, {@link +android.view.MotionEvent#AXIS_TOUCH_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOUCH_MINOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MAJOR}, {@link +android.view.MotionEvent#AXIS_TOOL_MINOR}, and {@link +android.view.MotionEvent#AXIS_ORIENTATION}.

    + +

    Each input device has a unique, system-assigned ID and may also provide +multiple sources. When a device provides multiple sources, more than one source +can provide axis data using the same axis. For example, a touch event coming +from the touch source uses the X axis for screen position data, while a joystick +event coming from the joystick source will use the X axis for the stick position +instead. For this reason, it's important for applications to interpret axis +values according to the source from which they originate. When handling a motion +event, applications should use methods on the {@link android.view.InputDevice} +class to determine the axes supported by a device or source. Specifically, +applications can use {@link android.view.InputDevice#getMotionRanges() +getMotionRanges()} to query for all axes of a device or all axes of a given +source of the device. In both cases, the range information for axes returned in +the {@link android.view.InputDevice.MotionRange} object specifies the source for +each axis value.

    + +

    Finally, since the motion events from joysticks, gamepads, mice, and +trackballs are not touch events, the platform adds a new callback method for +passing them to a {@link android.view.View} as "generic" motion events. +Specifically, it reports the non-touch motion events to +{@link android.view.View}s through a call to {@link +android.view.View#onGenericMotionEvent(android.view.MotionEvent) +onGenericMotionEvent()}, rather than to {@link +android.view.View#onTouchEvent(android.view.MotionEvent) +onTouchEvent()}.

    + +

    The platform dispatches generic motion events differently, depending on the +event source class. {@link android.view.InputDevice#SOURCE_CLASS_POINTER} events +go to the {@link android.view.View} under the pointer, similar to how touch +events work. All others go to the currently focused {@link android.view.View}. +For example, this means a {@link android.view.View} must take focus in order to +receive joystick events. If needed, applications can handle these events at the +level of Activity or Dialog by implementing {@link +android.view.View#onGenericMotionEvent(android.view.MotionEvent) +onGenericMotionEvent()} there instead.

    + +

    To look at a sample application that uses joystick motion +events, see GameControllerInput +and GameView.

    + +

    RTP API

    + +

    Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) +stack, which applications can use to manage on-demand or interactive data +streaming. In particular, apps that provide VOIP, push-to-talk, conferencing, +and audio streaming can use the API to initiate sessions and transmit or receive +data streams over any available network.

    + +

    The RTP API is available in the {@link android.net.rtp} package. Classes +include:

    +
      +
    • {@link android.net.rtp.RtpStream}, the base class of streams that send and +receive network packets with media payloads over RTP.
    • +
    • {@link android.net.rtp.AudioStream}, a subclass of {@link +android.net.rtp.RtpStream} that carries audio payloads over RTP.
    • +
    • {@link android.net.rtp.AudioGroup}, a local audio hub for managing and +mixing the device speaker, microphone, and {@link android.net.rtp.AudioStream}.
    • +
    • {@link android.net.rtp.AudioCodec}, which holds a collection of codecs that +you define for an {@link android.net.rtp.AudioStream}.
    • +
    + +

    To support audio conferencing and similar usages, an application instantiates +two classes as endpoints for the stream:

    + +
      +
    • {@link android.net.rtp.AudioStream} specifies a remote endpoint and consists +of network mapping and a configured {@link android.net.rtp.AudioCodec}.
    • +
    • {@link android.net.rtp.AudioGroup} represents the local endpoint for one +or more {@link android.net.rtp.AudioStream}s. The {@link android.net.rtp.AudioGroup} mixes +all the {@link android.net.rtp.AudioStream}s and optionally interacts with the device +speaker and the microphone at the same time.
    • +
    + +

    The simplest usage involves a single remote endpoint and local endpoint. +For more complex usages, please refer to the limitations described for +{@link android.net.rtp.AudioGroup}.

    + +

    To use the RTP API, applications must request permission from the user by +declaring <uses-permission +android:name="android.permission.INTERNET"> +in their manifest files. To acquire the device microphone, the <uses-permission +android:name="android.permission.RECORD_AUDIO"> permission is also required.

    + +

    Resizable app widgets

    + +

    Starting in Android 3.1, developers can make their homescreen widgets +resizeable — horizontally, vertically, or on both axes. Users touch-hold a +widget to show its resize handles, then drag the horizontal and/or vertical +handles to change the size on the layout grid.

    + +

    Developers can make any Home screen widget resizeable by defining a +resizeMode attribute in the widget's {@link +android.appwidget.AppWidgetProviderInfo} metadata. Values for the +resizeMode attribute include "horizontal", "vertical", and "none". +To declare a widget as resizeable horizontally and vertically, supply the value +"horizontal|vertical". + +

    Here's an example:

    + +
    <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:minWidth="294dp"
    +    android:minHeight="72dp"
    +    android:updatePeriodMillis="86400000"
    +    android:previewImage="@drawable/preview"
    +    android:initialLayout="@layout/example_appwidget"
    +    android:configure="com.example.android.ExampleAppWidgetConfigure"
    +    android:resizeMode="horizontal|vertical" >
    +</appwidget-provider>
    + +

    For more information about Home screen widgets, see the App Widgets +documentation.

    + +

    Animation framework

    + +
      +
    • New ViewPropertyAnimator class +
        +
      • A new {@link android.view.ViewPropertyAnimator} class provides a +convenient +way for developers to animate select properties on {@link android.view.View} objects. The class +automaties and optimizes the animation of the properties and makes it easier to +manage multiple simulataneous animations on a {@link android.view.View} object. +

        Using the {@link android.view.ViewPropertyAnimator} is straightforward. To animate properties for +a {@link android.view.View}, call {@link android.view.View#animate()} to +construct a {@link android.view.ViewPropertyAnimator} object for that {@link android.view.View}. Use the +methods on the {@link android.view.ViewPropertyAnimator} to specify what property to +animate and how to animate it. For example, to fade the {@link android.view.View} to transparent, +call alpha(0);. The {@link android.view.ViewPropertyAnimator} object +handles the details of configuring the underlying {@link +android.animation.Animator} class and starting it, then rendering the +animation.

      • +
      +
    • +
    • Animation background color +
        +
      • New {@link android.view.animation.Animation#getBackgroundColor()} and + {@link android.view.animation.Animation#setBackgroundColor(int)} methods let + you get/set the background color behind animations, for window animations +only. Currently the background must be black, with any desired alpha level.
      • +
      +
    • +
    • Getting animated fraction from ViewAnimator +
        +
      • A new {@link android.animation.ValueAnimator#getAnimatedFraction()} +method +lets you get the current animation fraction — the elapsed/interpolated +fraction used in the most recent frame update — from a {@link +android.animation.ValueAnimator}.
      • +
      +
    • +
    + +

    UI framework

    +
      +
    • Forced rendering of a layer +
        +
      • A new {@link android.view.View#buildLayer()} method lets an application +force a View's layer to be created and the View rendered into it immediately. +For example, an application could use this method to render a View into its +layer before starting an animation. If the View is complex, rendering it into +the layer before starting the animation will avoid skipping frames.
      • +
      +
    • +
    • Camera distance +
        +
      • Applications can use a new method +{@link android.view.View#setCameraDistance(float)} to set the distance from the +camera +to a View. This gives applications improved control over 3D transformations of +the View, such as rotations.
      • +
      +
    • +
    • Getting a calendar view from a DatePicker +
        +
      • A new {@link android.widget.DatePicker#getCalendarView()} method + lets you get a {@link android.widget.CalendarView} from a {@link +android.widget.DatePicker} + instance.
      • +
      +
    • +
    • Getting callbacks when views are detached +
        +
      • A new {@link android.view.View.OnAttachStateChangeListener} lets you +receive +callbacks when a View is attached or detached from its window. Use {@link +android.view.View#addOnAttachStateChangeListener(android.view.View.OnAttachStateChangeListener) addOnAttachStateChangeListener()} +to add a listener and {@link +android.view.View#removeOnAttachStateChangeListener(android.view.View.OnAttachStateChangeListener) addOnAttachStateChangeListener()} to remove it.
      • +
      +
    • +
    • Fragment breadcrumb listener, new onInflate() signature +
        +
      • A new method, {@link +android.app.FragmentBreadCrumbs#setOnBreadCrumbClickListener(android.app.FragmentBreadCrumbs.OnBreadCrumbClickListener) setOnBreadCrumbClickListener()}, +provides a hook to let +applications intercept fragment-breadcrumb clicks and take any action needed +before going to the backstack entry or fragment that was clicked.
      • +
      • In the {@link android.app.Fragment} class, {@link +android.app.Fragment#onInflate(android.util.AttributeSet, android.os.Bundle) +onInflate(attrs, savedInstanceState)} is deprecated. Please use {@link +android.app.Fragment#onInflate(android.app.Activity, android.util.AttributeSet, +android.os.Bundle) onInflate(activity, attrs, savedInstanceState)} instead.
      • +
      +
    • +
    • Display search result in new tab +
        +
      • An {@link android.app.SearchManager#EXTRA_NEW_SEARCH} data key for {@link +android.content.Intent#ACTION_WEB_SEARCH} intents lets you open a search in a +new browser tab, rather than in an existing one.
      • +
      +
    • + +
    • Drawable text cursor +
        +
      • You can now specify a drawable to use as the text cursor using the new +resource attribute {@link android.R.attr#textCursorDrawable}.
      • +
      +
    • +
    • Setting displayed child in remote views +
        +
      • A new convenience method, {@link +android.widget.RemoteViews#setDisplayedChild(int, int) setDisplayedChild(viewId, +childIndex)}, is available in {@link android.widget.RemoteViews} subclasses, to +let you set the child displayed in {@link android.widget.ViewAnimator} and +{@link android.widget.AdapterViewAnimator} subclasses such as {@link +android.widget.AdapterViewFlipper}, {@link android.widget.StackView}, {@link +android.widget.ViewFlipper}, and {@link android.widget.ViewSwitcher}.
      • +
      +
    • +
    • Generic keys for gamepads and other input devices +
        +
      • {@link android.view.KeyEvent} adds a range of generic keycodes to + accommodate gamepad buttons. The class also adds + {@link android.view.KeyEvent#isGamepadButton(int)} and several other + helper methods for working with keycodes.
      • +
      +
    • +
    + +

    Graphics

    + +
      +
    • Helpers for managing bitmaps +
        +
      • {@link android.graphics.Bitmap#setHasAlpha(boolean)} lets an app indicate that +all of the pixels in a Bitmap are known to be opaque (false) or that some of the +pixels may contain non-opaque alpha values (true). Note, for some configs (such +as RGB_565) this call is ignored, since it does not support per-pixel alpha +values. This is meant as a drawing hint, as in some cases a bitmap that is known +to be opaque can take a faster drawing case than one that may have non-opaque +per-pixel alpha values.
      • +
      • {@link android.graphics.Bitmap#getByteCount()} gets a Bitmap's size in +bytes.
      • +
      • {@link android.graphics.Bitmap#getGenerationId()} lets an application find +out whether a Bitmap has been modified, such as for caching.
      • +
      • {@link android.graphics.Bitmap#sameAs(android.graphics.Bitmap)} determines +whether a given Bitmap differs from the current Bitmap, in dimension, +configuration, or pixel data.
      • +
      +
    • +
    • Setting camera location and rotation +
        +
      • {@link android.graphics.Camera} adds two new methods {@link +android.graphics.Camera#rotate(float, float, float) rotate()} and {@link +android.graphics.Camera#setLocation(float, float, float) setLocation()} for +control of the +camera's location, for 3D transformations.
      • +
      +
    • +
    + +

    Network

    + +
      +
    • High-performance Wi-Fi lock +
        +
      • A new high-performance Wi-Fi lock lets applications maintain +high-performance Wi-Fi connections even when the device screen is off. +Applications that stream music, video, or voice for long periods can acquire the +high-performance Wi-Fi lock to ensure streaming performance even when the screen +is off. Because it uses more power, applications should acquire the +high-performance Wi-Fi when there is a need for a long-running active +connection. +

        To create a high-performance lock, pass {@link +android.net.wifi.WifiManager#WIFI_MODE_FULL_HIGH_PERF} as the lock mode in a +call to {@link android.net.wifi.WifiManager#createWifiLock(int, +java.lang.String) createWifiLock()}.

      • +
      +
    • +
    • More traffic stats +
        +
      • Applications can now access statistics about more types of network usage +using new methods in {@link android.net.TrafficStats}. Applications can use the +methods to get UDP stats, packet count, TCP transmit/receive payload bytes and +segments for a given UID.
      • +
      +
    • +
    • SIP auth username +
        +
      • Applications can now get and set the SIP auth username for a profile +using +the new methods {@link android.net.sip.SipProfile#getAuthUserName() +getAuthUserName()} and {@link +android.net.sip.SipProfile.Builder#setAuthUserName(java.lang.String) +setAuthUserName()}.
      • +
      +
    • +
    + + +

    Download Manager

    +
      +
    • Handling of completed downloads +
        +
      • Applications can now initiate downloads that notify users only on +completion. To initiate this type of download, applications pass {@link +android.app.DownloadManager.Request#VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION} +in the {@link +android.app.DownloadManager.Request#setNotificationVisibility(int) +setNotificationVisibility()} method of +the a request object.
      • +
      • A new method, {@link +android.app.DownloadManager#addCompletedDownload(java.lang.String, +java.lang.String, boolean, java.lang.String, java.lang.String, long, boolean) +addCompletedDownload()}, lets an application add a file to the +downloads database, so that it can be managed by the Downloads application.
      • +
      +
    • +
    • Show downloads sorted by size +
        +
      • Applications can start the Downloads application in sort-by-size mode by +adding the new extra {@link +android.app.DownloadManager#INTENT_EXTRAS_SORT_BY_SIZE} to an {@link +android.app.DownloadManager#ACTION_VIEW_DOWNLOADS} intent.
      • +
      +
    • +
    + +

    IME framework

    + +
      +
    • Getting an input method's extra value key +
      • The {@link android.view.inputmethod.InputMethodSubtype} adds the +method +{@link +android.view.inputmethod.InputMethodSubtype#containsExtraValueKey(java.lang.String) containsExtraValueKey()} to check whether an ExtraValue string is stored +for the subtype and +the method {@link +android.view.inputmethod.InputMethodSubtype#getExtraValueOf(java.lang.String) +getExtraValueOf()} to extract a specific key value from the ExtraValue hashmap. +
      • +
      +
    • +
    + +

    Media

    + +
      +
    • New streaming audio formats +
        +
      • The media framework adds built-in support for raw ADTS AAC content, for +improved streaming audio, as well as support for FLAC audio, for highest quality +(lossless) compressed audio content. See the Supported Media Formats +document for more information.

      • +
      +
    • +
    + +

    Launch controls on stopped +applications

    + +

    Starting from Android 3.1, the system's package manager keeps track of +applications that are in a stopped state and provides a means of controlling +their launch from background processes and other applications.

    + +

    Note that an application's stopped state is not the same as an Activity's +stopped state. The system manages those two stopped states separately.

    + +

    The platform defines two new intent flags that let a sender specify +whether the Intent should be allowed to activate components in stopped +application.

    + +
      +
    • {@link android.content.Intent#FLAG_INCLUDE_STOPPED_PACKAGES} — +Include intent filters of stopped applications in the list of potential targets +to resolve against.
    • +
    • {@link android.content.Intent#FLAG_EXCLUDE_STOPPED_PACKAGES} — +Exclude intent filters of stopped applications from the list of potential +targets.
    • +
    + +

    When neither or both of these flags is defined in an intent, the default +behavior is to include filters of stopped applications in the list of +potential targets.

    + +

    Note that the system adds {@link +android.content.Intent#FLAG_EXCLUDE_STOPPED_PACKAGES} to all broadcast +intents. It does this to prevent broadcasts from background services from +inadvertently or unnecessarily launching components of stoppped applications. +A background service or application can override this behavior by adding the +{@link android.content.Intent#FLAG_INCLUDE_STOPPED_PACKAGES} flag to broadcast +intents that should be allowed to activate stopped applications.

    + +

    Applications are in a stopped state when they are first installed but are not +yet launched and when they are manually stopped by the user (in Manage +Applications).

    + +

    Notification of application first launch and upgrade

    + +

    The platform adds improved notification of application first launch and +upgrades through two new intent actions:

    + +
      +
    • {@link android.content.Intent#ACTION_PACKAGE_FIRST_LAUNCH} — Sent to +the installer package of an application when that application is first launched +(that is, the first time it is moved out of a stopped state). The data +contains the name of the package.
    • + +
    • {@link android.content.Intent#ACTION_MY_PACKAGE_REPLACED} — Notifies +an application that it was updated, with a new version was installed over +an existing version. This is only sent to the application that was replaced. It +does not contain any additional data. To receive it, declare an intent filter +for this action. You can use the intent to trigger code that helps get your +application back in proper running shape after an upgrade. + +

      This intent is sent directly to the application, but only if the application +was upgraded while it was in started state (not in a stopped state).

    • + +
    + +

    Core utilities

    + +
      +
    • LRU cache +
        +
      • A new {@link android.util.LruCache} class lets your applications benefit +from efficient caching. Applications can use the class to reduce the time spent +computing or downloading data from the network, while maintaining a sensible +memory footprint for the cached data.{@link android.util.LruCache} is a cache +that holds strong references to a limited number of values. Each time a value is +accessed, it is moved to the head of a queue. When a value is added to a full +cache, the value at the end of that queue is evicted and may become eligible for +garbage collection.
      • +
      +
    • +
    • File descriptor as int +
        +
      • You can now get the native file descriptor int for a {@link +android.os.ParcelFileDescriptor} using either of the new methods {@link +android.os.ParcelFileDescriptor#getFd()} or {@link +android.os.ParcelFileDescriptor#detachFd()}.
      • +
      +
    • +
    + + + + + + +

    WebKit

    + +
      + +
    • File scheme cookies +
        +
      • The {@link android.webkit.CookieManager} now supports cookies that use +the +file: URI scheme. You can use {@link +android.webkit.CookieManager#setAcceptFileSchemeCookies(boolean) +setAcceptFileSchemeCookies()} to +enable/disable support for file scheme cookies, before constructing an instance +of WebView or CookieManager. In a +CookieManager instance, you can check whether file scheme cookies +is enabled by calling {@link +android.webkit.CookieManager#allowFileSchemeCookies()}.
      • +
      +
    • +
    • Notification of login request +
        +
      • To support the browser autologin features introduced in Android 3.0, the +new +method {@link +android.webkit.WebViewClient#onReceivedLoginRequest(android.webkit.WebView,java.lang.String, java.lang.String, java.lang.String) onReceivedLoginRequest()} +notifies the host +application that an autologin request for the user was processed.
      • +
      +
    • +
    • Removed classes and interfaces +
        +
      • Several classes and interfaces were removed from the public API, after +previously being in deprecated state. See the API +Differences Report for more information.

      • +
      +
    • +
    + + + +

    Browser

    + +

    The Browser application adds the following features to support web +applications:

    + +
      +
    • Support for inline playback of video embedded in HTML5 +<video> tag. Playback is hardware-accelerated where possible. +
    • +
    • Layer support for fixed position elements for all sites (mobile and +desktop).
    • +
    + + + + + +

    New feature constants

    + +

    The platform adds new hardware feature constants that developers can declare +in their application manifests, to inform external entities such as Google +Play of the application's requirement for new hardware capabilities supported +in this version of the platform. Developers declare these and other feature +constants in {@code +<uses-feature>} manifest elements. + +

      +
    • {@link android.content.pm.PackageManager#FEATURE_USB_ACCESSORY +android.hardware.usb.accessory} — The application uses the USB +API to communicate with external hardware devices connected over USB and +function as hosts.
    • +
    • {@link android.content.pm.PackageManager#FEATURE_USB_HOST +android.hardware.usb.host} — The application uses the USB API +to communicate with external hardware devices connected over USB and function as +devices.
    • +
    + +

    Google Play filters applications based on features declared in {@code +<uses-feature>} manifest elements. For more information about +declaring features in an application manifest, read Google Play +Filters.

    + + + +

    API Differences Report

    + +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level +{@sdkPlatformApiLevel}), see the API +Differences Report.

    + + + + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, +you need compile the application against the Android library that is provided in +the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you +might +also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" +attribute to the <uses-sdk> element in the application's +manifest.

    + +

    For more information, read What is API +Level?

    diff --git a/docs/html/about/versions/android-3.2.jd b/docs/html/about/versions/android-3.2.jd new file mode 100644 index 000000000000..02111a058737 --- /dev/null +++ b/docs/html/about/versions/android-3.2.jd @@ -0,0 +1,556 @@ +page.title=Android 3.2 Platform +sdk.platform.version=3.2 +sdk.platform.apiLevel=13 +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. Highlights
    2. +
    3. API Overview
    4. +
    5. API Level
    6. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + + +

    API Level: {@sdkPlatformApiLevel}

    + +

    Android 3.2 is an incremental platform release that adds new +capabilities for users and developers. The sections below provide an overview +of the new features and developer APIs.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + + +

    Platform Highlights

    + +

    New user features

    + +
      +
    • Optimizations for a wider range of tablets + +

      Android 3.2 includes a variety of optimizations across the system +to ensure a great user experience on a wider range of tablet devices.

    • + +
    • Compatibility zoom for fixed-sized apps + +

      Android 3.2 introduces a new compatibility zoom mode that gives +users a new way to view fixed-sized apps on larger devices. The new mode provides a +pixel-scaled alternative to the standard UI stretching for apps that are not +designed to run on larger screen sizes, such as on tablets. The new mode is +accessible to users from a menu icon in the system bar, for apps that need +compatibility support.

    • + +
    • Media sync from SD card +

      On devices that support an SD card, users can now load media files directly +from the SD card to apps that use them. A system facility makes the files +accessible to apps from the system media store.

    • +
    + + +

    New developer features

    + +
      +
    • Extended API for managing screens support + +

      Android 3.2 introduces extensions to the platform's screen support API to +give developers additional ways to manage application UI across the range of +Android-powered devices. The API includes new resource qualifiers and new +manifest attributes that give you more precise control over how your +apps are displayed on different sizes, rather than relying on generalized +size categories.

      + +

      To ensure the best possible display for fixed-sized apps and apps with limited +support for various screen sizes, the platform also provides a new zoom +compatibility mode that renders the UI on a smaller screen area, then scales it +up to fill the space available on the display. For more information about the +screen support API and the controls it provides, see the sections below.

    • +
    + + +

    API Overview

    + +

    Screens Support APIs

    + +

    Android 3.2 introduces new screens support APIs that give you more +control over how their applications are displayed across different screen sizes. +The API builds on the existing screens-support API, including the platform's +generalized screen density model, but extends it with the ability to precisely +target specific screen ranges by their dimensions, measured in +density-independent pixel units (such as 600dp or 720dp wide), rather than +by their generalized screen sizes (such as large or xlarge)

    + +

    When designing an application's UI, you can still rely on the platform to +provide density abstraction, which means that applications do not need to +compensate for the differences in actual pixel density across devices. You +can design the application UI according to the amount of horizontal or vertical +space available. The platform expresses the amount of space available using three new +characteristics: smallestWidth, width, and +height.

    + +
      +
    • A screen's smallestWidth is its fundamental minimum size, +measured in density-independent pixel ("dp") units. Of the screen's height or +width, it is the shorter of the two. For a screen in portrait orientation, the +smallestWidth is normally based on its width, while in landscape orientation it is based +on its height. In all cases, the smallestWidth is derived from a fixed characteristic of the +screen and the value does not change, regardless of orientation. The smallestWidth +is important for applications because it represents the shortest possible width +in which the application UI will need to be drawn, not including screen areas +reserved by the system. +
    • + +
    • In contrast, a screen's width and height represent the +current horizontal or vertical space available for application layout, measured +in "dp" units, not including screen areas reserved by the system. The width and +height of a screen change when the user switches orientation between landscape +and portrait.
    • + +
    + +

    The new screens support API is designed to let you manage application UI +according to the smallestWidth of the current screen. You can also manage the +UI according to current width or height, as needed. For those purposes, the API +provides these tools:

    + +
      +
    • New resource qualifiers for targeting layouts and other resources to a +minimum smallestWidth, width, or height, and
    • +
    • New manifest attributes, for specifying the app's maximum +screen compatibility range
    • +
    + +

    Additionally, applications can still query the system and manage UI and +resource loading at runtime, as in the previous versions of the platform.

    + +

    Since the new API lets you target screens more directly through smallestWidth, +width, and height, it's helpful to understand the typical +characteristics of the different screen types. The table below provides some +examples, measured in "dp" units.

    + +

    Table 1. Typical devices, with density +and size in dp.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TypeDensity (generalized)Dimensions (dp)smallestWidth (dp)
    Baseline phonemdpi320x480320
    Small tablet/large phonemdpi480x800480
    7-inch tabletmdpi600x1024600
    10-inch tabletmdpi800x1280800
    + +

    The sections below provide more information about the new screen qualifiers +and manifest attributes. For complete information about how to use the screen +support API, see Supporting Multiple +Screens.

    + +

    New resource qualifiers for screens support

    + +

    The new resource qualifiers in Android 3.2 let you better target your layouts +for ranges of screen sizes. Using the qualifiers, you can create resource +configurations designed for a specific minimum smallestWidth, current width, or +current height, measured in density-independent pixels.

    + +

    The new qualifiers are:

    +
      +
    • swNNNdp — Specifies the minimum smallestWidth on which +the resource should be used, measured in "dp" units. As mentioned above, a +screen's smallestWidth is constant, regardless of orientation. Examples: +sw320dp, sw720dp, sw720dp.
    • + +
    • wNNNdp and hNNNdp — Specifies the minimum +width or height on which the resource should be used, measured in "dp" units. As +mentioned above, a screen's width and height are relative to the orientation of +the screen and change whenever the orientation changes. Examples: +w320dp, w720dp, h1024dp.

    • +
    + +

    You can also create multiple overlapping resource configurations if needed. +For example, you could tag some resources for use on any screen wider than 480 +dp, others for wider than 600 dp, and others for wider than 720 dp. When +multiple resource configurations are qualified for a given screen, the system +selects the configuration that is the closest match. For precise control over +which resources are loaded on a given screen, you can tag resources with one +qualifier or combine several new or existing qualifiers. + +

    Based on the typical dimensions listed earlier, here are some examples of how +you could use the new qualifiers:

    + +
    res/layout/main_activity.xml   # For phones
    +res/layout-sw600dp/main_activity.xml   # For 7” tablets
    +res/layout-sw720dp/main_activity.xml   # For 10” tablets
    +res/layout-w600dp/main_activity.xml   # Multi-pane when enough width
    +res/layout-sw600dp-w720dp/main_activity.xml   # For large width
    + +

    Older versions of the platform will ignore the new qualifiers, so you can +mix them as needed to ensure that your app looks great on any device. Here +are some examples:

    + +
    res/layout/main_activity.xml   # For phones
    +res/layout-xlarge/main_activity.xml   # For pre-3.2 tablets
    +res/layout-sw600dp/main_activity.xml   # For 3.2 and up tablets
    + +

    For complete information about how to use the new qualifiers, see Using new +size qualifiers.

    + +

    New manifest attributes for screen-size compatibility

    + +

    The framework offers a new set of <supports-screens> manifest attributes that let +you manage your app's support for different screen sizess. +Specifically, you can specify the largest and smallest screens on which your app +is designed to run, as well as the largest screen on which it is designed run +without needing the system's new screen +compatibility mode. Like the resource qualifiers described above, the new +manifest attributes specify the range of screens that the application supports, +as specified by the smallestWidth.

    + +

    The new manifest attributes for screen support are:

    + +
      +
    • android:compatibleWidthLimitDp="numDp" — This +attribute lets you specify the maximum smallestWidth on which the application +can run without needing compatibility mode. If the current screen is larger than +the value specified, the system displays the application in normal mode but +allows the user to optionally switch to compatibility mode through a setting in +the system bar.
    • + +
    • android:largestWidthLimitDp="numDp" — This +attribute lets you specify the maximum smallestWidth on which the application +is designed to run. If the current screen is larger than the value specified, +the system forces the application into screen compatibility mode, to ensure best +display on the current screen.
    • + +
    • android:requiresSmallestWidthDp="numDp" — This +attribute lets you specify the minimum smallestWidth on which the application +can run. If the current screen is smaller than the value specified, the system +considers the application incompatible with the device, but does not prevent it +from being installed and run.
    • +
    + +

    Note: Google Play does not currently filter +apps based on any of the attributes above. Support for filtering will be +added in a later platform release. Applications that require +filtering based on screen size can use the existing <supports-screens> +attributes.

    + +

    For complete information about how to use the new attributes, see Declaring +screen size support.

    + +

    Screen compatibility mode

    + +

    Android 3.2 provides a new screen compatibility mode for applications +explicitly declaring that they do not support screens as large as the one on +which they are running. This new "zoom" mode is a pixel-scaled — it +renders the application in a smaller screen area and then scales the pixels to +fill the current screen.

    + +

    By default, the system offers screen compatibility mode as an user option, for apps +that require it. Users can turn the zoom mode on and off using a control available +in the system bar.

    + +

    Because the new screen compatibility mode may not be appropriate for all +applications, the platform allows the application to disable it using manifest +attributes. When disabled by the app, the system does not offer "zoom" compatibility +mode as an option for users when the app is running.

    + +

    Note: For important information about how +to control compatibility mode in your applications, please review the New Mode for Apps on Large Screens article on the Android +Developers Blog.

    + +

    New screen density for 720p televisions and similar devices

    + +

    To meet the needs of applications running on 720p televisions or similar with +moderate density screens, Android 3.2 introduces a new generalized density, +tvdpi, with an approximate dpi of 213. Applications can query for +the new density in {@link android.util.DisplayMetrics#densityDpi} and can use +the new tvdpi qualifier to tag resources for televisions and +similar devices. For example:

    + +
    res/drawable-tvdpi/my_icon.png   # Bitmap for tv density
    + +

    In general, applications should not need to work with this density. For situations +where output is needed for a 720p screen, the UI elements can be scaled +automatically by the platform.

    + + +

    UI framework

    +
      +
    • Fragments +
        +
      • New {@link android.app.Fragment.SavedState} class holds the state + information retrieved from a fragment instance through + {@link android.app.FragmentManager#saveFragmentInstanceState(android.app.Fragment) saveFragmentInstanceState()}.
      • +
      • New method {@link android.app.FragmentManager#saveFragmentInstanceState(android.app.Fragment) saveFragmentInstanceState()} + saves the current instance state of + the given Fragment. The state can be used later when creating a new instance + of the Fragment that matches the current state.
      • +
      • New method {@link android.app.Fragment#setInitialSavedState(SavedState) setInitialSavedState()} + sets the initial saved state for a Fragment when first constructed.
      • +
      • New {@link android.app.Fragment#onViewCreated(android.view.View, android.os.Bundle) + onViewCreated()} callback method notifies the Fragment that + {@link android.app.Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle) onCreateView()} + has returned, but before any saved state has been restored in to the View.
      • +
      • {@link android.app.Fragment#isDetached()} method determines whether + the Fragment has been explicitly detached from the UI.
      • +
      • New {@link android.app.FragmentTransaction#attach(android.app.Fragment) attach()} + and {@link android.app.FragmentTransaction#detach(android.app.Fragment) detach()} + methods let an application re-attach or detach fragments in the UI.
      • +
      • A new {@link android.app.FragmentTransaction#setCustomAnimations(int, int, int, int) + setCustomAnimations()} overload method lets you set specific animation + resources to run for enter/exit operations and specifically when + popping the back stack. The existing implementation does not account + for the different behavior of fragments when popping the back stack.
      • +
      +
    • +
    • Screen size information in ActivityInfo and ApplicationInfo +
        +
      • {@link android.content.pm.ActivityInfo} adds {@link android.content.pm.ActivityInfo#CONFIG_SCREEN_SIZE} + and {@link android.content.pm.ActivityInfo#CONFIG_SMALLEST_SCREEN_SIZE} as bit masks + in {@link android.R.attr#configChanges}. The bits indicate whether an Activity can + itself handle the screen size and smallest screen size.
      • +
      • {@link android.content.pm.ApplicationInfo} adds + {@link android.content.pm.ApplicationInfo#largestWidthLimitDp}, {@link android.content.pm.ApplicationInfo#compatibleWidthLimitDp}, + and {@link android.content.pm.ApplicationInfo#requiresSmallestWidthDp} fields, + derived from the corresponding <supports-screens> attributes + in the application manifest file.
      • +
      +
    • +
    • Helpers for getting display size from WindowManager +
        +
      • New methods {@link android.view.Display#getSize(android.graphics.Point) + getSize()} and {@link android.view.Display#getRectSize(android.graphics.Rect) + getRectSize()} let applications get the raw size of the display.
      • +
      +
    • +
    • New public "holographic" styles +
        +
      • The platform now exposes a variety of public "holographic" styles + for text, actionbar widgets and tabs, and more. See + {@link android.R.style} for a full list.
      • +
      +
    • +
    • {@link android.app.LocalActivityManager}, {@link android.app.ActivityGroup}, and + {@link android.app.LocalActivityManager} are now deprecated +
        +
      • New applications should use Fragments instead of these classes. To + continue to run on older versions of the platform, you can use the v4 Support + Library (compatibility library), available in the Android SDK. The v4 Support + Library provides a version of the Fragment API that is compatible down to + Android 1.6 (API level 4). +
      • For apps developing against Android 3.0 (API level + 11) or higher, tabs are typically presented in the UI using the new + {@link android.app.ActionBar#newTab() ActionBar.newTab()} and related APIs + for placing tabs within their action bar area.

      • +
      +
    • +
    + +

    Media framework

    +
      +
    • Applications that use the platform's media provider ({@link + android.provider.MediaStore}) can now read media data directly from the + removeable SD card, where supported by the device. Applications can also + interact with the SD card files directly, using the MTP API.
    • + +
    +

    Graphics

    +
      +
    • Parcelable utilities in Point and PointF +
        +
      • {@link android.graphics.Point} and {@link android.graphics.PointF} + classes now include the {@link android.os.Parcelable} interface and utility methods {@link + android.graphics.Point#describeContents()}, {@link + android.graphics.Point#readFromParcel(android.os.Parcel) readFromParcel()}, and {@link + android.graphics.Point#writeToParcel(android.os.Parcel, int) writeToParcel()}.
      • +
      +
    • +
    + + +

    IME framework

    +
      +
    • New {@link android.view.KeyEvent#getModifiers()} method for + retrieving the current state of the modifier keys.
    • +
    + + +

    USB framework

    +
      +
    • New {@link + android.hardware.usb.UsbDeviceConnection#getRawDescriptors()} method for + retrieving the raw USB descriptors for the device. You can use the + method to access descriptors not supported directly via the higher + level APIs.
    • +
    + + +

    Network

    +
      +
    • Network type constants +
        +
      • {@link android.net.ConnectivityManager} adds the constants {@link + android.net.ConnectivityManager#TYPE_ETHERNET} and {@link + android.net.ConnectivityManager#TYPE_BLUETOOTH}.
      • +
      +
    • +
    + + +

    Telephony

    +
      +
    • New {@link android.telephony.TelephonyManager#NETWORK_TYPE_HSPAP} network type constant.
    • +
    + +

    Core utilities

    +
      +
    • Parcelable utilities +
        +
      • New interface {@link android.os.Parcelable.ClassLoaderCreator} allows + the application to receive the ClassLoader in which the object is being created.
      • +
      • New {@link android.os.ParcelFileDescriptor#adoptFd(int) adoptFd}, {@link + android.os.ParcelFileDescriptor#dup(java.io.FileDescriptor) dup()}, and {@link + android.os.ParcelFileDescriptor#fromFd(int) fromFd()} for managing + {@link android.os.ParcelFileDescriptor} objects.
      • +
      +
    • +
    • Binder and IBinder +
        +
      • New method {@link android.os.Binder#dumpAsync(java.io.FileDescriptor, java.lang.String[]) dumpAsync()} + in {@link android.os.Binder} and {@link android.os.IBinder} let applications + dump to a specified file, ensuring that the target executes asynchronously.
      • +
      • New {@link android.os.IBinder} protocol transaction code {@link + android.os.IBinder#TWEET_TRANSACTION} lets applications send a tweet + to the target object.
      • +
      +
    • +
    + + + + +

    New feature constants

    + +

    The platform adds new hardware feature constants that you can declare +in their application manifests, to inform external entities such as Google +Play of required hardware and software capabilities. You declare these +and other feature constants in {@code +<uses-feature>} manifest elements. + +

    Google Play filters applications based on their <uses-feature> attributes, to ensure that they are available only to devices on which their requirements are met.

    + +
      +
    • Feature constants for landscape or portrait requirements + +

      Android 3.2 introduces new feature constants that let applications specify whether they require display in landscape orientation, portrait orientation, or both. Declaring these constants indicates that the application must not be installed on a device that doesn't offer the associated orientation. Conversely, if one or both of the constants are not declared, it indicates that the application does not have a preference for the undeclared orientations and may be installed on a device that doesn't offer them.

      + +
        +
      • {@link android.content.pm.PackageManager#FEATURE_SCREEN_LANDSCAPE +android.hardware.screen.landscape} — The application requires display in +landscape orientation.
      • +
      • {@link android.content.pm.PackageManager#FEATURE_SCREEN_PORTRAIT +android.hardware.screen.portrait} — The application requires display in +portrait orientation.
      • +
      + +

      A typical application that functions properly in both landscape and portrait orientations would not normally need to declare an orientation requirement. Rather, an application designed primarily for one orientation, such as an app designed for a television, could declare one of the constants to ensure that it isn't available to devices that don't provide that orientation.

      + +

      If any of activities declared in the manifest request that they run in a specific orientation, +using the {@code +android:screenOrientation} attribute, then this also declares that the application +requires that orientation.

      + +
    • +
    • Other feature constants + +
        +
      • {@link android.content.pm.PackageManager#FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT +android.hardware.faketouch.multitouch.distinct} — The application requires support for emulated mulitouch input with distinct tracking of two or more points.
      • + +
      • {@link android.content.pm.PackageManager#FEATURE_FAKETOUCH_MULTITOUCH_JAZZHAND +android.hardware.faketouch.multitouch.jazzhand} — The application requires support for emulated mulitouch input with distinct tracking of five or more points.
      • +
      + +
    • +
    + + +

    API Differences Report

    + +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API +Level +{@sdkPlatformApiLevel}), see the API +Differences Report.

    + + + + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} platform delivers an updated version of +the framework API. The Android {@sdkPlatformVersion} API +is assigned an integer identifier — +{@sdkPlatformApiLevel} — that is +stored in the system itself. This identifier, called the "API Level", allows the +system to correctly determine whether an application is compatible with +the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, +you need compile the application against the Android library that is provided in +the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you +might +also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" +attribute to the <uses-sdk> element in the application's +manifest.

    + +

    For more information, read What is API +Level?

    + + diff --git a/docs/html/about/versions/android-4.0-highlights.jd b/docs/html/about/versions/android-4.0-highlights.jd new file mode 100644 index 000000000000..9fdb02c8815b --- /dev/null +++ b/docs/html/about/versions/android-4.0-highlights.jd @@ -0,0 +1,1066 @@ +page.title=Ice Cream Sandwich + +@jd:body + + + + +

    Welcome to Android 4.0!

    + +

    Android 4.0 delivers a refined, unified UI for phones and tablets and +introduces innovative features for users and developers. This document provides +a glimpse of the many new features and technologies that make Android 4.0 +simple, beautiful, and beyond smart.

    + + + +

    Android 4.0 for Users

    + +
    + + +
    + + +

    Simple, beautiful, beyond smart

    + +

    Android 4.0 builds on the things people love most about Android — easy +multitasking, rich notifications, customizable home screens, resizable widgets, +and deep interactivity — and adds powerful new ways of communicating and +sharing.

    + +

    Refined, evolved UI

    + +

    Focused on bringing the power of Android to the surface, Android 4.0 makes +common actions more visible and lets users navigate with +simple, intuitive gestures. Refined animations and feedback +throughout the system make interactions engaging and interesting. An entirely +new typeface optimized for high-resolution screens improves +readability and brings a polished, modern feel to the user interface.

    + +

    Virtual buttons in the System Bar let users navigate instantly to Back, Home, +and Recent Apps. The System Bar and virtual buttons are present +across all apps, but can be dimmed by applications for full-screen viewing. +Users can access each application's contextual options in the Action +Bar, displayed at the top (and sometimes also at the bottom) of the +screen.

    + +

    Multitasking is a key strength of Android and it's made even +easier and more visual on Android 4.0. The Recent Apps button lets users jump +instantly from one task to another using the list in the System Bar. The list +pops up to show thumbnail images of apps used recently — tapping a +thumbnail switches to the app.

    + +
    +
    + + +
    The Recent Apps list makes +multitasking simple.
    + + +
    Jump to the camera or see +notifications without unlocking.
    + + + +
    For incoming calls, you can +respond instantly by text.
    +
    +
    + +

    Rich and interactive notifications let users keep in +constant touch with incoming messages, play music tracks, see real-time updates +from apps, and much more. On smaller-screen devices, notifications appear at the +top of the screen, while on larger-screen devices they appear in the System +Bar.

    + +
    +
    + + + + +
    The All Apps launcher (left) and resizable widgets (right) give you apps and rich +content from the home screen.
    +
    +
    + + +

    Home screen folders and +favorites tray

    + +

    New home screen folders offer a new way for users to group +their apps and shortcuts logically, just by dragging one onto another. Also, +in All Apps launcher, users can now simply drag an app to get +information about it or immediately uninstall it, or disable a pre-installed app.

    + +

    On smaller-screen devices, the home screen now includes a customizable +favorites tray visible from all home screens. Users can drag +apps, shortcuts, folders, and other priority items in or out of the favorites +tray for instant access from any home screen.

    + + +

    Resizable +widgets

    + +

    Home screens in Android 4.0 are designed to be content-rich and customizable. +Users can do much more than add shortcuts — they can embed live +application content directly through interactive widgets. +Widgets let users check email, flip through a calendar, play music, check social +streams, and more — right from the home screen, without having to launch +apps. Widgets are resizable, so users can expand them to show more content or +shrink them to save space.

    + + +

    New lock screen +actions

    + +

    The lock screens now let users do more without unlocking. From the slide lock +screen, users can jump directly to the camera for a picture or +pull down the notifications window to check for messages. When +listening to music, users can even manage music tracks and see album art.

    + + +

    Quick responses for +incoming calls

    + +

    When an incoming call arrives, users can now quickly respond by text +message, without needing to pick up the call or unlock the device. On +the incoming call screen, users simply slide a control to see a list of text +responses and then tap to send and end the call. Users can add their own +responses and manage the list from the Settings app.

    + + +

    Swipe to dismiss +notifications, tasks, and browser tabs

    + +

    Android 4.0 makes managing notifications, recent apps, and browser tabs even +easier. Users can now dismiss individual notifications, apps from the Recent +Apps list, and browser tabs with a simple swipe of a finger.

    + +
    +
    + + +
    A spell-checker lets you find errors and fix them faster.
    + + +
    A powerful voice input +engine lets you dictate continously.
    +
    +
    + +

    Improved text input and +spell-checking

    + +

    The soft keyboard in Android 4.0 makes text input even faster and more +accurate. Error correction and word suggestion are improved through a new set of +default dictionaries and more accurate heuristics for handling cases such as +double-typed characters, skipped letters, and omitted spaces. Word suggestion +is also improved and the suggestion strip is simplified to show only three +words at a time.

    + +

    To fix misspelled words more easily, Android 4.0 adds a +spell-checker that locates and underlines errors and suggests +replacement words. With one tap, users can choose from multiple spelling +suggestions, delete a word, or add it to the dictionary. Users can even tap to +see replacement suggestions for words that are spelled correctly. For +specialized features or additional languages, users can now download and install +third-party dictionaries, spell-checkers, and other text services.

    + + +

    Powerful voice input +engine

    + +

    Android 4.0 introduces a powerful new voice input engine that offers a +continuous "open microphone" experience and streaming voice recognition. The new +voice input engine lets users dictate the text they want, for as long as they +want, using the language they want. Users can speak continously for a prolonged +time, even pausing for intervals if needed, and dictate punctuation to create +correct sentences. As the voice input engine enters text, it underlines possible +dictation errors in gray. After dictating, users can tap the underlined words to +quickly replace them from a list of suggestions.

    + +
    +
    + + + + +
    Data usage controls let you monitor total usage by network type and application and +then set limits if needed.
    +
    +
    + +

    Control over network +data

    + +

    Mobile devices can make extensive use of network data for streaming content, +synchronizing data, downloading apps, and more. To meet the needs of users with +tiered or metered data plans, Android 4.0 adds new controls for +managing network data usage.

    + +

    In the Settings app, colorful charts show the total data usage on each +network type (mobile or Wi-Fi), as well as amount of data used by each running +application. Based on their data plans, users can optionally set warning levels +or hard limits on data usage or disable mobile data altogether. Users can also +manage the background data used by individual applications as needed.

    + + +

    Designed for +accessibility

    + +

    A variety of new features greatly enhance the accessibility of Android 4.0 +for blind or visually impaired users. Most important is a new +explore-by-touch mode that lets users navigate without having +to see the screen. Touching the screen once triggers audible feedback that +identifies the UI component below; a second touch in the same component +activates it with a full touch event. The new mode is especially important to +support users on new devices that use virtual buttons in the System Bar, rather +than dedicated hardware buttons or trackballs. Also, standard apps are updated +to offer an improved accessibility experience. The Browser +supports a script-based screen reader for reading favorite web content and +navigating sites. For improved readability, users can also increase the default +font size used across the system.

    + +

    The accessibility experience begins at first setup — a simple +touch gesture during setup (clockwise square from upper left) +activates all accessibility features and loads a setup tutorial. Once +accessibility features are active, everything visible on the screen can be +spoken aloud by the standard screen reader.

    + + +

    Communication and sharing

    + +
    +
    + + + + + + + + +
    Contacts and profiles are integrated across apps and social networks, for a +consistent, personal experience everywhere — from incoming calls to emails.
    +
    +
    + +

    Designed for the way people live, Android 4.0 integrates rich social +communication and sharing touchpoints across the system, making it easy to talk, +email, text, and share.

    + + +

    People and +profiles

    + +

    Throughout the system, a user’s social groups, profiles, and contacts are +linked together and integrated for easy accessibility. At the center is a new +People app that offers richer profile information, including a +large profile picture, phone numbers, addresses and accounts, status updates, +events, stream items, and a new button for connecting on integrated social networks.

    + +

    The user's own contact information is stored in a new "Me" +profile, allowing easier sharing with apps and people. All of the +user's integrated contacts are displayed in an easy to manage list, including +controls over which contacts are shown from any integrated account or social +network. Wherever the user navigates across the system, tapping a profile photo +displays Quick Contacts, with large profile pictures, shortcuts to phone numbers, +text messaging, and more.

    + + +

    Unified calendar, visual +voicemail

    + +

    To help organize appointments and events, an updated Calendar +app brings together personal, work, school, and social agendas. With +user permission, other applications can contribute events to the calendar and +manage reminders, for an integrated view across multiple calendar providers. The +app is redesigned to let users manage events more easily. Calendars are +color-coded and users can swipe left or right to change dates +and pinch to zoom in or out agendas.

    + +

    In the phone app, a new visual voicemail features integrates +incoming messages, voice transcriptions, and audio files from one or more +providers. Third-party applications can integrate with the Phone app to add +their own voice messages, transcriptions, and more to the visual voicemail +inbox.

    + +
    +
    + + + + + + +
    Capture the picture you want, +edit, and share instantly.
    +
    +
    + +

    Rich and versatile camera +capabilities

    + +

    The Camera app includes many new features that let users capture special moments +with great photos and videos. After capturing images, they can edit and share +them easily with friends.

    + +

    When taking pictures, continuous focus, zero shutter +lag exposure, and decreased shot-to-shot speed help capture clear, +precise images. Stabilized image zoom lets users compose photos +and video in the way they want, including while video is recording. For new +flexibility and convenience while shooting video, users can now take +snapshots at full video resolution just by tapping the screen +as video continues to record.

    + +

    To make it easier to take great pictures of people, built-in face +detection locates faces in the frame and automatically sets focus. For +more control, users can tap to focus anywhere in the preview +image.

    + +

    For capturing larger scenes, the Camera introduces a single-motion +panorama mode. In this mode, the user starts an exposure and then +slowly turns the Camera to encompass as wide a perspective as needed. The Camera +assembles the full range of continuous imagery into a single panoramic +photo.

    + +

    After taking a picture or video, users can quickly share it by email, text +message, bluetooth, social networks, and more, just by tapping the thumbnail in +the camera controls.

    + + +
    +
    + +
    A Photo Gallery widget +on the home screen.
    +
    + +

    Redesigned Gallery app +with photo editor

    + +

    The Gallery app now makes it easier to manage, show, and share photos and +videos. For managing collections, a redesigned album layout +shows many more albums and offers larger thumbnails. There are many ways to sort +albums, including by time, location, people, and tags. To help pictures look +their best, the Gallery now includes a powerful photo editor. +Users can crop and rotate pictures, set levels, remove red eyes, add effects, +and much more. After retouching, users can select one or multiple pictures or +videos to share instantly over email, text messaging, bluetooth, social +networks, or other apps.

    + +

    An improved Picture Gallery widget lets users look at +pictures directly on their home screen. The widget can display pictures from a +selected album, shuffle pictures from all albums, or show a single image. After +adding the widget to the home screen, users can flick through the photo stacks +to locate the image they want, then tap to load it in Gallery.

    + +
    +
    + +
    Live Effects let you +change backgrounds and use Silly Faces during video.
    +
    +
    + +

    Live Effects for transforming +video

    + +

    Live Effects is a collection of graphical transformations that add interest +and fun to videos captured in the Camera app. For example, users can +change the background behind them to any stock or custom image, +for just the right setting when shooting videeo. Also available for video is +Silly Faces, a set of morphing effects that use state-of-the-art face +recognition and GPU filters to transform facial features. For example, you can +use effects such as small eyes, big mouth, big nose, face squeeze, and more. +Outside of the Camera app, Live Effects is available during video chat in the +Google Talk app.

    + +
    +
    + + +
    Snapping a +screenshot.
    +
    +
    +
    + +

    Sharing with screenshots

    + +

    Users can now share what's on their screens more easily by taking +screenshots. Hardware buttons let them snap a screenshot and +store it locally. Afterward, they can view, edit, and share the screen shot in +Gallery or a similar app.

    + + +

    Cloud-connected experience

    + +
    +
    + + + + +
    The Browser tabs menu (left) lets you quickly switch browser tabs. The +options menu (right) gives you new ways to manage your browsing experience.
    + +
    Benchmark comparisons of +Android Browser.
    +
    +
    + +

    Android has always been cloud-connected, letting users browse the web and +sync photos, apps, games, email, and contacts — wherever they are and +across all of their devices. Android 4.0 adds new browsing and email +capabilities to let users take even more with them and keep communication +organized.

    + + +

    Powerful web +browsing

    + +

    The Android Browser offers an experience that’s as rich and convenient as a +desktop browser. It lets users instantly sync and manage Google Chrome +bookmarks from all of their accounts, jump to their favorite content +faster, and even save it for reading later in case there's no network +available.

    + +

    To get the most out of web content, users can now request full +desktop versions of web sites, rather than their mobile +versions. Users can set their preference for web sites separately for each +browser tab. For longer content, users can save a copy for +offline reading. To find and open saved pages, users can browse +a visual list that’s included with browser bookmarks and history. For better +readability and accessibility, users can increase the browser’s zoom +levels and override the system default text sizes.

    + +

    Across all types of content, the Android Browser offers dramatically improved +page rendering performance through updated versions of the +WebKit core and the V8 Crankshaft compilation engine for JavaScript. In +benchmarks run on a Nexus S device, the Android 4.0 browser showed an +improvement of nearly 220% over the Android 2.3 browser in the V8 Benchmark +Suite and more than 35% in the SunSpider 9.1 JavaScript Benchmark. When run on a +Galaxy Nexus device, the Android 4.0 browser showed improvement of nearly 550% +in the V8 benchmark and nearly 70% in the SunSpider benchmark.

    + + +

    Improved +email

    + +

    In Android 4.0, email is easier to send, read, and manage. For composing +email, improved auto-completion of recipients helps with +finding and adding frequent contacts more quickly. For easier input of frequent +text, users can now create quick responses and store them in +the app, then enter them from a convenient menu when composing. When replying to +a message, users can now toggle the message to Reply All and Forward without +changing screens.

    + +

    For easier browsing across accounts and labels, the app adds an +integrated menu of accounts and recent labels. To help users +locate and organize IMAP and Exchange email, the Email app now supports +nested mail subfolders, each with synchronization rules. Users +can also search across folders on the server, for faster results.

    + +

    For enterprises, the Email app supports EAS v14. It supports +EAS certificate authentication, provides ABQ strings for device type and mode, +and allows automatic sync to be disabled while roaming. Administrators can also +limit attachment size or disable attachments.

    + +

    For keeping track of incoming email more easily, a resizable Email +widget lets users flick through recent email right from the home +screen, then jump into the Email app to compose or reply.

    + + +
    +
    + + +
    Android +Beam lets users share what they are using with a single tap.
    +
    +
    + +

    Innovation

    + +

    Android is continously driving innovation forward, pushing the boundaries of +communication and sharing with new capabilities and interactions.

    + +

    Android Beam for +NFC-based sharing

    + +

    Android Beam is an innovative, convenient feature for sharing across two +NFC-enabled devices, It lets people instantly exchange favorite apps, contacts, +music, videos — almost anything. It’s incredibly simple and convenient to +use — there’s no menu to open, application to launch, or pairing needed. +Just touch one Android-powered phone to another, then tap to send.

    + +

    For sharing apps, Android Beam pushes a link to the app's details page in +Google Play. On the other device, the Google Play client app launches and loads the +details page, for easy downloading of the app. Individual apps can build on +Android Beam to add other types of interactions, such as passing game scores, +initiating a multiplayer game or chat, and more.

    + +
    +
    + + +
    Face recognition lets you +unlock your phone with your face.
    +
    +
    + +

    Face Unlock

    + +

    Android 4.0 introduces a completely new approach to securing a device, making +each person's device even more personal — Face Unlock is a new screen-lock +option that lets users unlock their devices with their faces. It takes advantage +of the device front-facing camera and state-of-the-art facial recognition +technology to register a face during setup and then to recognize it again when +unlocking the device. Users just hold their devices in front of their faces to +unlock, or use a backup PIN or pattern.

    + + +

    Wi-Fi Direct and Bluetooth HDP

    + +

    Support for Wi-Fi Direct lets users connect directly to +nearby peer devices over Wi-Fi, for more reliable, higher-speed communication. +No internet connection or tethering is needed. Through third-party apps, users +can connect to compatible devices to take advantage of new features such as +instant sharing of files, photos, or other media; streaming video or audio from +another device; or connecting to compatible printers or other devices.

    + +

    Android 4.0 also introduces built-in support for connecting to Bluetooth Health Device Profile (HDP) devices. With support from third-party apps, users can connect to wireless medical devices and sensors in hospitals, fitness centers, homes, and elsewhere.

    + + +

    New Developer Features

    + + + +

    Unified UI framework for phones, tablets, and more

    + +

    Android 4.0 brings a unified UI framework that lets developers create +elegant, innovative apps for phones, tablets, and more. It includes all of the +familiar Android 3.x interface elements and APIs — fragments, content +loaders, Action Bar, rich notifications, resizable home screen widgets, and more +— as well as new elements and APIs.

    + +

    For developers, the unified UI framework in Android 4.0 means new UI tools, +consistent design practices, simplified code and resources, and streamlined +development across the range of Android-powered devices.

    + + + +

    Communication and sharing

    + +

    Android 4.0 extends social and sharing features to any application on the +device. Applications can integrate contacts, profile data, stream items, +and calendar events from any of the user’s activities or social networks.

    + + +

    Social API

    + +

    A shared social provider and API provide a new unified store for contacts, +profile data, stream items, and photos. Any app or social network with user +permission can contribute raw contacts and make them accessible to other apps +and networks. Applications with user permission can also read profile data from +the provider and display it in their applications.

    + +

    The social API lets applications store standard contact data as well as new +types of content for any given contact, including large profile photos, stream +items, and recent activity feedback. Recent activity feedback is a standard way for +applications to “tag” a contact with common activity, such as when the user +calls the contact or sends an email or SMS message. The social provider uses the +recent activity feedback as a new signal in ranking, such as for name +auto-complete, to keep the most relevant contacts ranked closest to the top.

    + +

    Applications can also let users set up a social connection to a contact from +the People app. When the user touches Add Connection in a contact, the app +sends a public intent that other apps can handle, displaying any UI needed +to create the social connection.

    + +

    Building on the social API, developers can add powerful new interactions that +span multiple social networks and contacts sources.

    + + +

    Calendar API

    + +

    A shared calendar content provider and framework API make it easier for +developers to add calendar services to their apps.

    + +

    With user permission, any application can add events to the shared database +and manage dates, attendees, alerts, and reminders. Applications can also read +entries from the database, including events contributed by other applications, +and handle the display of event alerts and reminders. Using the calendar +provider, applications can take advantage of event data sourced from a variety +of apps and protocols, to offer innovative ways of viewing and managing a user’s +events. Apps can also use calendar data to improve the relevance of their +other content.

    + +

    For lighter-weight access to calendar services, the Calendar app defines a +set of public Intents for creating, viewing, and editing events. Rather than +needing to implement a calendar UI and integrate directly with the calendar +provider, applications can simply broadcast calendar Intents. When the Calendar +app receives the Intents, it launches the appropriate UI and stores any event +data entered. Using calendar Intents, for example, apps can let users add events +directly from lists, dialogs, or home screen widgets, such as for making +restaurant reservations or booking time with friends.

    + + +

    Visual voicemail +API

    + +

    A shared Voicemail provider and API allow developers to build applications +that contribute to a unified voicemail store. Voicemails are displayed and +played in the call log tab of the platform’s Phone app.

    + + +

    Android Beam

    + +

    Android Beam is an NFC-based feature that lets users instantly share +information about the apps they are using, just by touching two NFC-enabled +phones together. When the devices are in range — within a few centimeters +— the system sets up an NFC connection and displays a sharing UI. To share +whatever they are viewing with the other device, users just touch the screen. +

    + +

    For developers, Android Beam is a new way of triggering almost any type of +proximity-based interaction. For example, it can let users instantly exchange +contacts, set up multiplayer gaming, join a chat or video call, share a photo or +video, and more. The system provides the low-level NFC support and the sharing +UI, while the foreground app provides lightweight data to transfer to the other +device. Developers have complete control over the data that is shared and how it +is handled, so almost any interaction is possible. For larger payloads, +developers can even use Android Beam to initiate a connection and transfer the +data over Bluetooth, without the need for user-visible pairing.

    + +

    Even if developers do not add custom interactions based on Android Beam they +can still benefit from it being deeply integrated into Android. By default the +system shares the app’s Google Play URL, so it’s easy for the user to +download or purchase the app right away.

    + + +

    Modular sharing +widget

    + +

    The UI framework includes a new widget, ShareActionProvider, that lets +developers quickly embed standard share functionality and UI in the Action Bar +of their applications. Developers simply add ShareActionProvider to the menu and +set an intent that describes the desired sharing action. The system handles the +rest, building up the list of applications that can handle the share intent and +dispatching the intent when the user chooses from the menu.

    + + +

    New media capabilities

    + +

    Low-level streaming +multimedia

    + +

    Android 4.0 provides a direct, efficient path for low-level streaming +multimedia. The new path is ideal for applications that need to maintain +complete control over media data before passing it to the platform for +presentation. For example, media applications can now retrieve data from any +source, apply proprietary encryption/decryption, and then send the data to the +platform for display.

    + +

    Applications can now send processed data to the platform as a multiplexed +stream of audio/video content in MPEG-2 transport stream format. The platform +de-muxes, decodes, and renders the content. The audio track is rendered to the +active audio device, while the video track is rendered to either a Surface or a +SurfaceTexture. When rendering to a SurfaceTexture, the application can apply +subsequent graphics effects to each frame using OpenGL.

    + +

    To support this low-level streaming, the platform introduces a new native API +based on Khronos +OpenMAX AL 1.0.1. The API is implemented on the same underlying services as +the platform’s existing OpenSL ES API, so developers can make use of both APIs +together if needed. Tools support for low-level streaming multimedia will be +available in an upcoming release of the Android NDK.

    + + +

    New camera +capabilities

    + +

    Developers can take advantage of a variety of new camera features in Android +4.0. ZSL exposure, continuous focus, and image zoom let apps capture better +still and video images, including during video capture. Apps can even capture +full-resolution snapshots while shooting video. Apps can now set custom metering +regions in a camera preview, then manage white balance and exposure dynamically +for those regions. For easier focusing and image processing, a face-detection +service identifies and tracks faces in a preview and returns their screen +coordinates.

    + + +

    Media effects for +transforming images and video

    + +

    A set of high-performance transformation filters let developers apply rich +effects to any image passed as an OpenGL ES 2.0 texture. Developers can adjust +color levels and brightness, change backgrounds, sharpen, crop, rotate, add lens +distortion, and apply other effects. The transformations are processed by the +GPU, so they are fast enough for processing image frames loaded from disk, +camera, or video stream.

    + + +

    Audio remote +controls

    + +

    Android 4.0 adds a new audio remote control API that lets media applications +integrate with playback controls that are displayed in a remote view. Media +applications can integrate with a remote music playback control that’s built +into in the platform’s lock screen, allowing users to control song selection and +playback without having to unlock and navigate to the music app.

    + +

    Using the audio remote control API, any music or media app can register to +receive media button events from the remote control and then manage play state +accordingly. The application can also supply metadata to the remote control, +such as album art or image, play state, track number and description, duration, +genre, and more.

    + + +

    New media codecs and +containers

    + +

    Android 4.0 adds support for additional media types and containers to give +developers access to the formats they need. For high-quality compressed images, +the media framework adds support for WebP content. For video, the framework now +supports streaming VP8 content. For streaming multimedia, the framework supports +HTTP Live streaming protocol version 3 and encoding of ADTS-contained AAC +content. Additionally, developers can now use Matroska containers for Vorbis and +VP8 content.

    + + +

    New types of connectivity

    + +

    Wi-Fi Direct

    + +

    Developers can use a framework API to discover and connect directly to nearby +devices over a high-performance, secure Wi-Fi Direct connection. No internet +connection or hotspot is needed.

    + +

    Wi-Fi Direct opens new opportunities for developers to add innovative +features to their applications. Applications can use Wi-Fi Direct to share +files, photos, or other media between devices or between a desktop computer and +an Android-powered device. Applications could also use Wi-Fi Direct to stream +media content from a peer device such as a digital television or audio player, +connect a group of users for gaming, print files, and more.

    + + +

    Bluetooth Health Device +Profile (HDP)

    + +

    Developers can now build powerful medical applications that use Bluetooth to +communicate with wireless devices and sensors in hospitals, fitness centers, +homes, and elsewhere. Applications can collect and manage data from HDP source +devices and transmit it to backend medical applications such as records systems, +data analysis services, and others.

    + +

    Using a framework API, applications can use Bluetooth to discover nearby +devices, establish reliable or streaming data channels, and manage data +transmission. Applications can supply any IEEE 11073 Manager to retrieve and +interpret health data from Continua-certified devices such as heart-rate +monitors, blood meters, thermometers, and scales.

    + + +

    New UI components and capabilities

    + +

    Layout +enhancements

    + +

    A new layout, GridLayout, improves the performance of Android applications by +supporting flatter view hierarchies that are faster to layout and render. +Because hierarchies are flatter, developers can also manage alignments between +components that are visually related to each other even when they are not +logically related, for precise control over application UI. GridLayout is also +specifically designed to be configured by drag-and-drop design tools such as the +ADT Plug-in for Eclipse.

    + + +

    OpenGL ES texture +views

    + +

    A new TextureView object lets developers directly integrate OpenGL ES +textures as rendering targets in a UI hierarchy. The object lets developers +display and manipulate OpenGL ES rendering just as they would a normal view +object in the hierarchy, including moving, transforming, and animating the view +as needed. The TextureView object makes it easy for developers to embed camera +preview, decoded video, OpenGL game scenes, and more. TextureView can be viewed +as a more powerful version of the existing SurfaceView object, since it offers +the same benefits of access to a GL rendering surface, with the added advantage +of having that surface participate fully in the normal view hierarchy.

    + + +

    Hardware-accelerated 2D +drawing

    + +

    All Android-powered devices running Android 4.0 are required to support +hardware-accelerated 2D drawing. Developers can take advantage of this to add +great UI effects while maintaining optimal performance on high-resolution +screens, even on phones. For example, developers can rely on accelerated +scaling, rotation, and other 2D operations, as well as accelerated UI components +such as TextureView and compositing modes such as filtering, blending, and +opacity.

    + + +

    New input types and text services

    + +

    Stylus input, button +support, hover events

    + +

    Android 4.0 includes full support for stylus input events, including tilt and +distance axes, pressure, and related motion event properties. To help +applications distinguish motion events from different sources, the platform adds +distinct tool types for stylus, finger, mouse, and eraser. For improved input +from multi-button pointing devices, the platform now provides distinct primary, +secondary, and tertiary buttons, as well as back and forward buttons. +Hover-enter and hover-exit events are also added, for improved navigation and +accessibility. Developers can build on these new input features to add powerful +interactions to their apps, such as precise drawing and gesturing, handwriting +and shape recognition, improved mouse input, and others.

    + + +

    Text services API for +integrating spelling checkers

    + +

    Android 4.0 lets applications query available text services such as +dictionaries and spell checkers for word suggestions, corrections, and similar +data. The text services are external to the active IME, so developers can create +and distribute dictionaries and suggestion engines that plug into the platform. +When an application receives results from a text service — for example, +word suggestions — it can display them in a dedicated suggestion popup +window directly inside the text view, rather than relying on the IME to display +them.

    + + +

    Enhanced accessibility APIs

    + +

    Android 4.0 adds new accessibility features and an enhanced API to let +developers improve the user experience in their apps, especially on devices that +don’t have hardware buttons. For accessibility services such as screen readers +in particular, the platform offers new APIs to query window content, for easier +navigation, better feedback, and richer user interfaces.

    + + +

    Accessibility +API

    + +

    To let applications manage interactions more effectively when accessibility +features are enabled, the platform adds accessibility events for +explore-by-touch mode, scrolling, and text selection. For these and other +events, the platform can attach a new object called an accessibility record that +provides extra information about the event context.

    + +

    Using the accessibility record and related APIs, applications can now access +the view hierarchy associated with an event. Applications can query for key +properties such as parent and child nodes, available states, supported actions, +screen position, and more. Applications can also request changes to certain +properties to help manage focus and selected state. For example, an +accessibility service could use these new capabilities to add convenient +features such as screen-search by text.

    + + +

    Text-to-speech +API

    + +

    A new framework API lets developers write text-to-speech engines and make +them available to any app requesting TTS capabilities.

    + + +

    Efficient network usage

    + +

    In Android 4.0, users can see how much network data their running apps are +using. They can also set limits on data usage by network type and disable +background data usage for specific applications. In this context, developers +need to design their apps to run efficiently and follow best practices for +checking the network connection. Android 4.0 provides network APIs to let +applications meet those goals.

    + +

    As users move between networks or set limits on network data, the platform +lets applications query for connection type and availability. Developers can use +this information to dynamically manage network requests to ensure the best +experience for users. Developers can also build custom network and data-usage +options into their apps, then expose them to users directly from Settings by +means of a new system Intent.

    + + +

    Security for apps and content

    + +

    Secure management of +credentials

    + +

    Android 4.0 makes it easier for applications to manage authentication and +secure sessions. A new keychain API and underlying encrypted storage let +applications store and retrieve private keys and their corresponding certificate +chains. Any application can use the keychain API to install and store user +certificates and CAs securely.

    + + +

    Address Space Layout +Randomization

    + +

    Android 4.0 now provides address space layout randomization (ASLR) to help +protect system and third party applications from exploitation due to +memory-management issues.

    + + +

    Enhancements for Enterprise

    + +

    VPN client +API

    + +

    Developers can now build or extend their own VPN solutions on the platform +using a new VPN API and underlying secure credential storage. With user +permission, applications can configure addresses and routing rules, process +outgoing and incoming packets, and establish secure tunnels to a remote server. +Enterprises can also take advantage of a standard VPN client built into the +platform that provides access to L2TP and IPSec protocols.

    + + +

    Device policy management +for camera

    + +

    The platform adds a new policy control for administrators who manage devices +using an installed Device Policy Manager. Administrators can now remotely +disable the camera on a managed device for users working in sensitive +environments.

    + + + + + diff --git a/docs/html/about/versions/android-4.0.3.jd b/docs/html/about/versions/android-4.0.3.jd new file mode 100644 index 000000000000..b7d4db3c5229 --- /dev/null +++ b/docs/html/about/versions/android-4.0.3.jd @@ -0,0 +1,304 @@ +page.title=Android 4.0.3 Platform +sdk.platform.version=4.0.3 +sdk.platform.apiLevel=15 +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. Previous APIs
    4. +
    5. API Level
    6. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + +

    API Level: {@sdkPlatformApiLevel}

    + +

    Android {@sdkPlatformVersion} is an incremental release of the Android 4.x +(Ice Cream Sandwich) platform family. This release includes new features for +users and developers, API changes, and various bug fixes.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + + +

    API Overview

    + +

    The sections below provide a technical overview of new APIs in Android 4.0.3.

    + + + + + + + +

    Social stream API in Contacts Provider

    + +

    Applications that use social stream data such as status updates and check-ins +can now sync that data with each of the user’s contacts, providing items in a +stream along with photos for each.

    + +

    The database table that contains an individual contact’s social stream is +defined by {@link android.provider.ContactsContract.StreamItems}, the Uri for +which is nested within the {@link android.provider.ContactsContract.RawContacts} +directory to which the stream items belong. Each social stream table includes +several columns for metadata about each stream item, such as an icon +representing the source (an avatar), a label for the item, the primary text +content, comments about the item (such as responses from other people), and +more. Photos associated with a stream are stored in another table, defined by +{@link android.provider.ContactsContract.StreamItemPhotos}, which is available +as a sub-directory of the {@link android.provider.ContactsContract.StreamItems} +Uri.

    + +

    See {@link android.provider.ContactsContract.StreamItems} and +{@link android.provider.ContactsContract.StreamItemPhotos} for more information.

    + +

    To read or write social stream items for a contact, an application must +request permission from the user by declaring <uses-permission +android:name="android.permission.READ_SOCIAL_STREAM"> and/or <uses-permission +android:name="android.permission.WRITE_SOCIAL_STREAM"> in their manifest files.

    + +

    Calendar Provider

    +
      +
    • Adds the class {@link android.provider.CalendarContract.Colors} to represent +a color table in the Calendar +Provider. The class provides fields for accessing +colors available for a given account. Colors are referenced by +{@link android.provider.CalendarContract.ColorsColumns#COLOR_KEY COLOR_KEY} +which must be unique for a given account name/type. These values can only be +updated by the sync adapter.
    • +
    • Adds {@link android.provider.CalendarContract.CalendarColumns#ALLOWED_AVAILABILITY ALLOWED_AVAILABILITY} +and +{@link android.provider.CalendarContract.CalendarColumns#ALLOWED_ATTENDEE_TYPES ALLOWED_ATTENDEE_TYPES} +for exchange/sync support.
    • +
    • Adds {@link android.provider.CalendarContract.AttendeesColumns#TYPE_RESOURCE} +(such as conference rooms) for attendees and +{@link android.provider.CalendarContract.EventsColumns#AVAILABILITY_TENTATIVE}, +as well as {@link android.provider.CalendarContract.EventsColumns#EVENT_COLOR_KEY} +for events.
    • +
    + +

    Home screen widgets

    + +

    Starting from Android 4.0, home screen widgets should no longer include their +own padding. Instead, the system now automatically adds padding for each widget, +based the characteristics of the current screen. This leads to a more uniform, +consistent presentation of widgets in a grid. To assist applications that host +home screen widgets, the platform provides a new method +{@link android.appwidget.AppWidgetHostView#getDefaultPaddingForWidget(android.content.Context, android.content.ComponentName, android.graphics.Rect) +getDefaultPaddingForWidget()}. Applications can call this method to get the +system-defined padding and account for it when computing the number of cells to +allocate to the widget.

    + +

    Spell-checking

    + +
      +
    • For apps that accessing spell-checker services, a new {@link +android.view.textservice.SpellCheckerSession#cancel() cancel()} method cancels +any pending and running spell-checker tasks in a session.
    • + +
    • For spell-checker services, a new suggestions flag, +{@link android.view.textservice.SuggestionsInfo#RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS}, +lets the services distinguish higher-confidence suggestions from +lower-confidence ones. For example, a spell-checker could set the flag if an +input word is not in the user dictionary but has likely suggestions, or not set +the flag if an input word is not in the dictionary and has suggestions that are +likely to be less useful. + +

      Apps connected to the spell-checker can use the {@link +android.view.textservice.SuggestionsInfo#RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS} +flag in combination with other suggestion attributes, as well as the {@link +android.view.textservice.SuggestionsInfo#getSuggestionsAttributes()} and {@link +android.view.textservice.SuggestionsInfo#getSuggestionsCount()} methods, to +determine whether to mark input words as typos and offer suggestions.

    • + +
    • A new {@link android.text.style.SuggestionSpan#FLAG_AUTO_CORRECTION} style +for text spans indicates that auto correction is about to be applied to a +word/text that the user is typing/composing. This type of suggestion is rendered +differently, to indicate the auto correction is happening.
    • +
    + +

    Bluetooth

    +

    New public methods {@link +android.bluetooth.BluetoothDevice#fetchUuidsWithSdp()} and {@link +android.bluetooth.BluetoothDevice#getUuids()} let apps determine the features +(UUIDs) supported by a remote device. In the case of {@link +android.bluetooth.BluetoothDevice#fetchUuidsWithSdp()}, the system performs a +service discovery on the remote device to get the UUIDs supported, then +broadcasts the result in an {@link +android.bluetooth.BluetoothDevice#ACTION_UUID} intent.

    + +

    UI toolkit

    + +

    New methods {@link android.app.Fragment#setUserVisibleHint(boolean) setUserVisibleHint()} and +{@link android.app.Fragment#getUserVisibleHint() getUserVisibleHint()} allow a +fragment to set a hint of whether or not it is currently user-visible. The +system defers the start of fragments that are not user-visible until the loaders +for visible fragments have run. The visibility hint is "true" by default. +

    + +

    Graphics

    + +
      +
    • New method {@link android.graphics.SurfaceTexture#setDefaultBufferSize(int +width, int height)} in {@link android.graphics.SurfaceTexture} sets the default size of the image +buffers. This method may be used to set the image size when producing images +with {@link android.graphics.Canvas} (via {@link +android.view.Surface#lockCanvas}), or OpenGL ES (via an EGLSurface).
    • +
    • Adds definitions for the enums of the GL_OES_EGL_image_external OpenGL ES extension — +{@link android.opengl.GLES11Ext#GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES}, +{@link android.opengl.GLES11Ext#GL_SAMPLER_EXTERNAL_OES}, +{@link android.opengl.GLES11Ext#GL_TEXTURE_BINDING_EXTERNAL_OES}, and +{@link android.opengl.GLES11Ext#GL_TEXTURE_EXTERNAL_OES}.
    • +
    + +

    Accessibility

    + +
      +
    • Clients of {@link android.widget.RemoteViews} can now use the method {@link +android.widget.RemoteViews#setContentDescription(int, java.lang.CharSequence) +setContentDescription()} to set and get the content description of any View in +the inflated layout.
    • + +
    • The methods {@link android.view.accessibility.AccessibilityRecord#getMaxScrollX()}, +{@link android.view.accessibility.AccessibilityRecord#getMaxScrollY()}, +{@link android.view.accessibility.AccessibilityRecord#setMaxScrollX(int) setMaxScrollX()}, and +{@link android.view.accessibility.AccessibilityRecord#setMaxScrollY(int) setMaxScrollY()} +allow apps to get and set the maximum scroll offset for an +{@link android.view.accessibility.AccessibilityRecord} object.
    • + +
    • When touch-exploration mode is enabled, a new secure setting +{@link android.provider.Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD} +indicates whether the user requests the IME to speak text entered in password fields, even when +a headset is not in use. By default, no password text is spoken unless a headset +is in use.
    • +
    + +

    Text-to-speech

    + +
      +
    • Adds the new method {@link +android.speech.tts.TextToSpeech.Engine#getFeatures(java.util.Locale) +getFeatures()}for querying and enabling network TTS support. +
    • Adds a new listener class, {@link +android.speech.tts.UtteranceProgressListener}, that engines can register to +receive notification of speech-synthesis errors.
    • +
    + +

    Database

    + +
      +
    • A new {@link android.database.CrossProcessCursorWrapper} class lets content +providers return results for a cross-process query more efficiently. The new +class is a useful building block for wrapping cursors that will be sent to +processes remotely. It can also transform normal {@link android.database.Cursor} +objects into {@link android.database.CrossProcessCursor} objects +transparently. + +

      The {@link android.database.CrossProcessCursorWrapper} class fixes common +performance issues and bugs that applications have encountered when +implementing content providers.

    • + +
    • The {@link android.database.CursorWindow#CursorWindow(java.lang.String)} +constructor now takes a name string as input. The system no longer distinguishes +between local and remote cursor windows, so {@link +android.database.CursorWindow#CursorWindow(boolean)} is now deprecated.
    • +
    + +

    Intents

    + +

    Adds new categories for targeting common types of applications on the +device, such as {@link android.content.Intent#CATEGORY_APP_BROWSER}, {@link +android.content.Intent#CATEGORY_APP_CALENDAR}, {@link +android.content.Intent#CATEGORY_APP_MAPS}, and more. + +

    Camera

    + +
      +
    • {@link android.media.MediaMetadataRetriever} adds the new constant +{@link android.media.MediaMetadataRetriever#METADATA_KEY_LOCATION} to let apps +access retrieve location information for an image or video.
    • + +
    • {@link android.media.CamcorderProfile} adds the QVGA (320x240) resolution +profiles. Quality level is represented by the +{@link android.media.CamcorderProfile#QUALITY_QVGA}.and +{@link android.media.CamcorderProfile#QUALITY_TIME_LAPSE_QVGA} constants.
    • + +
    • New methods {@link android.hardware.Camera.Parameters#setVideoStabilization(boolean) setVideoStabilization()}, +{@link android.hardware.Camera.Parameters#getVideoStabilization() setVideoStabilization()}, and {@link android.hardware.Camera.Parameters#isVideoStabilizationSupported() isVideoStabilizationSupported()} +let you check and manage video stabilization for a {@link android.hardware.Camera}.
    • +
    + +

    Permissions

    + +

    The following are new permissions:

    +
      +
    • {@link android.Manifest.permission#READ_SOCIAL_STREAM} and +{@link android.Manifest.permission#WRITE_SOCIAL_STREAM}: Allow a sync +adapter to read and write social stream data to a contact in the shared +Contacts Provider.
    • +
    + + +
    +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level +{@sdkPlatformApiLevel}), see the API Differences Report.

    +
    + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} API is assigned an integer +identifier—{@sdkPlatformApiLevel}—that is stored in the system itself. +This identifier, called the "API level", allows the system to correctly determine whether an +application is compatible with the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the +application against an Android platform that supports API level {@sdkPlatformApiLevel} or +higher. Depending on your needs, you might also need to add an +android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the +{@code <uses-sdk>} +element.

    + +

    For more information, see the API Levels +document.

    + diff --git a/docs/html/about/versions/android-4.0.jd b/docs/html/about/versions/android-4.0.jd new file mode 100644 index 000000000000..bea07253c87b --- /dev/null +++ b/docs/html/about/versions/android-4.0.jd @@ -0,0 +1,1829 @@ +page.title=Android 4.0 Platform +sdk.platform.version=4.0 +sdk.platform.apiLevel=14 +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. API Overview
    2. +
    3. Previous APIs
    4. +
    5. API Level
    6. +
    + +

    Reference

    +
      +
    1. API +Differences Report »
    2. +
    + +
    +
    + + +

    API Level: {@sdkPlatformApiLevel}

    + +

    Android 4.0 is a major platform release that adds a variety of new features for users and app +developers. Besides all the new features and APIs discussed below, Android 4.0 is an important +platform release because it brings the extensive set of APIs and Holographic themes from Android 3.x +to smaller screens. As an app developer, you now have a single platform and unified API framework +that enables you to develop and publish your application with a single APK that provides an +optimized user experience for handsets, tablets, and more, when running the same version of +Android—Android 4.0 (API level 14) or greater.

    + +

    For developers, the Android {@sdkPlatformVersion} platform is available as a +downloadable component for the Android SDK. The downloadable platform includes +an Android library and system image, as well as a set of emulator skins and +more. To get started developing or testing against Android {@sdkPlatformVersion}, +use the Android SDK Manager to download the platform into your SDK.

    + +

    API Overview

    + +

    The sections below provide a technical overview of new APIs in Android 4.0.

    + + + + + + + +

    Social APIs in Contacts Provider

    + +

    The contact APIs defined by the {@link android.provider.ContactsContract} provider have been +extended to support new social-oriented features such as a personal profile for the device owner and +the ability for users to invite individual contacts to social networks that are installed on the +device.

    + + +

    User Profile

    + +

    Android now includes a personal profile that represents the device owner, as defined by the +{@link android.provider.ContactsContract.Profile} table. Social apps that maintain a user identity +can contribute to the user's profile data by creating a new {@link +android.provider.ContactsContract.RawContacts} entry within the {@link +android.provider.ContactsContract.Profile}. That is, raw contacts that represent the device user do +not belong in the traditional raw contacts table defined by the {@link +android.provider.ContactsContract.RawContacts} Uri; instead, you must add a profile raw contact in +the table at {@link android.provider.ContactsContract.Profile#CONTENT_RAW_CONTACTS_URI}. Raw +contacts in this table are then aggregated into the single user-visible profile labeled "Me".

    + +

    Adding a new raw contact for the profile requires the {@link +android.Manifest.permission#WRITE_PROFILE} permission. Likewise, in order to read from the profile +table, you must request the {@link android.Manifest.permission#READ_PROFILE} permission. However, +most apps should not need to read the user profile, even when contributing data to the +profile. Reading the user profile is a sensitive permission and you should expect users to be +skeptical of apps that request it.

    + + +

    Invite Intent

    + +

    The {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent action allows an app +to invoke an action that indicates the user wants to add a contact to a social network. The app +receiving the app uses it to invite the specified contact to that +social network. Most apps will be on the receiving-end of this operation. For example, the +built-in People app invokes the invite intent when the user selects "Add connection" for a specific +social app that's listed in a person's contact details.

    + +

    To make your app visible as in the "Add connection" list, your app must provide a sync adapter to +sync contact information from your social network. You must then indicate to the system that your +app responds to the {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent by +adding the {@code inviteContactActivity} attribute to your app’s sync configuration file, with a +fully-qualified name of the activity that the system should start when sending the invite intent. +The activity that starts can then retrieve the URI for the contact in question from the intent’s +data and perform the necessary work to invite that contact to the network or add the person to the +user’s connections.

    + +

    See the Sample Sync +Adapter app for an example (specifically, see the contacts.xml +file).

    + + +

    Large photos

    + +

    Android now supports high resolution photos for contacts. Now, when you push a photo into a +contact record, the system processes it into both a 96x96 thumbnail (as it has previously) and a +256x256 "display photo" that's stored in a new file-based photo store (the exact dimensions that the +system chooses may vary in the future). You can add a large photo to a contact by putting a large +photo in the usual {@link android.provider.ContactsContract.CommonDataKinds.Photo#PHOTO} column of a +data row, which the system will then process into the appropriate thumbnail and display photo +records.

    + + +

    Contact Usage Feedback

    + +

    The new {@link android.provider.ContactsContract.DataUsageFeedback} APIs allow you to help track +how often the user uses particular methods of contacting people, such as how often the user uses +each phone number or e-mail address. This information helps improve the ranking for each contact +method associated with each person and provide better suggestions for contacting each person.

    + + + + + +

    Calendar Provider

    + +

    The new calendar APIs allow you to read, add, modify and delete calendars, events, attendees, +reminders and alerts, which are stored in the Calendar Provider.

    + +

    A variety of apps and widgets can use these APIs to read and modify calendar events. However, +some of the most compelling use cases are sync adapters that synchronize the user's calendar from +other calendar services with the Calendar Provider, in order to offer a unified location for all the +user's events. Google Calendar events, for example, are synchronized with the Calendar Provider by +the Google Calendar Sync Adapter, allowing these events to be viewed with Android's built-in +Calendar app.

    + +

    The data model for calendars and event-related information in the Calendar Provider is +defined by {@link android.provider.CalendarContract}. All the user’s calendar data is stored in a +number of tables defined by various subclasses of {@link android.provider.CalendarContract}:

    + +
      +
    • The {@link android.provider.CalendarContract.Calendars} table holds the calendar-specific +information. Each row in this table contains the details for a single calendar, such as the name, +color, sync information, and so on.
    • + +
    • The {@link android.provider.CalendarContract.Events} table holds event-specific information. +Each row in this table contains the information for a single event, such as the +event title, location, start time, end time, and so on. The event can occur one time or recur +multiple times. Attendees, reminders, and extended properties are stored in separate tables and +use the event’s {@code _ID} to link them with the event.
    • + +
    • The {@link android.provider.CalendarContract.Instances} table holds the start and end time for +occurrences of an event. Each row in this table represents a single occurrence. For one-time events +there is a one-to-one mapping of instances to events. For recurring events, multiple rows are +automatically generated to correspond to the multiple occurrences of that event.
    • + +
    • The {@link android.provider.CalendarContract.Attendees} table holds the event attendee or guest +information. Each row represents a single guest of an event. It specifies the type of guest the +person is and the person’s response for the event.
    • + +
    • The {@link android.provider.CalendarContract.Reminders} table holds the alert/notification data. +Each row represents a single alert for an event. An event can have multiple reminders. The number of +reminders per event is specified in {@code MAX_REMINDERS}, which is set by the sync adapter that +owns the given calendar. Reminders are specified in number-of-minutes before the event is +scheduled and specify an alarm method such as to use an alert, email, or SMS to remind +the user.
    • + +
    • The {@link android.provider.CalendarContract.ExtendedProperties} table hold opaque data fields +used by the sync adapter. The provider takes no action with items in this table except to delete +them when their related events are deleted.
    • +
    + +

    To access a user’s calendar data with the Calendar Provider, your application must request +the {@link android.Manifest.permission#READ_CALENDAR} permission (for read access) and +{@link android.Manifest.permission#WRITE_CALENDAR} (for write access).

    + + +

    Event intent

    + +

    If all you want to do is add an event to the user’s calendar, you can use an {@link +android.content.Intent#ACTION_INSERT} intent with the data defined by {@link +android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} in order to start an +activity in the Calendar app that creates new events. Using the intent does not require any +permission and you can specify event details with the following extras:

    + +
      +
    • {@link android.provider.CalendarContract.EventsColumns#TITLE Events.TITLE}: Name for the +event
    • +
    • {@link +android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME}: +Event begin time in milliseconds from the +epoch
    • +
    • {@link +android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME}: Event +end time in milliseconds from the epoch
    • +
    • {@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION}: +Location of the event
    • +
    • {@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION}: Event +description
    • +
    • {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL}: Email addresses of those to +invite
    • +
    • {@link android.provider.CalendarContract.EventsColumns#RRULE Events.RRULE}: The recurrence +rule for the event
    • +
    • {@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL}: +Whether the event is private or public
    • +
    • {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY}: +Whether the time period of this event allows for other events to be scheduled at the same time
    • +
    + + + + +

    Voicemail Provider

    + +

    The new Voicemail Provider allows applications to add voicemails to the +device, in order to present all the user's voicemails in a single visual presentation. For instance, +it’s possible that a user has multiple voicemail sources, such as +one from the phone’s service provider and others from VoIP or other alternative voice +services. These apps can use the Voicemail Provider APIs to add their voicemails to the device. The +built-in Phone application then presents all voicemails to the user in a unified presentation. +Although the system’s Phone application is the only application that can read all the voicemails, +each application that provides voicemails can read those that it has added to the system (but cannot +read voicemails from other services).

    + +

    Because the APIs currently do not allow third-party apps to read all the voicemails from the +system, the only third-party apps that should use the voicemail APIs are those that have voicemail +to deliver to the user.

    + +

    The {@link android.provider.VoicemailContract} class defines the content provider for the +Voicemail Provder. The subclasses {@link android.provider.VoicemailContract.Voicemails} and {@link +android.provider.VoicemailContract.Status} provide tables in which apps can +insert voicemail data for storage on the device. For an example of a voicemail provider app, see the +Voicemail Provider +Demo.

    + + + + + +

    Multimedia

    + +

    Android 4.0 adds several new APIs for applications that interact with media such as photos, +videos, and music.

    + + +

    Media Effects

    + +

    A new media effects framework allows you to apply a variety of visual effects to images and +videos. For example, image effects allow you to easily fix red-eye, convert an image to grayscale, +adjust brightness, adjust saturation, rotate an image, apply a fisheye effect, and much more. The +system performs all effects processing on the GPU to obtain maximum performance.

    + +

    For maximum performance, effects are applied directly to OpenGL textures, so your application +must have a valid OpenGL context before it can use the effects APIs. The textures to which you apply +effects may be from bitmaps, videos or even the camera. However, there are certain restrictions that +textures must meet:

    +
      +
    1. They must be bound to a {@link android.opengl.GLES20#GL_TEXTURE_2D} texture image
    2. +
    3. They must contain at least one mipmap level
    4. +
    + +

    An {@link android.media.effect.Effect} object defines a single media effect that you can apply to +an image frame. The basic workflow to create an {@link android.media.effect.Effect} is:

    + +
      +
    1. Call {@link android.media.effect.EffectContext#createWithCurrentGlContext +EffectContext.createWithCurrentGlContext()} from your OpenGL ES 2.0 context.
    2. +
    3. Use the returned {@link android.media.effect.EffectContext} to call {@link +android.media.effect.EffectContext#getFactory EffectContext.getFactory()}, which returns an instance +of {@link android.media.effect.EffectFactory}.
    4. +
    5. Call {@link android.media.effect.EffectFactory#createEffect createEffect()}, passing it an +effect name from @link android.media.effect.EffectFactory}, such as {@link +android.media.effect.EffectFactory#EFFECT_FISHEYE} or {@link +android.media.effect.EffectFactory#EFFECT_VIGNETTE}.
    6. +
    + +

    You can adjust an effect’s parameters by calling {@link android.media.effect.Effect#setParameter +setParameter()} and passing a parameter name and parameter value. Each type of effect accepts +different parameters, which are documented with the effect name. For example, {@link +android.media.effect.EffectFactory#EFFECT_FISHEYE} has one parameter for the {@code scale} of the +distortion.

    + +

    To apply an effect on a texture, call {@link android.media.effect.Effect#apply apply()} on the +{@link +android.media.effect.Effect} and pass in the input texture, it’s width and height, and the output +texture. The input texture must be bound to a {@link android.opengl.GLES20#GL_TEXTURE_2D} texture +image (usually done by calling the {@link android.opengl.GLES20#glTexImage2D glTexImage2D()} +function). You may provide multiple mipmap levels. If the output texture has not been bound to a +texture image, it will be automatically bound by the effect as a {@link +android.opengl.GLES20#GL_TEXTURE_2D} and with one mipmap level (0), which will have the same +size as the input.

    + +

    All effects listed in {@link android.media.effect.EffectFactory} are guaranteed to be supported. +However, some additional effects available from external libraries are not supported by all devices, +so you must first check if the desired effect from the external library is supported by calling +{@link android.media.effect.EffectFactory#isEffectSupported isEffectSupported()}.

    + + +

    Remote control client

    + +

    The new {@link android.media.RemoteControlClient} allows media players to enable playback +controls from remote control clients such as the device lock screen. Media players can also expose +information about the media currently playing for display on the remote control, such as track +information and album art.

    + +

    To enable remote control clients for your media player, instantiate a {@link +android.media.RemoteControlClient} with its constructor, passing it a {@link +android.app.PendingIntent} that broadcasts {@link +android.content.Intent#ACTION_MEDIA_BUTTON}. The intent must also declare the explicit {@link +android.content.BroadcastReceiver} component in your app that handles the {@link +android.content.Intent#ACTION_MEDIA_BUTTON} event.

    + +

    To declare which media control inputs your player can handle, you must call {@link +android.media.RemoteControlClient#setTransportControlFlags setTransportControlFlags()} on your +{@link android.media.RemoteControlClient}, passing a set of {@code FLAG_KEY_MEDIA_*} flags, such as +{@link android.media.RemoteControlClient#FLAG_KEY_MEDIA_PREVIOUS} and {@link +android.media.RemoteControlClient#FLAG_KEY_MEDIA_NEXT}.

    + +

    You must then register your {@link android.media.RemoteControlClient} by passing it to {@link +android.media.AudioManager#registerRemoteControlClient MediaManager.registerRemoteControlClient()}. +Once registered, the broadcast receiver you declared when you instantiated the {@link +android.media.RemoteControlClient} will receive {@link android.content.Intent#ACTION_MEDIA_BUTTON} +events when a button is pressed from a remote control. The intent you receive includes the {@link +android.view.KeyEvent} for the media key pressed, which you can retrieve from the intent with {@link +android.content.Intent#getParcelableExtra getParcelableExtra(Intent.EXTRA_KEY_EVENT)}.

    + +

    To display information on the remote control about the media playing, call {@link +android.media.RemoteControlClient#editMetadata editMetaData()} and add metadata to the returned +{@link android.media.RemoteControlClient.MetadataEditor}. You can supply a bitmap for media artwork, +numerical information such as elapsed time, and text information such as the track title. For +information on available keys see the {@code METADATA_KEY_*} flags in {@link +android.media.MediaMetadataRetriever}.

    + +

    For a sample implementation, see the Random Music Player, which +provides compatibility logic such that it enables the remote control client on Android 4.0 +devices while continuing to support devices back to Android 2.1.

    + + +

    Media player

    + +
      +
    • Streaming online media from {@link android.media.MediaPlayer} now requires the {@link +android.Manifest.permission#INTERNET} permission. If you use {@link android.media.MediaPlayer} to +play content from the Internet, be sure to add the {@link android.Manifest.permission#INTERNET} +permission to your manifest or else your media playback will not work beginning with Android +4.0.
    • + +
    • {@link android.media.MediaPlayer#setSurface(Surface) setSurface()} allows you define a {@link +android.view.Surface} to behave as the video sink.
    • + +
    • {@link android.media.MediaPlayer#setDataSource(Context,Uri,Map) setDataSource()} allows you to +send additional HTTP headers with your request, which can be useful for HTTP(S) live streaming
    • + +
    • HTTP(S) live streaming now respects HTTP cookies across requests
    • +
    + + +

    Media types

    + +

    Android 4.0 adds support for:

    +
      +
    • HTTP/HTTPS live streaming protocol version 3
    • +
    • ADTS raw AAC audio encoding
    • +
    • WEBP images
    • +
    • Matroska video
    • +
    +

    For more info, see Supported Media +Formats.

    + + + + + +

    Camera

    + +

    The {@link android.hardware.Camera} class now includes APIs for detecting faces and controlling +focus and metering areas.

    + + +

    Face detection

    + +

    Camera apps can now enhance their abilities with Android’s face detection APIs, which not +only detect the face of a subject, but also specific facial features, such as the eyes and mouth. +

    + +

    To detect faces in your camera application, you must register a {@link +android.hardware.Camera.FaceDetectionListener} by calling {@link +android.hardware.Camera#setFaceDetectionListener setFaceDetectionListener()}. You can then start +your camera surface and start detecting faces by calling {@link +android.hardware.Camera#startFaceDetection}.

    + +

    When the system detects one or more faces in the camera scene, it calls the {@link +android.hardware.Camera.FaceDetectionListener#onFaceDetection onFaceDetection()} callback in your +implementation of {@link android.hardware.Camera.FaceDetectionListener}, including an array of +{@link android.hardware.Camera.Face} objects.

    + +

    An instance of the {@link android.hardware.Camera.Face} class provides various information about +the face detected, including:

    +
      +
    • A {@link android.graphics.Rect} that specifies the bounds of the face, relative to the camera's +current field of view
    • +
    • An integer betwen 1 and 100 that indicates how confident the system is that the object is a +human face
    • +
    • A unique ID so you can track multiple faces
    • +
    • Several {@link android.graphics.Point} objects that indicate where the eyes and mouth are +located
    • +
    + +

    Note: Face detection may not be supported on some +devices, so you should check by calling {@link +android.hardware.Camera.Parameters#getMaxNumDetectedFaces()} and ensure the return +value is greater than zero. Also, some devices may not support identification of eyes and mouth, +in which case, those fields in the {@link android.hardware.Camera.Face} object will be null.

    + + +

    Focus and metering areas

    + +

    Camera apps can now control the areas that the camera uses for focus and for metering white +balance +and auto-exposure. Both features use the new {@link android.hardware.Camera.Area} class to specify +the region of the camera’s current view that should be focused or metered. An instance of the {@link +android.hardware.Camera.Area} class defines the bounds of the area with a {@link +android.graphics.Rect} and the area's weight—representing the level of importance of that +area, relative to other areas in consideration—with an integer.

    + +

    Before setting either a focus area or metering area, you should first call {@link +android.hardware.Camera.Parameters#getMaxNumFocusAreas} or {@link +android.hardware.Camera.Parameters#getMaxNumMeteringAreas}, respectively. If these return zero, then +the device does not support the corresponding feature.

    + +

    To specify the focus or metering areas to use, simply call {@link +android.hardware.Camera.Parameters#setFocusAreas setFocusAreas()} or {@link +android.hardware.Camera.Parameters#setMeteringAreas setMeteringAreas()}. Each take a {@link +java.util.List} of {@link android.hardware.Camera.Area} objects that indicate the areas to consider +for focus or metering. For example, you might implement a feature that allows the user to set the +focus area by touching an area of the preview, which you then translate to an {@link +android.hardware.Camera.Area} object and request that the camera focus on that area of the scene. +The focus or exposure in that area will continually update as the scene in the area changes.

    + + +

    Continuous auto focus for photos

    + +

    You can now enable continuous auto focusing (CAF) when taking photos. To enable CAF in your +camera app, pass {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE} +to {@link android.hardware.Camera.Parameters#setFocusMode setFocusMode()}. When ready to capture +a photo, call {@link android.hardware.Camera#autoFocus autoFocus()}. Your {@link +android.hardware.Camera.AutoFocusCallback} immediately receives a callback to indicate whether +focus was achieved. To resume CAF after receiving the callback, you must call {@link +android.hardware.Camera#cancelAutoFocus()}.

    + +

    Note: Continuous auto focus is also supported when capturing +video, using {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO}, which was +added in API level 9.

    + + +

    Other camera features

    + +
      +
    • While recording video, you can now call {@link android.hardware.Camera#takePicture +takePicture()} to save a photo without interrupting the video session. Before doing so, you should +call {@link android.hardware.Camera.Parameters#isVideoSnapshotSupported} to be sure the hardware +supports it.
    • + +
    • You can now lock auto exposure and white balance with {@link +android.hardware.Camera.Parameters#setAutoExposureLock setAutoExposureLock()} and {@link +android.hardware.Camera.Parameters#setAutoWhiteBalanceLock setAutoWhiteBalanceLock()} to prevent +these properties from changing.
    • + +
    • You can now call {@link android.hardware.Camera#setDisplayOrientation +setDisplayOrientation()} while the camera preview is running. Previously, you could call this +only before beginning the preview, but you can now change the orientation at any time.
    • +
    + + +

    Camera broadcast intents

    + +
      +
    • {@link android.hardware.Camera#ACTION_NEW_PICTURE Camera.ACTION_NEW_PICTURE}: +This indicates that the user has captured a new photo. The built-in Camera app invokes this +broadcast after a photo is captured and third-party camera apps should also broadcast this intent +after capturing a photo.
    • +
    • {@link android.hardware.Camera#ACTION_NEW_VIDEO Camera.ACTION_NEW_VIDEO}: +This indicates that the user has captured a new video. The built-in Camera app invokes this +broadcast after a video is recorded and third-party camera apps should also broadcast this intent +after capturing a video.
    • +
    + + + + + +

    Android Beam (NDEF Push with NFC)

    + +

    Android Beam is a new NFC feature that allows you to send NDEF messages from one device to +another (a process also known as “NDEF Push"). The data transfer is initiated when two +Android-powered devices that support Android Beam are in close proximity (about 4 cm), usually with +their backs touching. The data inside the NDEF message can contain any data that you wish to share +between devices. For example, the People app shares contacts, YouTube shares videos, and Browser +shares URLs using Android Beam.

    + +

    To transmit data between devices using Android Beam, you need to create an {@link +android.nfc.NdefMessage} that contains the information you want to share while your activity is in +the foreground. You must then pass the {@link android.nfc.NdefMessage} to the system in one of two +ways:

    + +
      +
    • Define a single {@link android.nfc.NdefMessage} to push while in the activity: +

      Call {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} at any time to set +the message you want to send. For instance, you might call this method and pass it your {@link +android.nfc.NdefMessage} during your activity’s {@link android.app.Activity#onCreate onCreate()} +method. Then, whenever Android Beam is activated with another device while the activity is in the +foreground, the system sends the {@link android.nfc.NdefMessage} to the other device.

    • + +
    • Define the {@link android.nfc.NdefMessage} to push at the time that Android Beam is initiated: +

      Implement {@link android.nfc.NfcAdapter.CreateNdefMessageCallback}, in which your +implementation of the {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} +method returns the {@link android.nfc.NdefMessage} you want to send. Then pass the {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback} implementation to {@link +android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}.

      +

      In this case, when Android Beam is activated with another device while your activity is in the +foreground, the system calls {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} to retrieve +the {@link android.nfc.NdefMessage} you want to send. This allows you to define the {@link +android.nfc.NdefMessage} to deliver only once Android Beam is initiated, in case the contents +of the message might vary throughout the life of the activity.

    • +
    + +

    In case you want to run some specific code once the system has successfully delivered your NDEF +message to the other device, you can implement {@link +android.nfc.NfcAdapter.OnNdefPushCompleteCallback} and set it with {@link +android.nfc.NfcAdapter#setOnNdefPushCompleteCallback setNdefPushCompleteCallback()}. The system will +then call {@link android.nfc.NfcAdapter.OnNdefPushCompleteCallback#onNdefPushComplete +onNdefPushComplete()} when the message is delivered.

    + +

    On the receiving device, the system dispatches NDEF Push messages in a similar way to regular NFC +tags. The system invokes an intent with the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} +action to start an activity, with either a URL or a MIME type set according to the first {@link +android.nfc.NdefRecord} in the {@link android.nfc.NdefMessage}. For the activity you want to +respond, you can declare intent filters for the URLs or MIME types your app cares about. For more +information about Tag Dispatch see the NFC developer guide.

    + +

    If you want your {@link android.nfc.NdefMessage} to carry a URI, you can now use the convenience +method {@link android.nfc.NdefRecord#createUri createUri} to construct a new {@link +android.nfc.NdefRecord} based on either a string or a {@link android.net.Uri} object. If the URI is +a special format that you want your application to also receive during an Android Beam event, you +should create an intent filter for your activity using the same URI scheme in order to receive the +incoming NDEF message.

    + +

    You should also pass an “Android application record" with your {@link android.nfc.NdefMessage} in +order to guarantee that your application handles the incoming NDEF message, even if other +applications filter for the same intent action. You can create an Android application record by +calling {@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}, passing it +your application’s package name. When the other device receives the NDEF message with the +application record and multiple applications contain activities that handle the specified intent, +the system always delivers the message to the activity in your application (based on the matching +application record). If the target device does not currently have your application installed, the +system uses the Android application record to launch Google Play and take the user to the +application in order to install it.

    + +

    If your application doesn’t use NFC APIs to perform NDEF Push messaging, then Android provides a +default behavior: When your application is in the foreground on one device and Android Beam is +invoked with another Android-powered device, then the other device receives an NDEF message with an +Android application record that identifies your application. If the receiving device has the +application installed, the system launches it; if it’s not installed, Google Play opens and takes +the user to your application in order to install it.

    + +

    You can read more about Android Beam and other NFC features in the NFC Basics developer guide. For some example code +using Android Beam, see the Android +Beam Demo.

    + + + + + +

    Wi-Fi Direct

    + +

    Android now supports Wi-Fi Direct for peer-to-peer (P2P) connections between Android-powered +devices and other device types without a hotspot or Internet connection. The Android framework +provides a set of Wi-Fi P2P APIs that allow you to 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.

    + +

    A new package, {@link android.net.wifi.p2p}, contains all the APIs for performing peer-to-peer +connections with Wi-Fi. The primary class you need to work with is {@link +android.net.wifi.p2p.WifiP2pManager}, which you can acquire by calling {@link +android.app.Activity#getSystemService getSystemService(WIFI_P2P_SERVICE)}. The {@link +android.net.wifi.p2p.WifiP2pManager} includes APIs that allow you to:

    +
      +
    • Initialize your application for P2P connections by calling {@link +android.net.wifi.p2p.WifiP2pManager#initialize initialize()}
    • + +
    • Discover nearby devices by calling {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers +discoverPeers()}
    • + +
    • Start a P2P connection by calling {@link android.net.wifi.p2p.WifiP2pManager#connect +connect()}
    • +
    • And more
    • +
    + +

    Several other interfaces and classes are necessary as well, such as:

    +
      +
    • The {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} interface allows you to receive +callbacks when an operation such as discovering peers or connecting to them succeeds or fails.
    • + +
    • {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} interface allows you to receive +information about discovered peers. The callback provides a {@link +android.net.wifi.p2p.WifiP2pDeviceList}, from which you can retrieve a {@link +android.net.wifi.p2p.WifiP2pDevice} object for each device within range and get information such as +the device name, address, device type, the WPS configurations the device supports, and more.
    • + +
    • The {@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener} interface allows you to +receive information about a P2P group. The callback provides a {@link +android.net.wifi.p2p.WifiP2pGroup} object, which provides group information such as the owner, the +network name, and passphrase.
    • + +
    • {@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener} interface allows you to +receive information about the current connection. The callback provides a {@link +android.net.wifi.p2p.WifiP2pInfo} object, which has information such as whether a group has been +formed and who is the group owner.
    • +
    + +

    In order to use the Wi-Fi P2P APIs, your app must request the following user permissions:

    +
      +
    • {@link android.Manifest.permission#ACCESS_WIFI_STATE}
    • +
    • {@link android.Manifest.permission#CHANGE_WIFI_STATE}
    • +
    • {@link android.Manifest.permission#INTERNET} (although your app doesn’t technically connect +to the Internet, communicating to Wi-Fi Direct peers with standard java sockets requires Internet +permission).
    • +
    + +

    The Android system also broadcasts several different actions during certain Wi-Fi P2P events:

    +
      +
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}: The P2P +connection state has changed. This carries {@link +android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_P2P_INFO} with a {@link +android.net.wifi.p2p.WifiP2pInfo} object and {@link +android.net.wifi.p2p.WifiP2pManager#EXTRA_NETWORK_INFO} with a {@link android.net.NetworkInfo} +object.
    • + +
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}: The P2P state has +changed between enabled and disabled. It carries {@link +android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_STATE} with either {@link +android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_DISABLED} or {@link +android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_ENABLED}
    • + +
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}: The list of peer +devices has changed.
    • + +
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}: The details for +this device have changed.
    • +
    + +

    See the {@link android.net.wifi.p2p.WifiP2pManager} documentation for more information. Also +look at the Wi-Fi Direct Demo +sample application.

    + + + + + +

    Bluetooth Health Devices

    + +

    Android now supports Bluetooth Health Profile devices, so you can create applications that use +Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, +blood meters, thermometers, and scales.

    + +

    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#HEALTH} profile type to establish a connection with the profile +proxy object.

    + +

    Once you’ve acquired the Health Profile proxy (the {@link android.bluetooth.BluetoothHealth} +object), connecting to and communicating with paired health devices involves the following new +Bluetooth classes:

    +
      +
    • {@link android.bluetooth.BluetoothHealthCallback}: 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.
    • +
    • {@link android.bluetooth.BluetoothHealthAppConfiguration}: During callbacks to your {@link +android.bluetooth.BluetoothHealthCallback}, you’ll receive an instance of this object, which +provides configuration information about the available Bluetooth health device, which you must use +to perform various operations such as initiate and terminate connections with the {@link +android.bluetooth.BluetoothHealth} APIs.
    • +
    + +

    For more information about using the Bluetooth Health Profile, see the documentation for {@link +android.bluetooth.BluetoothHealth}.

    + + + + + +

    Accessibility

    + +

    Android 4.0 improves accessibility for sight-impaired users with new explore-by-touch mode +and extended APIs that allow you to provide more information about view content or +develop advanced accessibility services.

    + + +

    Explore-by-touch mode

    + +

    Users with vision loss can now explore the screen by touching and dragging a finger across the +screen to hear voice descriptions of the content. Because the explore-by-touch mode works like a +virtual cursor, it allows screen readers to identify the descriptive text the same way that screen +readers can when the user navigates with a d-pad or trackball—by reading information provided +by {@link android.R.attr#contentDescription android:contentDescription} and {@link +android.view.View#setContentDescription setContentDescription()} upon a simulated "hover" event. So, +consider this is a reminder that you should provide descriptive text for the views in your +application, especially for {@link android.widget.ImageButton}, {@link android.widget.EditText}, +{@link android.widget.ImageView} and other widgets that might not naturally contain descriptive +text.

    + + +

    Accessibility for views

    + +

    To enhance the information available to accessibility services such as screen readers, you can +implement new callback methods for accessibility events in your custom {@link +android.view.View} components.

    + +

    It's important to first note that the behavior of the {@link +android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} method has changed in Android +4.0. As with previous version of Android, when the user enables accessibility services on the device +and an input event such as a click or hover occurs, the respective view is notified with a call to +{@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()}. Previously, the +implementation of {@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} would +initialize an {@link android.view.accessibility.AccessibilityEvent} and send it to {@link +android.view.accessibility.AccessibilityManager}. The new behavior involves some additional callback +methods that allow the view and its parents to add more contextual information to the event: +

      +
    1. When invoked, the {@link +android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} and {@link +android.view.View#sendAccessibilityEventUnchecked sendAccessibilityEventUnchecked()} methods defer +to {@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()}. +

      Custom implementations of {@link android.view.View} might want to implement {@link +android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} to +attach additional accessibility information to the {@link +android.view.accessibility.AccessibilityEvent}, but should also call the super implementation to +provide default information such as the standard content description, item index, and more. +However, you should not add additional text content in this callback—that happens +next.

    2. +
    3. Once initialized, if the event is one of several types that should be populated with text +information, the view then receives a call to {@link +android.view.View#dispatchPopulateAccessibilityEvent dispatchPopulateAccessibilityEvent()}, which +defers to the {@link android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} +callback. +

      Custom implementations of {@link android.view.View} should usually implement {@link +android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} to add additional +text content to the {@link android.view.accessibility.AccessibilityEvent} if the {@link +android.R.attr#contentDescription android:contentDescription} text is missing or +insufficient. To add more text description to the +{@link android.view.accessibility.AccessibilityEvent}, call {@link +android.view.accessibility.AccessibilityEvent#getText()}.{@link java.util.List#add add()}.

      +
    4. +
    5. At this point, the {@link android.view.View} passes the event up the view hierarchy by calling +{@link android.view.ViewGroup#requestSendAccessibilityEvent requestSendAccessibilityEvent()} on the +parent view. Each parent view then has the chance to augment the accessibility information by +adding an {@link android.view.accessibility.AccessibilityRecord}, until it +ultimately reaches the root view, which sends the event to the {@link +android.view.accessibility.AccessibilityManager} with {@link +android.view.accessibility.AccessibilityManager#sendAccessibilityEvent +sendAccessibilityEvent()}.
    6. +
    + +

    In addition to the new methods above, which are useful when extending the {@link +android.view.View} class, you can also intercept these event callbacks on any {@link +android.view.View} by extending {@link +android.view.View.AccessibilityDelegate AccessibilityDelegate} and setting it on the view with +{@link android.view.View#setAccessibilityDelegate setAccessibilityDelegate()}. +When you do, each accessibility method in the view defers the call to the corresponding method in +the delegate. For example, when the view receives a call to {@link +android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()}, it passes it to the +same method in the {@link android.view.View.AccessibilityDelegate}. Any methods not handled by +the delegate are given right back to the view for default behavior. This allows you to override only +the methods necessary for any given view without extending the {@link android.view.View} class.

    + + +

    If you want to maintain compatibility with Android versions prior to 4.0, while also supporting +the new the accessibility APIs, you can do so with the latest version of the v4 support +library (in Compatibility Package, r4) +using a set of utility classes that provide the new accessibility APIs in a backward-compatible +design.

    + + + + +

    Accessibility services

    + +

    If you're developing an accessibility service, the information about various accessibility events +has been significantly expanded to enable more advanced accessibility feedback for users. In +particular, events are generated based on view composition, providing better context information and +allowing accessibility services to traverse view hierarchies to get additional view information and +deal with special cases.

    + +

    If you're developing an accessibility service (such as a screen reader), you can access +additional content information and traverse view hierarchies with the following procedure:

    +
      +
    1. Upon receiving an {@link android.view.accessibility.AccessibilityEvent} from an application, +call the {@link android.view.accessibility.AccessibilityEvent#getRecord(int) +AccessibilityEvent.getRecord()} to retrieve a specific {@link +android.view.accessibility.AccessibilityRecord} (there may be several records attached to the +event).
    2. + +
    3. From either {@link android.view.accessibility.AccessibilityEvent} or an individual {@link +android.view.accessibility.AccessibilityRecord}, you can call {@link +android.view.accessibility.AccessibilityRecord#getSource() getSource()} to retrieve a {@link +android.view.accessibility.AccessibilityNodeInfo} object. +

      An {@link android.view.accessibility.AccessibilityNodeInfo} represents a single node +of the window content in a format that allows you to query accessibility information about that +node. The {@link android.view.accessibility.AccessibilityNodeInfo} object returned from {@link +android.view.accessibility.AccessibilityEvent} describes the event source, whereas the source from +an {@link android.view.accessibility.AccessibilityRecord} describes the predecessor of the event +source.

    4. + +
    5. With the {@link android.view.accessibility.AccessibilityNodeInfo}, you can query information +about it, call {@link +android.view.accessibility.AccessibilityNodeInfo#getParent getParent()} or {@link +android.view.accessibility.AccessibilityNodeInfo#getChild getChild()} to traverse the view +hierarchy, and even add child views to the node.
    6. +
    + +

    In order for your application to publish itself to the system as an accessibility service, it +must declare an XML configuration file that corresponds to {@link +android.accessibilityservice.AccessibilityServiceInfo}. For more information about creating an +accessibility service, see {@link +android.accessibilityservice.AccessibilityService} and {@link +android.accessibilityservice.AccessibilityService#SERVICE_META_DATA +SERVICE_META_DATA} for information about the XML configuration.

    + + +

    Other accessibility APIs

    + +

    If you're interested in the device's accessibility state, the {@link +android.view.accessibility.AccessibilityManager} has some new APIs such as:

    +
      +
    • {@link android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener} +is an interface that allows you to receive a callback whenever accessibility is enabled or +disabled.
    • +
    • {@link android.view.accessibility.AccessibilityManager#getEnabledAccessibilityServiceList + getEnabledAccessibilityServiceList()} provides information about which accessibility services + are currently enabled.
    • +
    • {@link android.view.accessibility.AccessibilityManager#isTouchExplorationEnabled()} tells + you whether the explore-by-touch mode is enabled.
    • +
    + + + + + + +

    Spell Checker Services

    + +

    A new spell checker framework allows apps to create spell checkers in a manner similar to the +input method framework (for IMEs). To create a new spell checker, you must implement a service that +extends +{@link android.service.textservice.SpellCheckerService} and extend the {@link +android.service.textservice.SpellCheckerService.Session} class to provide spelling suggestions based +on text provided by the interface's callback methods. In the {@link +android.service.textservice.SpellCheckerService.Session} callback methods, you must return the +spelling suggestions as {@link android.view.textservice.SuggestionsInfo} objects.

    + +

    Applications with a spell checker service must declare the {@link +android.Manifest.permission#BIND_TEXT_SERVICE} permission as required by the service. +The service must also declare an intent filter with {@code <action +android:name="android.service.textservice.SpellCheckerService" />} as the intent’s action and should +include a {@code <meta-data>} element that declares configuration information for the spell +checker.

    + +

    See the sample +Spell Checker Service app and +sample +Spell Checker Client app for example code.

    + + + + +

    Text-to-speech Engines

    + +

    Android’s text-to-speech (TTS) APIs have been significantly extended to allow applications to +more easily implement custom TTS engines, while applications that want to use a TTS engine have a +couple new APIs for selecting an engine.

    + + +

    Using text-to-speech engines

    + +

    In previous versions of Android, you could use the {@link android.speech.tts.TextToSpeech} class +to perform text-to-speech (TTS) operations using the TTS engine provided by the system or set a +custom engine using {@link android.speech.tts.TextToSpeech#setEngineByPackageName +setEngineByPackageName()}. In Android 4.0, the {@link +android.speech.tts.TextToSpeech#setEngineByPackageName setEngineByPackageName()} method has been +deprecated and you can now specify the engine to use with a new {@link +android.speech.tts.TextToSpeech} constructor that accepts the package name of a TTS engine.

    + +

    You can also query the available TTS engines with {@link +android.speech.tts.TextToSpeech#getEngines()}. This method returns a list of {@link +android.speech.tts.TextToSpeech.EngineInfo} objects, which include meta data such as the engine’s +icon, label, and package name.

    + + +

    Building text-to-speech engines

    + +

    Previously, custom engines required that the engine be built using an undocumented native header +file. In Android 4.0, there is a complete set of framework APIs for building TTS engines.

    + +

    The basic setup requires an implementation of {@link android.speech.tts.TextToSpeechService} that +responds to the {@link android.speech.tts.TextToSpeech.Engine#INTENT_ACTION_TTS_SERVICE} intent. The +primary work for a TTS engine happens during the {@link +android.speech.tts.TextToSpeechService#onSynthesizeText onSynthesizeText()} callback in a service +that extends {@link android.speech.tts.TextToSpeechService}. The system delivers this method two +objects:

    +
      +
    • {@link android.speech.tts.SynthesisRequest}: This contains various data including the text to +synthesize, the locale, the speech rate, and voice pitch.
    • +
    • {@link android.speech.tts.SynthesisCallback}: This is the interface by which your TTS engine +delivers the resulting speech data as streaming audio. First the engine must call {@link +android.speech.tts.SynthesisCallback#start start()} to indicate that the engine is ready to deliver +the audio, then call {@link android.speech.tts.SynthesisCallback#audioAvailable audioAvailable()}, +passing it the audio data in a byte buffer. Once your engine has passed all audio through the +buffer, call {@link android.speech.tts.SynthesisCallback#done()}.
    • +
    + +

    Now that the framework supports a true API for creating TTS engines, support for the native code +implementation has been removed. Look for a blog post about a compatibility layer +that you can use to convert your old TTS engines to the new framework.

    + +

    For an example TTS engine using the new APIs, see the Text To Speech Engine sample app.

    + + + + + + +

    Network Usage

    + +

    Android 4.0 gives users precise visibility of how much network data their applications are using. +The Settings app provides controls that allow users to manage set limits for network data usage and +even disable the use of background data for individual apps. In order to avoid users disabling your +app’s access to data from the background, you should develop strategies to use the data +connection efficiently and adjust your usage depending on the type of connection available.

    + +

    If your application performs a lot of network transactions, you should provide user settings that +allow users to control your app’s data habits, such as how often your app syncs data, whether to +perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, etc. With these +controls available to them, users are much less likely to disable your app’s access to data when +they approach their limits, because they can instead precisely control how much data your app uses. +If you provide a preference activity with these settings, you should include in its manifest +declaration an intent filter for the {@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} +action. For example:

    + +
    +<activity android:name="DataPreferences" android:label="@string/title_preferences">
    +    <intent-filter>
    +       <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
    +       <category android:name="android.intent.category.DEFAULT" />
    +    </intent-filter>
    +</activity>
    +
    + +

    This intent filter indicates to the system that this is the activity that controls your +application’s data usage. Thus, when the user inspects how much data your app is using from the +Settings app, a “View application settings" button is available that launches your +preference activity so the user can refine how much data your app uses.

    + +

    Also beware that {@link android.net.ConnectivityManager#getBackgroundDataSetting()} is now +deprecated and always returns true—use {@link +android.net.ConnectivityManager#getActiveNetworkInfo()} instead. Before you attempt any network +transactions, you should always call {@link android.net.ConnectivityManager#getActiveNetworkInfo()} +to get the {@link android.net.NetworkInfo} that represents the current network and query {@link +android.net.NetworkInfo#isConnected()} to check whether the device has a +connection. You can then check other connection properties, such as whether the device is +roaming or connected to Wi-Fi.

    + + + + + + + + +

    RenderScript

    + +

    Three major features have been added to RenderScript:

    + +
      +
    • Off-screen rendering to a framebuffer object
    • +
    • Rendering inside a view
    • +
    • RS for each from the framework APIs
    • +
    + +

    The {@link android.renderscript.Allocation} class now supports a {@link +android.renderscript.Allocation#USAGE_GRAPHICS_RENDER_TARGET} memory space, which allows you to +render things directly into the {@link android.renderscript.Allocation} and use it as a framebuffer +object.

    + +

    {@link android.renderscript.RSTextureView} provides a means to display RenderScript graphics +inside of a {@link android.view.View}, unlike {@link android.renderscript.RSSurfaceView}, which +creates a separate window. This key difference allows you to do things such as move, transform, or +animate an {@link android.renderscript.RSTextureView} as well as draw RenderScript graphics inside +a view that lies within an activity layout.

    + +

    The {@link android.renderscript.Script#forEach Script.forEach()} method allows you to call +RenderScript compute scripts from the VM level and have them automatically delegated to available +cores on the device. You do not use this method directly, but any compute RenderScript that you +write will have a {@link android.renderscript.Script#forEach forEach()} method that you can call in +the reflected RenderScript class. You can call the reflected {@link +android.renderscript.Script#forEach forEach()} method by passing in an input {@link +android.renderscript.Allocation} to process, an output {@link android.renderscript.Allocation} to +write the result to, and a {@link android.renderscript.FieldPacker} data structure in case the +RenderScript needs more information. Only one of the {@link android.renderscript.Allocation}s is +necessary and the data structure is optional.

    + + + + + + + + + +

    Enterprise

    + +

    Android 4.0 expands the capabilities for enterprise application with the following features.

    + +

    VPN services

    + +

    The new {@link android.net.VpnService} allows applications to build their own VPN (Virtual +Private Network), running as a {@link android.app.Service}. A VPN service creates an interface for a +virtual network with its own address and routing rules and performs all reading and writing with a +file descriptor.

    + +

    To create a VPN service, use {@link android.net.VpnService.Builder}, which allows you to specify +the network address, DNS server, network route, and more. When complete, you can establish the +interface by calling {@link android.net.VpnService.Builder#establish()}, which returns a {@link +android.os.ParcelFileDescriptor}.

    + +

    Because a VPN service can intercept packets, there are security implications. As such, if you +implement {@link android.net.VpnService}, then your service must require the {@link +android.Manifest.permission#BIND_VPN_SERVICE} to ensure that only the system can bind to it (only +the system is granted this permission—apps cannot request it). To then use your VPN service, +users must manually enable it in the system settings.

    + + +

    Device policies

    + +

    Applications that manage the device restrictions can now disable the camera using {@link +android.app.admin.DevicePolicyManager#setCameraDisabled setCameraDisabled()} and the {@link +android.app.admin.DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} property (applied with a {@code +<disable-camera />} element in the policy configuration file).

    + + +

    Certificate management

    + +

    The new {@link android.security.KeyChain} class provides APIs that allow you to import and access +certificates in the system key store. Certificates streamline the installation of both client +certificates (to validate the identity of the user) and certificate authority certificates (to +verify server identity). Applications such as web browsers or email clients can access the installed +certificates to authenticate users to servers. See the {@link android.security.KeyChain} +documentation for more information.

    + + + + + + + +

    Device Sensors

    + +

    Two new sensor types have been added in Android 4.0:

    + +
      +
    • {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE}: A temperature sensor that provides +the ambient (room) temperature in degrees Celsius.
    • +
    • {@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY}: A humidity sensor that provides the +relative ambient (room) humidity as a percentage.
    • +
    + +

    If a device has both {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} and {@link +android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY} sensors, you can use them to calculate the dew point +and the absolute humidity.

    + +

    The previous temperature sensor, {@link android.hardware.Sensor#TYPE_TEMPERATURE}, has been +deprecated. You should use the {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} sensor +instead.

    + +

    Additionally, Android’s three synthetic sensors have been greatly improved so they now have lower +latency and smoother output. These sensors include the gravity sensor ({@link +android.hardware.Sensor#TYPE_GRAVITY}), rotation vector sensor ({@link +android.hardware.Sensor#TYPE_ROTATION_VECTOR}), and linear acceleration sensor ({@link +android.hardware.Sensor#TYPE_LINEAR_ACCELERATION}). The improved sensors rely on the gyroscope +sensor to improve their output, so the sensors appear only on devices that have a gyroscope.

    + + + + + +

    Action Bar

    + +

    The {@link android.app.ActionBar} has been updated to support several new behaviors. Most +importantly, the system gracefully manages the action bar’s size and configuration when running on +smaller screens in order to provide an optimal user experience on all screen sizes. For example, +when the screen is narrow (such as when a handset is in portrait orientation), the action bar’s +navigation tabs appear in a “stacked bar," which appears directly below the main action bar. You can +also opt-in to a “split action bar," which places all action items in a separate bar at the bottom +of the screen when the screen is narrow.

    + + +

    Split action bar

    + +

    If your action bar includes several action items, not all of them will fit into the action bar on +a narrow screen, so the system will place more of them into the overflow menu. However, Android 4.0 +allows you to enable “split action bar" so that more action items can appear on the screen in a +separate bar at the bottom of the screen. To enable split action bar, add {@link +android.R.attr#uiOptions android:uiOptions} with {@code "splitActionBarWhenNarrow"} to either your +{@code <application>} +tag or +individual {@code +<activity>} tags +in your manifest file. When enabled, the system will add an additional bar at the bottom of the +screen for all action items when the screen is narrow (no action items will appear in the primary +action bar).

    + +

    If you want to use the navigation tabs provided by the {@link android.app.ActionBar.Tab} APIs, +but don’t need the main action bar on top (you want only the tabs to appear at the top), then enable +the split action bar as described above and also call {@link +android.app.ActionBar#setDisplayShowHomeEnabled setDisplayShowHomeEnabled(false)} to disable the +application icon in the action bar. With nothing left in the main action bar, it +disappears—all that’s left are the navigation tabs at the top and the action items at the +bottom of the screen.

    + + +

    Action bar styles

    + +

    If you want to apply custom styling to the action bar, you can use new style properties {@link +android.R.attr#backgroundStacked} and {@link android.R.attr#backgroundSplit} to apply a background +drawable or color to the stacked bar and split bar, respectively. You can also set these styles at +runtime with {@link android.app.ActionBar#setStackedBackgroundDrawable +setStackedBackgroundDrawable()} and {@link android.app.ActionBar#setSplitBackgroundDrawable +setSplitBackgroundDrawable()}.

    + + +

    Action provider

    + +

    The new {@link android.view.ActionProvider} class allows you to create a specialized handler for +action items. An action provider can define an action view, a default action behavior, and a submenu +for each action item to which it is associated. When you want to create an action item that has +dynamic behaviors (such as a variable action view, default action, or submenu), extending {@link +android.view.ActionProvider} is a good solution in order to create a reusable component, rather than +handling the various action item transformations in your fragment or activity.

    + +

    For example, the {@link android.widget.ShareActionProvider} is an extension of {@link +android.view.ActionProvider} that facilitates a “share" action from the action bar. Instead of using +traditional action item that invokes the {@link android.content.Intent#ACTION_SEND} intent, you can +use this action provider to present an action view with a drop-down list of applications that handle +the {@link android.content.Intent#ACTION_SEND} intent. When the user selects an application to use +for the action, {@link android.widget.ShareActionProvider} remembers that selection and provides it +in the action view for faster access to sharing with that app.

    + +

    To declare an action provider for an action item, include the {@code android:actionProviderClass} +attribute in the {@code +<item>} element for your activity’s options menu, with the class name of the action +provider as the value. For example:

    + +
    +<item android:id="@+id/menu_share"
    +      android:title="Share"
    +      android:showAsAction="ifRoom"
    +      android:actionProviderClass="android.widget.ShareActionProvider" />
    +
    + +

    In your activity’s {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} +callback method, retrieve an instance of the action provider from the menu item and set the +intent:

    + +
    +public boolean onCreateOptionsMenu(Menu menu) {
    +    getMenuInflater().inflate(R.menu.options, menu);
    +    ShareActionProvider shareActionProvider =
    +          (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider();
    +    // Set the share intent of the share action provider.
    +    shareActionProvider.setShareIntent(createShareIntent());
    +    ...
    +    return super.onCreateOptionsMenu(menu);
    +}
    +
    + +

    For an example using the {@link android.widget.ShareActionProvider}, see ActionBarShareActionProviderActivity in ApiDemos.

    + + +

    Collapsible action views

    + +

    Action items that provide an action view can now toggle between their action view state and +traditional action item state. Previously only the {@link android.widget.SearchView} supported +collapsing when used as an action view, but now you can add an action view for any action item and +switch between the expanded state (action view is visible) and collapsed state (action item is +visible).

    + +

    To declare that an action item that contains an action view be collapsible, include the {@code +“collapseActionView"} flag in the {@code android:showAsAction} attribute for the {@code +<item>} element in the menu’s XML file.

    + +

    To receive callbacks when an action view switches between expanded and collapsed, register an +instance of {@link android.view.MenuItem.OnActionExpandListener} with the respective {@link +android.view.MenuItem} by calling {@link android.view.MenuItem#setOnActionExpandListener +setOnActionExpandListener()}. Typically, you should do so during the {@link +android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback.

    + +

    To control a collapsible action view, you can call {@link +android.view.MenuItem#collapseActionView()} and {@link android.view.MenuItem#expandActionView()} on +the respective {@link android.view.MenuItem}.

    + +

    When creating a custom action view, you can also implement the new {@link +android.view.CollapsibleActionView} interface to receive callbacks when the view is expanded and +collapsed.

    + + +

    Other APIs for action bar

    +
      +
    • {@link android.app.ActionBar#setHomeButtonEnabled setHomeButtonEnabled()} allows you to specify +whether the icon/logo behaves as a button to navigate home or “up" (pass “true" to make it behave as +a button).
    • + +
    • {@link android.app.ActionBar#setIcon setIcon()} and {@link android.app.ActionBar#setLogo +setLogo()} allow you to define the action bar icon or logo at runtime.
    • + +
    • {@link android.app.Fragment#setMenuVisibility Fragment.setMenuVisibility()} allows you to enable +or disable the visibility of the options menu items declared by the fragment. This is useful if the +fragment has been added to the activity, but is not visible, so the menu items should be +hidden.
    • + +
    • {@link android.app.FragmentManager#invalidateOptionsMenu +FragmentManager.invalidateOptionsMenu()} +allows you to invalidate the activity options menu during various states of the fragment lifecycle +in which using the equivalent method from {@link android.app.Activity} might not be available.
    • +
    + + + + + + + + +

    User Interface and Views

    + +

    Android 4.0 introduces a variety of new views and other UI components.

    + + +

    GridLayout

    + +

    {@link android.widget.GridLayout} is a new view group that places child views in a rectangular +grid. Unlike {@link android.widget.TableLayout}, {@link android.widget.GridLayout} relies on a flat +hierarchy and does not make use of intermediate views such as table rows for providing structure. +Instead, children specify which row(s) and column(s) they should occupy (cells can span multiple +rows and/or columns), and by default are laid out sequentially across the grid’s rows and columns. +The {@link android.widget.GridLayout} orientation determines whether sequential children are by +default laid out horizontally or vertically. Space between children may be specified either by using +instances of the new {@link android.widget.Space} view or by setting the relevant margin parameters +on children.

    + +

    See ApiDemos +for samples using {@link android.widget.GridLayout}.

    + + + +

    TextureView

    + +

    {@link android.view.TextureView} is a new view that allows you to display a content stream, such +as a video or an OpenGL scene. Although similar to {@link android.view.SurfaceView}, {@link +android.view.TextureView} is unique in that it behaves like a regular view, rather than creating a +separate window, so you can treat it like any other {@link android.view.View} object. For example, +you can apply transforms, animate it using {@link android.view.ViewPropertyAnimator}, or +adjust its opacity with {@link android.view.View#setAlpha setAlpha()}.

    + +

    Beware that {@link android.view.TextureView} works only within a hardware accelerated window.

    + +

    For more information, see the {@link android.view.TextureView} documentation.

    + + +

    Switch widget

    + +

    The new {@link android.widget.Switch} widget is a two-state toggle that users can drag to one +side or the other (or simply tap) to toggle an option between two states.

    + +

    You can use the {@code android:textOn} and {@code android:textOff} attributes to specify the text +to appear on the switch when in the on and off setting. The {@code android:text} attribute also +allows you to place a label alongside the switch.

    + +

    For a sample using switches, see the switches.xml layout file +and respective Switches + activity.

    + + +

    Popup menus

    + +

    Android 3.0 introduced {@link android.widget.PopupMenu} to create short contextual menus that pop +up at an anchor point you specify (usually at the point of the item selected). Android 4.0 extends +the {@link android.widget.PopupMenu} with a couple useful features:

    +
      +
    • You can now easily inflate the contents of a popup menu from an XML menu resource with {@link +android.widget.PopupMenu#inflate inflate()}, passing it the menu resource ID.
    • +
    • You can also now create a {@link android.widget.PopupMenu.OnDismissListener} that receives a +callback when the menu is dismissed.
    • +
    + + +

    Preferences

    + +

    A new {@link android.preference.TwoStatePreference} abstract class serves as the basis for +preferences that provide a two-state selection option. The new {@link +android.preference.SwitchPreference} is an extension of {@link +android.preference.TwoStatePreference} that provides a {@link android.widget.Switch} widget in the +preference view to allow users to toggle a setting on or off without the need to open an additional +preference screen or dialog. For example, the Settings application uses a {@link +android.preference.SwitchPreference} for the Wi-Fi and Bluetooth settings.

    + + + +

    System themes

    + +

    The default theme for all applications that target Android 4.0 (by setting either {@code targetSdkVersion} or +{@code minSdkVersion} to +{@code “14"} or higher) is now the +"device default" theme: {@link android.R.style#Theme_DeviceDefault Theme.DeviceDefault}. This may be +the dark Holo theme or a different dark theme defined by the specific device.

    + +

    The {@link android.R.style#Theme_Holo Theme.Holo} family of themes are guaranteed to not change +from one device to another when running the same version of Android. If you explicitly +apply any of the {@link android.R.style#Theme_Holo Theme.Holo} themes to your activities, you can +rest assured that these themes will not change character on different devices within the same +platform version.

    + +

    If you wish for your app to blend in with the overall device theme (such as when different OEMs +provide different default themes for the system), you should explicitly apply themes from the {@link +android.R.style#Theme_DeviceDefault Theme.DeviceDefault} family.

    + + +

    Options menu button

    + +

    Beginning with Android 4.0, you'll notice that handsets no longer require a Menu hardware button. +However, there's no need for you to worry about this if your existing application provides an options menu and expects there to be a +Menu button. To ensure that existing apps continue to work as they expect, the system provides an +on-screen Menu button for apps that were designed for older versions of Android.

    + +

    For the best user experience, new and updated apps should instead use the {@link +android.app.ActionBar} to provide access to menu items and set {@code targetSdkVersion} to +{@code "14"} to take advantage of the latest framework default behaviors.

    + + + +

    Controls for system UI visibility

    + +

    Since the early days of Android, the system has managed a UI component known as the status +bar, which resides at the top of handset devices to deliver information such as the carrier +signal, time, notifications, and so on. Android 3.0 added the system bar for tablet +devices, which resides at the bottom of the screen to provide system navigation controls (Home, +Back, and so forth) and also an interface for elements traditionally provided by the status bar. In +Android 4.0, the system provides a new type of system UI called the navigation bar. You +might consider the navigation bar a re-tuned version of the system bar designed for +handsets—it provides navigation controls +for devices that don’t have hardware counterparts for navigating the system, but it leaves out the +system bar's notification UI and setting controls. As such, a device that provides the navigation +bar also has the status bar at the top.

    + +

    To this day, you can hide the status bar on handsets using the {@link +android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN} flag. In Android 4.0, the APIs that control +the system bar’s visibility have been updated to better reflect the behavior of both the system bar +and navigation bar:

    +
      +
    • The {@link android.view.View#SYSTEM_UI_FLAG_LOW_PROFILE} flag replaces the {@code +STATUS_BAR_HIDDEN} flag. When set, this flag enables “low profile" mode for the system bar or +navigation bar. Navigation buttons dim and other elements in the system bar also hide. Enabling +this is useful for creating more immersive games without distraction for the system navigation +buttons.
    • + +
    • The {@link android.view.View#SYSTEM_UI_FLAG_VISIBLE} flag replaces the {@code +STATUS_BAR_VISIBLE} flag to request the system bar or navigation bar be visible.
    • + +
    • The {@link android.view.View#SYSTEM_UI_FLAG_HIDE_NAVIGATION} is a new flag that requests +the navigation bar hide completely. Be aware that this works only for the navigation bar +used by some handsets (it does not hide the system bar on tablets). The navigation +bar returns to view as soon as the system receives user input. As such, this mode is useful +primarily for video playback or other cases in which the whole screen is needed but user input is +not required.
    • +
    + +

    You can set each of these flags for the system bar and navigation bar by calling {@link +android.view.View#setSystemUiVisibility setSystemUiVisibility()} on any view in your activity. The +window manager combines (OR-together) all flags from all views in your window and +apply them to the system UI as long as your window has input focus. When your window loses input +focus (the user navigates away from your app, or a dialog appears), your flags cease to have effect. +Similarly, if you remove those views from the view hierarchy their flags no longer apply.

    + +

    To synchronize other events in your activity with visibility changes to the system UI (for +example, hide the action bar or other UI controls when the system UI hides), you should register a +{@link android.view.View.OnSystemUiVisibilityChangeListener} to be notified when the visibility +of the system bar or navigation bar changes.

    + +

    See the +OverscanActivity class for a demonstration of different system UI options.

    + + + + + +

    Input Framework

    + +

    Android 4.0 adds support for cursor hover events and new stylus and mouse button events.

    + +

    Hover events

    + +

    The {@link android.view.View} class now supports “hover" events to enable richer interactions +through the use of pointer devices (such as a mouse or other devices that drive an on-screen +cursor).

    + +

    To receive hover events on a view, implement the {@link android.view.View.OnHoverListener} and +register it with {@link android.view.View#setOnHoverListener setOnHoverListener()}. When a hover +event occurs on the view, your listener receives a call to {@link +android.view.View.OnHoverListener#onHover onHover()}, providing the {@link android.view.View} that +received the event and a {@link android.view.MotionEvent} that describes the type of hover event +that occurred. The hover event can be one of the following:

    +
      +
    • {@link android.view.MotionEvent#ACTION_HOVER_ENTER}
    • +
    • {@link android.view.MotionEvent#ACTION_HOVER_EXIT}
    • +
    • {@link android.view.MotionEvent#ACTION_HOVER_MOVE}
    • +
    + +

    Your {@link android.view.View.OnHoverListener} should return true from {@link +android.view.View.OnHoverListener#onHover onHover()} if it handles the hover event. If your +listener returns false, then the hover event will be dispatched to the parent view as usual.

    + +

    If your application uses buttons or other widgets that change their appearance based on the +current state, you can now use the {@code android:state_hovered} attribute in a state list drawable to +provide a different background drawable when a cursor hovers over the view.

    + +

    For a demonstration of the new hover events, see the Hover class in +ApiDemos.

    + + +

    Stylus and mouse button events

    + +

    Android now provides APIs for receiving input from a stylus input device such as a digitizer +tablet peripheral or a stylus-enabled touch screen.

    + +

    Stylus input operates in a similar manner to touch or mouse input. When the stylus is in contact +with the digitizer, applications receive touch events just like they would when a finger is used to +touch the display. When the stylus is hovering above the digitizer, applications receive hover +events just like they would when a mouse pointer was being moved across the display when no buttons +are pressed.

    + +

    Your application can distinguish between finger, mouse, stylus and eraser input by querying the +“tool type" associated with each pointer in a {@link android.view.MotionEvent} using {@link +android.view.MotionEvent#getToolType getToolType()}. The currently defined tool types are: {@link +android.view.MotionEvent#TOOL_TYPE_UNKNOWN}, {@link android.view.MotionEvent#TOOL_TYPE_FINGER}, +{@link android.view.MotionEvent#TOOL_TYPE_MOUSE}, {@link android.view.MotionEvent#TOOL_TYPE_STYLUS}, +and {@link android.view.MotionEvent#TOOL_TYPE_ERASER}. By querying the tool type, your application +can choose to handle stylus input in different ways from finger or mouse input.

    + +

    Your application can also query which mouse or stylus buttons are pressed by querying the “button +state" of a {@link android.view.MotionEvent} using {@link android.view.MotionEvent#getButtonState +getButtonState()}. The currently defined button states are: {@link +android.view.MotionEvent#BUTTON_PRIMARY}, {@link android.view.MotionEvent#BUTTON_SECONDARY}, {@link +android.view.MotionEvent#BUTTON_TERTIARY}, {@link android.view.MotionEvent#BUTTON_BACK}, and {@link +android.view.MotionEvent#BUTTON_FORWARD}. For convenience, the back and forward mouse buttons are +automatically mapped to the {@link android.view.KeyEvent#KEYCODE_BACK} and {@link +android.view.KeyEvent#KEYCODE_FORWARD} keys. Your application can handle these keys to support +mouse button based back and forward navigation.

    + +

    In addition to precisely measuring the position and pressure of a contact, some stylus input +devices also report the distance between the stylus tip and the digitizer, the stylus tilt angle, +and the stylus orientation angle. Your application can query this information using {@link +android.view.MotionEvent#getAxisValue getAxisValue()} with the axis codes {@link +android.view.MotionEvent#AXIS_DISTANCE}, {@link android.view.MotionEvent#AXIS_TILT}, and {@link +android.view.MotionEvent#AXIS_ORIENTATION}.

    + +

    For a demonstration of tool types, button states and the new axis codes, see the TouchPaint + class in ApiDemos.

    + + + + + + +

    Properties

    + +

    The new {@link android.util.Property} class provides a fast, efficient, and easy way to specify a +property on any object that allows callers to generically set/get values on target objects. It also +allows the functionality of passing around field/method references and allows code to set/get values +of the property without knowing the details of what the fields/methods are.

    + +

    For example, if you want to set the value of field {@code bar} on object {@code foo}, you would +previously do this:

    +
    +foo.bar = value;
    +
    + +

    If you want to call the setter for an underlying private field {@code bar}, you would previously +do this:

    +
    +foo.setBar(value);
    +
    + +

    However, if you want to pass around the {@code foo} instance and have some other code set the +{@code bar} value, there is really no way to do it prior to Android 4.0.

    + +

    Using the {@link android.util.Property} class, you can declare a {@link android.util.Property} +object {@code BAR} on class {@code Foo} so that you can set the field on instance {@code foo} of +class {@code Foo} like this:

    +
    +BAR.set(foo, value);
    +
    + +

    The {@link android.view.View} class now leverages the {@link android.util.Property} class to +allow you to set various fields, such as transform properties that were added in Android 3.0 ({@link +android.view.View#ROTATION}, {@link android.view.View#ROTATION_X}, {@link +android.view.View#TRANSLATION_X}, etc.).

    + +

    The {@link android.animation.ObjectAnimator} class also uses the {@link android.util.Property} +class, so you can create an {@link android.animation.ObjectAnimator} with a {@link +android.util.Property}, which is faster, more efficient, and more type-safe than the string-based +approach.

    + + + + + + +

    Hardware Acceleration

    + +

    Beginning with Android 4.0, hardware acceleration for all windows is enabled by default if your +application has set either {@code targetSdkVersion} or +{@code minSdkVersion} to +{@code “14"} or higher. Hardware acceleration generally results in smoother animations, smoother +scrolling, and overall better performance and response to user interaction.

    + +

    If necessary, you can manually disable hardware acceleration with the {@code hardwareAccelerated} +attribute for individual {@code +<activity>} elements or the {@code <application>} +element. You can alternatively disable hardware acceleration for individual views by calling {@link +android.view.View#setLayerType setLayerType(LAYER_TYPE_SOFTWARE)}.

    + +

    For more information about hardware acceleration, including a list of unsupported drawing +operations, see the Hardware +Acceleration document.

    + + + +

    JNI Changes

    + +

    In previous versions of Android, JNI local references weren’t indirect handles; Android used +direct pointers. This wasn't a problem as long as the garbage collector didn't move objects, but it +seemed to work because it made it possible to write buggy code. In Android 4.0, the system now uses +indirect references in order to detect these bugs.

    + +

    The ins and outs of JNI local references are described in “Local and Global References" in JNI Tips. In Android 4.0, +CheckJNI has been enhanced to detect these errors. Watch the Android Developers Blog for an upcoming post +about common errors with JNI references and how you can fix them.

    + +

    This change in the JNI implementation only affects apps that target Android 4.0 by setting either +the {@code +targetSdkVersion} or {@code +minSdkVersion} to {@code “14"} or higher. If you’ve set these attributes to any lower value, +then JNI local references behave the same as in previous versions.

    + + + + + +

    WebKit

    +
      +
    • WebKit updated to version 534.30
    • +
    • Support for Indic fonts (Devanagari, Bengali, and Tamil, including the complex character support +needed for combining glyphs) in {@link android.webkit.WebView} and the built-in Browser
    • +
    • Support for Ethiopic, Georgian, and Armenian fonts in {@link android.webkit.WebView} and the +built-in Browser
    • +
    • Support for WebDriver makes +it easier for you to test apps that use {@link android.webkit.WebView}
    • +
    + + +

    Android Browser

    + +

    The Browser application adds the following features to support web applications:

    + + + + +

    Permissions

    + +

    The following are new permissions:

    +
      +
    • {@link android.Manifest.permission#ADD_VOICEMAIL}: Allows a voicemail service to add voicemail +messages to the device.
    • +
    • {@link android.Manifest.permission#BIND_TEXT_SERVICE}: A service that implements {@link +android.service.textservice.SpellCheckerService} must require this permission for itself.
    • +
    • {@link android.Manifest.permission#BIND_VPN_SERVICE}: A service that implements {@link +android.net.VpnService} must require this permission for itself.
    • +
    • {@link android.Manifest.permission#READ_PROFILE}: Provides read access to the {@link +android.provider.ContactsContract.Profile} provider.
    • +
    • {@link android.Manifest.permission#WRITE_PROFILE}: Provides write access to the {@link +android.provider.ContactsContract.Profile} provider.
    • +
    + + + +

    Device Features

    + +

    The following are new device features:

    +
      +
    • {@link android.content.pm.PackageManager#FEATURE_WIFI_DIRECT}: Declares that the application +uses +Wi-Fi for peer-to-peer communications.
    • +
    + + +
    +

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level +{@sdkPlatformApiLevel}), see the API Differences Report.

    +
    + + +

    Previous APIs

    + +

    In addition to everything above, Android 4.0 naturally supports all APIs from previous releases. +Because the Android 3.x platform is available only for large-screen devices, if you've +been developing primarily for handsets, then you might not be aware of all the APIs added to Android +in these recent releases.

    + +

    Here's a look at some of the most notable APIs you might have missed that are now available +on handsets as well:

    + +
    +
    Android 3.0
    +
    +
      +
    • {@link android.app.Fragment}: A framework component that allows you to separate distinct +elements of an activity into self-contained modules that define their own UI and lifecycle. See the +Fragments developer guide.
    • +
    • {@link android.app.ActionBar}: A replacement for the traditional title bar at the top of +the activity window. It includes the application logo in the left corner and provides a new +interface for menu items. See the +Action Bar developer guide.
    • +
    • {@link android.content.Loader}: A framework component that facilitates asynchronous +loading of data in combination with UI components to dynamically load data without blocking the +main thread. See the +Loaders developer guide.
    • +
    • System clipboard: Applications can copy and paste data (beyond mere text) to and from +the system-wide clipboard. Clipped data can be plain text, a URI, or an intent. See the +Copy and Paste developer guide.
    • +
    • Drag and drop: A set of APIs built into the view framework that facilitates drag and drop +operations. See the +Drag and Drop developer guide.
    • +
    • An all new flexible animation framework allows you to animate arbitrary properties of any +object (View, Drawable, Fragment, Object, or anything else) and define animation aspects such +as duration, interpolation, repeat and more. The new framework makes Animations in Android +simpler than ever. See the +Property Animation developer +guide.
    • +
    • RenderScript graphics and compute engine: RenderScript offers a high performance 3D +graphics rendering and compute API at the native level, which you write in the C (C99 standard), +providing the type of performance you expect from a native environment while remaining portable +across various CPUs and GPUs. See the +RenderScript developer +guide.
    • +
    • Hardware accelerated 2D graphics: You can now enable the OpenGL renderer for your +application by setting {android:hardwareAccelerated="true"} in your manifest element's <application> +element or for individual <activity> +elements. This results +in smoother animations, smoother scrolling, and overall better performance and response to user +interaction. +

      Note: If you set your application's {@code minSdkVersion} or {@code targetSdkVersion} to +{@code "14"} or higher, hardware acceleration is enabled by default.

    • +
    • And much, much more. See the Android 3.0 Platform +notes for more information.
    • +
    +
    + +
    Android 3.1
    +
    +
      +
    • USB APIs: Powerful new APIs for integrating connected peripherals with +Android applications. The APIs are based on a USB stack and services that are +built into the platform, including support for both USB host and device interactions. See the USB Host and Accessory developer guide.
    • +
    • MTP/PTP APIs: Applications can interact directly with connected cameras and other PTP +devices to receive notifications when devices are attached and removed, manage files and storage on +those devices, and transfer files and metadata to and from them. The MTP API implements the PTP +(Picture Transfer Protocol) subset of the MTP (Media Transfer Protocol) specification. See the +{@link android.mtp} documentation.
    • +
    • RTP APIs: Android exposes an API to its built-in RTP (Real-time Transport Protocol) stack, +which applications can use to manage on-demand or interactive data streaming. In particular, apps +that provide VOIP, push-to-talk, conferencing, and audio streaming can use the API to initiate +sessions and transmit or receive data streams over any available network. See the {@link +android.net.rtp} documentation.
    • +
    • Support for joysticks and other generic motion inputs.
    • +
    • See the Android 3.1 Platform +notes for many more new APIs.
    • +
    +
    + +
    Android 3.2
    +
    +
      +
    • New screens support APIs that give you more control over how your applications are +displayed across different screen sizes. The API extends the existing screen support model with the +ability to precisely target specific screen size ranges by dimensions, measured in +density-independent pixel units (such as 600dp or 720dp wide), rather than by their generalized +screen sizes (such as large or xlarge). For example, this is important in order to help you +distinguish between a 5" device and a 7" device, which would both traditionally be bucketed as +"large" screens. See the blog post, +New Tools for Managing Screen Sizes.
    • +
    • New constants for {@code <uses-feature>} to +declare landscape or portrait screen orientation requirements.
    • +
    • The device "screen size" configuration now changes during a screen orientation +change. If your app targets API level 13 or higher, you must handle the {@code "screenSize"} +configuration change if you also want to handle the {@code "orientation"} configuration change. See +{@code +android:configChanges} for more information.
    • +
    • See the Android 3.2 Platform +notes for other new APIs.
    • +
    +
    + +
    + + + + +

    API Level

    + +

    The Android {@sdkPlatformVersion} API is assigned an integer +identifier—{@sdkPlatformApiLevel}—that is stored in the system itself. +This identifier, called the "API level", allows the system to correctly determine whether an +application is compatible with the system, prior to installing the application.

    + +

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the +application against an Android platform that supports API level {@sdkPlatformApiLevel} or +higher. Depending on your needs, you might also need to add an +android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the +{@code <uses-sdk>} +element.

    + +

    For more information, read What is API +Level?

    diff --git a/docs/html/about/versions/api-levels.jd b/docs/html/about/versions/api-levels.jd new file mode 100644 index 000000000000..525e2cb5570a --- /dev/null +++ b/docs/html/about/versions/api-levels.jd @@ -0,0 +1,421 @@ +page.title=Android API Levels +@jd:body + + + +

    As you develop your application on Android, it's useful to understand the +platform's general approach to API change management. It's also important to +understand the API Level identifier and the role it plays in ensuring your +application's compatibility with devices on which it may be installed.

    + +

    The sections below provide information about API Level and how it affects +your applications.

    + +

    For information about how to use the "Filter by API Level" control +available in the API reference documentation, see +Filtering the documentation at the +end of this document.

    + +

    What is API Level?

    + +

    API Level is an integer value that uniquely identifies the framework API +revision offered by a version of the Android platform.

    + +

    The Android platform provides a framework API that applications can use to +interact with the underlying Android system. The framework API consists of:

    + +
      +
    • A core set of packages and classes
    • +
    • A set of XML elements and attributes for declaring a manifest file
    • +
    • A set of XML elements and attributes for declaring and accessing resources
    • +
    • A set of Intents
    • +
    • A set of permissions that applications can request, as well as permission +enforcements included in the system
    • +
    + +

    Each successive version of the Android platform can include updates to the +Android application framework API that it delivers.

    + +

    Updates to the framework API are designed so that the new API remains +compatible with earlier versions of the API. That is, most changes in the API +are additive and introduce new or replacement functionality. As parts of the API +are upgraded, the older replaced parts are deprecated but are not removed, so +that existing applications can still use them. In a very small number of cases, +parts of the API may be modified or removed, although typically such changes are +only needed to ensure API robustness and application or system security. All +other API parts from earlier revisions are carried forward without +modification.

    + +

    The framework API that an Android platform delivers is specified using an +integer identifier called "API Level". Each Android platform version supports +exactly one API Level, although support is implicit for all earlier API Levels +(down to API Level 1). The initial release of the Android platform provided +API Level 1 and subsequent releases have incremented the API Level.

    + +

    The following table specifies the API Level supported by each version of the +Android platform.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Platform VersionAPI LevelVERSION_CODENotes
    Android 4.0.315{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1}Platform +Highlights
    Android 4.0, 4.0.1, 4.0.214{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}
    Android 3.213{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2}
    Android 3.1.x12{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR1}Platform Highlights
    Android 3.0.x11{@link android.os.Build.VERSION_CODES#HONEYCOMB}Platform Highlights
    Android 2.3.4
    Android 2.3.3
    10{@link android.os.Build.VERSION_CODES#GINGERBREAD_MR1}Platform Highlights
    Android 2.3.2
    Android 2.3.1
    Android 2.3
    9{@link android.os.Build.VERSION_CODES#GINGERBREAD}
    Android 2.2.x8{@link android.os.Build.VERSION_CODES#FROYO}Platform Highlights
    Android 2.1.x7{@link android.os.Build.VERSION_CODES#ECLAIR_MR1}Platform Highlights
    Android 2.0.16{@link android.os.Build.VERSION_CODES#ECLAIR_0_1}
    Android 2.05{@link android.os.Build.VERSION_CODES#ECLAIR}
    Android 1.64{@link android.os.Build.VERSION_CODES#DONUT}Platform Highlights
    Android 1.53{@link android.os.Build.VERSION_CODES#CUPCAKE}Platform Highlights
    Android 1.12{@link android.os.Build.VERSION_CODES#BASE_1_1}
    Android 1.01{@link android.os.Build.VERSION_CODES#BASE}
    + + +

    Uses of API Level in Android

    + +

    The API Level identifier serves a key role in ensuring the best possible +experience for users and application developers: + +

      +
    • It lets the Android platform describe the maximum framework API revision +that it supports
    • +
    • It lets applications describe the framework API revision that they +require
    • +
    • It lets the system negotiate the installation of applications on the user's +device, such that version-incompatible applications are not installed.
    • +
    + +

    Each Android platform version stores its API Level identifier internally, in +the Android system itself.

    + +

    Applications can use a manifest element provided by the framework API — +<uses-sdk> — to describe the minimum and maximum API +Levels under which they are able to run, as well as the preferred API Level that +they are designed to support. The element offers three key attributes:

    + +
      +
    • android:minSdkVersion — Specifies the minimum API Level +on which the application is able to run. The default value is "1".
    • +
    • android:targetSdkVersion — Specifies the API Level +on which the application is designed to run. In some cases, this allows the +application to use manifest elements or behaviors defined in the target +API Level, rather than being restricted to using only those defined +for the minimum API Level.
    • +
    • android:maxSdkVersion — Specifies the maximum API Level +on which the application is able to run. Important: Please read the <uses-sdk> +documentation before using this attribute.
    • +
    + +

    For example, to specify the minimum system API Level that an application +requires in order to run, the application would include in its manifest a +<uses-sdk> element with a android:minSdkVersion +attribute. The value of android:minSdkVersion would be the integer +corresponding to the API Level of the earliest version of the Android platform +under which the application can run.

    + +

    When the user attempts to install an application, or when revalidating an +appplication after a system update, the Android system first checks the +<uses-sdk> attributes in the application's manifest and +compares the values against its own internal API Level. The system allows the +installation to begin only if these conditions are met:

    + +
      +
    • If a android:minSdkVersion attribute is declared, its value +must be less than or equal to the system's API Level integer. If not declared, +the system assumes that the application requires API Level 1.
    • +
    • If a android:maxSdkVersion attribute is declared, its value +must be equal to or greater than the system's API Level integer. +If not declared, the system assumes that the application +has no maximum API Level. Please read the <uses-sdk> +documentation for more information about how the system handles this attribute.
    • +
    + +

    When declared in an application's manifest, a <uses-sdk> +element might look like this:

    + +
    <manifest>
    +  <uses-sdk android:minSdkVersion="5" />
    +  ...
    +</manifest>
    + +

    The principal reason that an application would declare an API Level in +android:minSdkVersion is to tell the Android system that it is +using APIs that were introduced in the API Level specified. If the +application were to be somehow installed on a platform with a lower API Level, +then it would crash at run-time when it tried to access APIs that don't exist. +The system prevents such an outcome by not allowing the application to be +installed if the lowest API Level it requires is higher than that of the +platform version on the target device.

    + +

    For example, the {@link android.appwidget} package was introduced with API +Level 3. If an application uses that API, it must declare a +android:minSdkVersion attribute with a value of "3". The +application will then be installable on platforms such as Android 1.5 (API Level +3) and Android 1.6 (API Level 4), but not on the Android 1.1 (API Level 2) and +Android 1.0 platforms (API Level 1).

    + +

    For more information about how to specify an application's API Level +requirements, see the <uses-sdk> + section of the manifest file documentation.

    + + +

    Development Considerations

    + +

    The sections below provide information related to API level that you should +consider when developing your application.

    + +

    Application forward compatibility

    + +

    Android applications are generally forward-compatible with new versions of +the Android platform.

    + +

    Because almost all changes to the framework API are additive, an Android +application developed using any given version of the API (as specified by its +API Level) is forward-compatible with later versions of the Android platform and +higher API levels. The application should be able to run on all later versions +of the Android platform, except in isolated cases where the application uses a +part of the API that is later removed for some reason.

    + +

    Forward compatibility is important because many Android-powered devices +receive over-the-air (OTA) system updates. The user may install your +application and use it successfully, then later receive an OTA update to a new +version of the Android platform. Once the update is installed, your application +will run in a new run-time version of the environment, but one that has the API +and system capabilities that your application depends on.

    + +

    In some cases, changes below the API, such those in the underlying +system itself, may affect your application when it is run in the new +environment. For that reason it's important for you, as the application +developer, to understand how the application will look and behave in each system +environment. To help you test your application on various versions of the Android +platform, the Android SDK includes multiple platforms that you can download. +Each platform includes a compatible system image that you can run in an AVD, to +test your application.

    + +

    Application backward compatibility

    + +

    Android applications are not necessarily backward compatible with versions of +the Android platform older than the version against which they were compiled. +

    + +

    Each new version of the Android platform can include new framework APIs, such +as those that give applications access to new platform capabilities or replace +existing API parts. The new APIs are accessible to applications when running on +the new platform and, as mentioned above, also when running on later versions of +the platform, as specified by API Level. Conversely, because earlier versions of +the platform do not include the new APIs, applications that use the new APIs are +unable to run on those platforms.

    + +

    Although it's unlikely that an Android-powered device would be downgraded to +a previous version of the platform, it's important to realize that there are +likely to be many devices in the field that run earlier versions of the +platform. Even among devices that receive OTA updates, some might lag and +might not receive an update for a significant amount of time.

    + +

    Selecting a platform version and API Level

    + +

    When you are developing your application, you will need to choose +the platform version against which you will compile the application. In +general, you should compile your application against the lowest possible +version of the platform that your application can support. + +

    You can determine the lowest possible platform version by compiling the +application against successively lower build targets. After you determine the +lowest version, you should create an AVD using the corresponding platform +version (and API Level) and fully test your application. Make sure to declare a +android:minSdkVersion attribute in the application's manifest and +set its value to the API Level of the platform version.

    + +

    Declaring a minimum API Level

    + +

    If you build an application that uses APIs or system features introduced in +the latest platform version, you should set the +android:minSdkVersion attribute to the API Level of the latest +platform version. This ensures that users will only be able to install your +application if their devices are running a compatible version of the Android +platform. In turn, this ensures that your application can function properly on +their devices.

    + +

    If your application uses APIs introduced in the latest platform version but +does not declare a android:minSdkVersion attribute, then +it will run properly on devices running the latest version of the platform, but +not on devices running earlier versions of the platform. In the latter +case, the application will crash at runtime when it tries to use APIs that don't +exist on the earlier versions.

    + +

    Testing against higher API Levels

    + +

    After compiling your application, you should make sure to test it on the +platform specified in the application's android:minSdkVersion +attribute. To do so, create an AVD that uses the platform version required by +your application. Additionally, to ensure forward-compatibility, you should run +and test the application on all platforms that use a higher API Level than that +used by your application.

    + +

    The Android SDK includes multiple platform versions that you can use, +including the latest version, and provides an updater tool that you can use to +download other platform versions as necessary.

    + +

    To access the updater, use the android command-line tool, +located in the <sdk>/tools directory. You can launch the SDK updater by +executing android sdk. You can +also simply double-click the android.bat (Windows) or android (OS X/Linux) file. +In ADT, you can also access the updater by selecting +Window > Android SDK +Manager.

    + +

    To run your application against different platform versions in the emulator, +create an AVD for each platform version that you want to test. For more +information about AVDs, see Creating and Managing Virtual Devices. If +you are using a physical device for testing, ensure that you know the API Level +of the Android platform it runs. See the table at the top of this document for +a list of platform versions and their API Levels.

    + +

    Using a Provisional API Level

    + +

    In some cases, an "Early Look" Android SDK platform may be available. To let +you begin developing on the platform although the APIs may not be final, the +platform's API Level integer will not be specified. You must instead use the +platform's provisional API Level in your application manifest, in order +to build applications against the platform. A provisional API Level is not an +integer, but a string matching the codename of the unreleased platform version. +The provisional API Level will be specified in the release notes for the Early +Look SDK release notes and is case-sensitive.

    + +

    The use of a provisional API Level is designed to protect developers and +device users from inadvertently publishing or installing applications based on +the Early Look framework API, which may not run properly on actual devices +running the final system image.

    + +

    The provisional API Level will only be valid while using the Early Look SDK +and can only be used to run applications in the emulator. An application using +the provisional API Level can never be installed on an Android device. At the +final release of the platform, you must replace any instances of the provisional +API Level in your application manifest with the final platform's actual API +Level integer.

    + + +

    Filtering the Reference Documentation by API Level

    + +

    Reference documentation pages on the Android Developers site offer a "Filter +by API Level" control in the top-right area of each page. You can use the +control to show documentation only for parts of the API that are actually +accessible to your application, based on the API Level that it specifies in +the android:minSdkVersion attribute of its manifest file.

    + +

    To use filtering, select the checkbox to enable filtering, just below the +page search box. Then set the "Filter by API Level" control to the same API +Level as specified by your application. Notice that APIs introduced in a later +API Level are then grayed out and their content is masked, since they would not +be accessible to your application.

    + +

    Filtering by API Level in the documentation does not provide a view +of what is new or introduced in each API Level — it simply provides a way +to view the entire API associated with a given API Level, while excluding API +elements introduced in later API Levels.

    + +

    If you decide that you don't want to filter the API documentation, just +disable the feature using the checkbox. By default, API Level filtering is +disabled, so that you can view the full framework API, regardless of API Level. +

    + +

    Also note that the reference documentation for individual API elements +specifies the API Level at which each element was introduced. The API Level +for packages and classes is specified as "Since <api level>" at the +top-right corner of the content area on each documentation page. The API Level +for class members is specified in their detailed description headers, +at the right margin.

    diff --git a/docs/html/about/versions/index.jd b/docs/html/about/versions/index.jd new file mode 100644 index 000000000000..30826c085a0e --- /dev/null +++ b/docs/html/about/versions/index.jd @@ -0,0 +1,141 @@ +page.title=App Framework +@jd:body + +

    Android is a software stack for mobile devices that includes an operating +system, middleware and key applications. The Android SDK +provides the tools and APIs necessary to begin developing applications on the +Android platform using the Java programming language.

    + +

    Features

    + +
      +
    • Application framework enabling reuse and replacement + of components
    • +
    • Dalvik virtual machine optimized for mobile + devices
    • +
    • Integrated browser based on the open source WebKit engine
    • +
    • Optimized graphics powered by a custom 2D graphics library; 3D + graphics based on the OpenGL ES 1.0 specification (hardware acceleration + optional)
    • +
    • SQLite for structured data storage
    • +
    • Media support for common audio, video, and still + image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, + GIF)
    • +
    • GSM Telephony (hardware dependent)
    • +
    • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
    • +
    • Camera, GPS, compass, and accelerometer (hardware dependent)
    • +
    • Rich development environment including a device + emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE
    • +
    + + +

    Android Architecture

    + +

    The following diagram shows the major components of the Android operating +system. Each section is described in more detail below.

    + +

    Android System Architecture

    + + +

    Applications

    + +

    Android will ship with a set of core applications including an email +client, SMS program, calendar, maps, browser, contacts, and +others. All applications are written using the Java programming language.

    + + +

    Application Framework

    + +

    By providing an open development platform, Android +offers developers the ability to build extremely rich and innovative +applications. Developers are free to take advantage of the +device hardware, access location information, run background services, set alarms, +add notifications to the status bar, and much, much more.

    + +

    Developers have full access to the same framework APIs used by the core +applications. The application architecture is designed to simplify the reuse +of components; any application can publish its capabilities and any other +application may then make use of those capabilities (subject to security +constraints enforced by the framework). This same mechanism allows components +to be replaced by the user.

    + +

    Underlying all applications is a set of services and systems, including: +

      +
    • A rich and extensible set of Views that can be used to + build an application, including lists, grids, text boxes, buttons, and even + an embeddable web browser
    • +
    • Content + Providers that enable applications to access data from other + applications (such as Contacts), or to share their own data
    • A Resource + Manager, providing access to non-code resources such as localized + strings, graphics, and layout files
    • +
    • A {@link android.app.NotificationManager Notification Manager} that enables + all applications to display custom alerts in the status bar
    • +
    • An {@link android.app.Activity Activity Manager} that manages the + lifecycle of applications and provides a common navigation backstack
    • +
    + +

    For more details and a walkthrough of an application, see the Notepad Tutorial.

    + + +

    Libraries

    + +

    Android includes a set of C/C++ libraries used by various components of the +Android system. These capabilities are exposed to developers through the +Android application framework. Some of the core libraries are listed below:

    +
      +
    • System C library - a BSD-derived implementation of + the standard C system library (libc), tuned for embedded Linux-based + devices
    • +
    • Media Libraries - based on PacketVideo's OpenCORE; + the libraries support playback and recording of many popular audio and video + formats, as well as static image files, including MPEG4, H.264, MP3, AAC, + AMR, JPG, and PNG
    • +
    • Surface Manager - manages access to the display + subsystem and seamlessly composites 2D and 3D graphic layers from multiple + applications
    • +
    • LibWebCore - a modern web browser engine which + powers both the Android browser and an embeddable web view
    • +
    • SGL - the underlying 2D graphics + engine
    • +
    • 3D libraries - an implementation based on + OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration + (where available) or the included, highly optimized 3D software + rasterizer
    • +
    • FreeType - bitmap and vector font rendering
    • +
    • SQLite - a powerful and lightweight relational + database engine available to all applications
    • +
    + + + +

    Android Runtime

    + +

    Android includes a set of core libraries that provides most of +the functionality available in the core libraries of the Java programming +language.

    + +

    Every Android application runs in its own process, with its own instance of +the Dalvik virtual machine. Dalvik has been written so that a device can run +multiple VMs efficiently. The Dalvik VM executes files in the Dalvik +Executable (.dex) format which is optimized for minimal memory +footprint. The VM is register-based, and runs classes +compiled by a Java language compiler that have been transformed into the .dex +format by the included "dx" tool.

    + +

    The Dalvik VM relies on the Linux kernel for underlying functionality such +as threading and low-level memory management.

    + + + +

    Linux Kernel

    + +

    Android relies on Linux version 2.6 for core system services such as +security, memory management, process management, network stack, and driver +model. The kernel also acts as an abstraction layer between the hardware and +the rest of the software stack.

    diff --git a/docs/html/community/index.html b/docs/html/community/index.html deleted file mode 100644 index fb2a0d35bcc1..000000000000 --- a/docs/html/community/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should have been redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/design/building-blocks/index.jd b/docs/html/design/building-blocks/index.jd index 52b4915f2020..d915aae51abf 100644 --- a/docs/html/design/building-blocks/index.jd +++ b/docs/html/design/building-blocks/index.jd @@ -10,7 +10,7 @@ footer.hide=1 #text-overlay { position: absolute; - left: 10px; + left: 0; top: 472px; width: 450px; } diff --git a/docs/html/design/building-blocks/progress.jd b/docs/html/design/building-blocks/progress.jd index b18853871fce..03fc09c7302c 100644 --- a/docs/html/design/building-blocks/progress.jd +++ b/docs/html/design/building-blocks/progress.jd @@ -1,5 +1,4 @@ page.title=Progress and Activity -header.title=Feedback @jd:body

    When an operation of interest to the user is taking place over a relatively long period of time, diff --git a/docs/html/design/design_toc.cs b/docs/html/design/design_toc.cs index 6dd8d610418f..a31fdd322e93 100644 --- a/docs/html/design/design_toc.cs +++ b/docs/html/design/design_toc.cs @@ -63,8 +63,4 @@

    -
  • - -
  • - \ No newline at end of file diff --git a/docs/html/design/index.jd b/docs/html/design/index.jd index d404aa6e42e2..1e6b40c5876b 100644 --- a/docs/html/design/index.jd +++ b/docs/html/design/index.jd @@ -1,4 +1,4 @@ -page.title= +page.title=Design header.hide=1 footer.hide=1 @jd:body @@ -10,7 +10,7 @@ footer.hide=1 #text-overlay { position: absolute; - left: 10px; + left: 0; top: 472px; width: 280px; } diff --git a/docs/html/design/media/typography_sizes.png b/docs/html/design/media/typography_sizes.png index fe6cdcee9464..eda1d996d4a0 100644 Binary files a/docs/html/design/media/typography_sizes.png and b/docs/html/design/media/typography_sizes.png differ diff --git a/docs/html/design/patterns/index.jd b/docs/html/design/patterns/index.jd index 732e4dbc60bc..6f88e6d99fd0 100644 --- a/docs/html/design/patterns/index.jd +++ b/docs/html/design/patterns/index.jd @@ -10,7 +10,7 @@ footer.hide=1 #text-overlay { position: absolute; - left: 10px; + left: 0; top: 492px; width: 200px; } diff --git a/docs/html/design/style/iconography.jd b/docs/html/design/style/iconography.jd index c4e8bd6acaee..775e45d9fdbb 100644 --- a/docs/html/design/style/iconography.jd +++ b/docs/html/design/style/iconography.jd @@ -139,7 +139,7 @@ files for further customization.
    • -

      Action bar icons for phones and tablets should be 32x32 dp.

    • +

      Action bar icons for phones should be 32x32 dp.

    diff --git a/docs/html/design/style/index.jd b/docs/html/design/style/index.jd index d346aea114e1..74d085b759b0 100644 --- a/docs/html/design/style/index.jd +++ b/docs/html/design/style/index.jd @@ -10,7 +10,7 @@ footer.hide=1 #text-overlay { position: absolute; - left: 10px; + left: 0; top: 402px; width: 220px; } diff --git a/docs/html/develop/index.jd b/docs/html/develop/index.jd new file mode 100644 index 000000000000..6830b72cfe84 --- /dev/null +++ b/docs/html/develop/index.jd @@ -0,0 +1,366 @@ +fullpage=true +page.title=Develop +header.hide=1 +carousel=1 +tabbedList=1 +@jd:body + + + +
    +
    +
    + + Your video is supposed to appear here.
    + Make sure you have the Flash® Player. +
    +
    + close video +
    +
    + +
    + +
    + Prev + Next +
    +
      + + + + +
    +
    +
    + +
    +
    + +
    +
      +
    • DEVELOPER NEWS
    • +
    • FEATURED DOCS
    • +
    +
    +
    + + + + +
    +
    +
    + +
    +
      +
    • DEVELOPERS LIVE
    • +
    • VIDEO PLAYLISTS
    • +
    +
    +
    +
      +
    +
      +
    +
    +
    +
    + +
    + +
    +
    + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/html/distribute/distribute_toc.cs b/docs/html/distribute/distribute_toc.cs new file mode 100644 index 000000000000..bc028e57530f --- /dev/null +++ b/docs/html/distribute/distribute_toc.cs @@ -0,0 +1,112 @@ + + \ No newline at end of file diff --git a/docs/html/distribute/googleplay/about/distribution.jd b/docs/html/distribute/googleplay/about/distribution.jd new file mode 100644 index 000000000000..291d559888d5 --- /dev/null +++ b/docs/html/distribute/googleplay/about/distribution.jd @@ -0,0 +1,127 @@ +page.title=Distribution Control +page.metaDescription=Reach the users you want, whenever you want. + +@jd:body + +

    Deliver your apps to the users you want, on the devices you want, on your schedule.

    + +

    Instant publishing, instant updates

    + +

    On Google Play, you can publish your products to customers instantly. Just +upload and configure your product in the Google Play Android Developer Console +and press the Publish button—your app appears in the store listings within +hours, not weeks. There are no delays for code or policy reviews, so you keep +complete control over your release schedule.

    + +

    Once your app is published, you can update it as often as you want. You can +change prices, configuration, and distribution options at any time through the +Google Play Android Developer Console, without needing to update your app +binary.

    + +

    Later, as you add features or address code issues, you can publish an updated +binary at any time. Google Play makes the new version available immediately and +notifies existing customers that an update is ready for download. To streamline +the rollout across your customer base, Google Play also lets users accept +automatic updates of your app, so that your updates are delivered and installed +s soon as you publish them.

    + +

    Reaching the customers you want

    + +

    Google Play does more than connect your app with users—it helps you +reach the broadest possible distribution across the Android ecosystem, while +making sure that your app is only available to the audience that you want to +reach.

    + +
    + +
    + +

    Geographic targeting

    + +

    You can use controls in the Google Play Android Developer Console to easily +manage the geographic distribution of your apps, without any changes in your +application binary. You can specify which countries and territories you want to +distribute to, and even which carriers (for some countries).

    + +

    When users visit the store, Google Play makes sure that they are in one of +your targeted countries before downloading your app. You can change your country +and carrier targeting at any time just by saving changes in the Google Play +Android Developer Console

    + +
    + +
    + +

    Capabilities targeting

    + +

    Google Play also lets you control distribution according to device features +or capabilities that your app depends on. There are several types of +dependencies that the app can define in its manifest, such as hardware features, +OpenGL texture compression formats, libraries, Android platform versions, and +others.

    + +

    When you upload your app, Google Play reads the dependencies and sets up any +necessary distribution rules. For technical information about declaring +dependencies, read Filters on +Google Play.

    + +

    For pinpoint control over distribution, Google Play lets you see all of the +devices your app is available to based on its dependencies (if any). From the +Google Play Android Developer Console, you can list the supported devices and +even exclude specific devices if needed.

    + +

    Statistics for analyzing installs

    + +

    Once you’ve published your app, Google Play makes it easy to see how it’s +doing. The Google Play Android Developer Console gives you access to a variety +of anonymized metrics that show your app’s installation performance measured by +unique users and unique devices, across a variety of different dimensions such +as country, Android version, device, country, carrier, and app version.

    + +
    + +
    +

    You can also view your installation data on timeline charts, for all metrics and +dimensions. At a glance, these charts highlight your app’s installation peaks +and longer-term trends, which you can correlate to promotions, app improvements, +or other factors. You can even focus in on data inside a dimension by +highlighting specific data points (such as individual platform versions or +languages) on the timeline.

    + +

    So that you can “take your data with you”, you can download all of your +installation data as a CSV file for viewing in the business program of your +choice.

    + + +

    Advanced delivery options

    + +

    Google Play offers convenient options for managing how your apps are +delivered to users.

    + +

    In most cases, it’s easy to create an app that supports all of your targeted +screen sizes and platform versions from a single APK. Distributing a single APK +to all of your users is a highly recommended approach, because it’s the easiest +way to manage and maintain the app. If you need to deliver a different APK to +devices, Google Play provides a way to do that.

    + +

    An option called Multiple APK support lets you create multiple APK packages +that use the same package name but differ in their OpenGL texture compression +formats, screen-size support, or Android platform versions supported. You can +upload all of the APKs to Google Play under a single product listing and Google +Play selects the best APK to deliver to users, based on the characteristics of +their devices.

    + +

    The APK Expansion Files option lets you upload up to two secondary downloads +for each published APK, including multiple APKs. Each of the two expansion files +can be up to 2GB each and can contain any type of code or assets. When you +upload the expansion files, Google Play hosts them for free and handles the +download of the files as part of the normal APK installation.

    + +

    Protecting your App

    + +

    To help you protect your application against piracy, Google Play offers a +licensing service that you can implement in your app. It’s a network-based +service that lets an application query a trusted Google Play licensing server to +determine whether the application is licensed to the current device user.

    diff --git a/docs/html/distribute/googleplay/about/monetizing.jd b/docs/html/distribute/googleplay/about/monetizing.jd new file mode 100644 index 000000000000..1e3437b266a2 --- /dev/null +++ b/docs/html/distribute/googleplay/about/monetizing.jd @@ -0,0 +1,152 @@ +page.title=Flexible Monetizing and Business Tools +page.metaDescription= + +@jd:body + +
    + + +
    + +

    Sell your app in more than 130 countries. Flexible monetization options with +in-app purchase, subscriptions, and more.

    + +

    Streamlined purchase flow for users

    + +

    When users find your app, they can purchase it instantly with a streamlined, +consistent purchasing process and convenient payment methods.

    + +

    Instant purchase from device or web

    + +

    Google Play makes it fast and easy for your customers to buy your products, +whether from a phone, a tablet, or a desktop computer. When users find an app or +game that they want to buy, they can purchase it in as few as two steps—one +to initiate the purchase and another to accept purchase details and permissions +and complete the transaction.

    + +

    Google Play's convenient purchase experience is the same familiar process for +all products everywhere across Google Play—apps, games, in-app products and +subscriptions, and other digital content.

    + +

    Cloud-connected

    + +

    Purchasing is even more convenient on Google Play because it’s +cloud-connected. Users can find and purchase your products from anywhere—from +their Android phones or using any web browser on any host computer.

    + +

    When users find an app or game they want to buy, they purchase it and download +it instantly to their devices over-the-air. Users who sign in to the Google Play web site can also buy apps and games +and push them instantly to their phones, tablets, or other devices. Google Play +manages the application download.

    + +

    Convenient payment options

    + +

    Users can purchase your products on Google Play using several convenient +payment methods—credit card, Direct Carrier Billing, and Google Play balance.

    + +

    Credit card is the most common method of payment. Users can pay using any credit card +that they’ve registered in Google Play. To make it easy for users to get started, +registration is offered as a part of initial device setup process.

    + + + +

    Subscribers on many popular carrier networks worldwide can charge purchases +to their monthly mobile phone bills through Direct +Carrier Billing. This form of payment is convenient and simple and is +extremely popular in regions where credit cards are less common. More than 75 +million users in key markets around the world can purchase +your products through Direct Carrier Billing. Many more will get the option in +the months ahead.

    + +

    The payment methods available to users worldwide may vary, based on +location, carrier network, and other factors.

    + +
    + +
    + +

    Choice of billing models

    + +

    Google Play gives you a choice of billing models to let you monetize your +products.

    + +

    You can offer apps to all users for free, or +you can set an initial price for the app, paid before download. You can also +sell one-time purchases and auto-renewing subscriptions from inside the app, and +you can take advantage of AdMob integration to monetize your app through +targeted advertising.

    + + + +

    You can combine these billing models in different ways, based on your business +needs or market conditions.

    + +

    For example, you can use a freemium or ad-supported model by distributing +your app for free and selling in-app products or advertising. Alternatively you +could set a nominal price for your app at download and sell value add-ons, +gameplay levels, and upgrades as in-app products. The only restriction is that +free apps must remain free (to download) for the life of the app.

    + +

    Flexible pricing in the currencies of your customers

    + +
    + +
    + +

    Google Play gives you complete control over how you price your products. You +can set prices in more than 130 countries, for millions of +users around the world. When users browse your app’s product page or initiate a +purchase, Google Play shows them the price they will be charged in +their local currency.

    + +

    You can set and adjust your prices at any time, in any available currency. +Your prices in available currencies are independent, so you can adjust one +price without affecting others. This gives you the ability to run +short-term promotions and discounts in specific countries and more easily +manage shifts in exchange rates.

    + +

    You can set and manage prices for your apps and in-app products from the +Google Play Android Developer Console.

    + +

    Monthly payouts in your local currency

    + +

    To sell products in Google Play, all you have to do is register for a Google +Checkout merchant account and link it to your Google Play Android Developer +Console account (see Get Started with +Publishing for details). Once you’ve set up your account and published your +apps, Google Play makes monthly payouts of sales proceeds to your merchant +account, in your local currency.

    + +

    Detailed financial reporting

    + +

    When you sell priced apps or in-app products on Google Play, you get a +variety of financial reports to help you track and project sales, optimize your +marketing campaigns, and support your customers.

    + +

    To help you keep up-to-date with the current activity, you can download daily +reports summarizing recent purchases of your products. The reports include +estimated sales amounts and include a variety of other data for each +transaction.

    + +

    At the close of the month, you can download a complete sales report that +gives you the final details of all transactions that closed in the month, +including the payout amounts and other data. Additional financial reports are +available in your Google Checkout merchant account.

    diff --git a/docs/html/distribute/googleplay/about/visibility.jd b/docs/html/distribute/googleplay/about/visibility.jd new file mode 100644 index 000000000000..2c5dbe522055 --- /dev/null +++ b/docs/html/distribute/googleplay/about/visibility.jd @@ -0,0 +1,247 @@ +page.title=Visibility for Your Apps +page.metaDescription= + +@jd:body + +
    + +
    + +

    A billion downloads a month and growing. Get your apps in front of millions +of users at Google's scale.

    + + +

    Worldwide reach, rapid growth

    + +

    Google Play is the premier store for distributing Android apps. It’s +preinstalled on more than 300 million devices worldwide, a number growing by +almost a million every day. Android users have downloaded +more than 15 billion apps from Google +Play, growing at a rate of more than 1 billion per month.

    + +

    When you publish on Google Play, you put your apps in front of Android's huge +base of active customers, in more than 130 countries and territories across the +world.

    + +

    Google Play is a central part of the Android experience. New users +personalize their devices with apps, games, and other Google Play content. +Existing users return regularly to see what's trending and new. Downloading new +apps is extremely convenient and fast— Google Play pushes apps to the +user's devices instantly, over the air. No cable or sync is ever needed.

    + +
    +
    + +
    +

    Growth in app consumption: Users download more than +1 billion apps from Google Play each month.

    +
    + +
    +

    Google Play is also a top destination for visitors from the the web. Anyone +with a browser can explore everything that Google Play has to offer from its web site. Android users can even buy and +install the apps they want and Google Play pushes them automatically to their +devices over the air.

    + +

    The accessiblility and convenience of the Google Play web +site give you new ways to drive traffic to your products from online ads, web +search, cross-linking, and more.

    +
    + +
    +

    Built for app discovery

    + +

    Google Play is designed to connect users with great apps and games. It +provides key channels to help your app get noticed and gain traction in the +marketplace.

    + +

    User ratings and reviews

    + +

    When you develop a great app, Android users show their appreciation through +ratings and reviews. They rate your app (out of 5 stars) after downloading it +and can post a short description of their experience. When other users are +considering your app, they look at the ratings and reviews as key benchmarks of +the app’s quality.

    + +
    + +

    Your app’s rating is one of the most important factors influencing its +ranking in the various lists and search results in Google Play. It's also one of +the key signals that the editorial staff looks for, when curating apps and games +for promotion in the store.

    + +
    + +
    + +

    Category browsing

    + +

    When you publish an app in Google Play, you pick the category in which you +want users to find your app. More than 30 categories are available. Inside each +category, apps are ranked based on a combination of ratings, reviews, downloads, +country, and other factors. Many popular categories also start with a collection +of featured apps selected by the Google Play editorial staff.

    + +
    +
    + + + +
    +

    Featuring in +categories: Most app and game categories include a featured list curated +by the editorial team.

    +
    + + + +

    Search on Google Play lets users pinpoint an app or game quickly. Search uses +powerful heuristics to suggest terms as the user types, and it offers direct +links to apps as suggestions. In results, users find the most relevant, most +popular apps at the top.

    + +
    + +
    + +

    Top charts and lists

    + +

    Top charts keep users in touch with what’s popular and trending with Android +users, right from the Apps and Games home pages. The charts are generated +several times each day based on recent download activity, keeping them fresh and +allowing new apps to move upward in the charts. To make the charts as relevant +as possible for users across the world, they are also country-specific.

    + +

    As your apps get traction and build momentum in downloads and ratings, +they’ll climb one or more of the top charts and gain even more exposure.

    + +
    + + + + + + + + + + +
    Top FreeFree apps and games
    Top PaidPriced apps and games
    Top New FreeLess than 30 days old
    Top New PaidLess than 30 days old
    Top GrossingGross proceeds, free or priced
    Best SellingPopular priced games
    TrendingNew arrivals growing quickly in installs
    +
    + +
    + + + +
    + + +
    + +

    The Google Play editorial team is dedicated to bringing the best apps to the +attention of users. It constantly reviews apps from across Google Play to find +not only the biggest apps and games, but also the “diamonds in the rough” that +they want more people to see.

    + +

    When the team finds great apps and games they use the Featured, +Staff Picks, and other collections to promote them. Any one of those +can give your apps dramatically higher visibility and market penetration.

    + +

    You can’t nominate your app for featuring or pay for a promotional slot, +because the editorial team wants to show the best apps and give the same chances +to all developers. However, if you build an app that users love and that looks +great on Android devices, the editorial team will notice. +

    + +

    Featured and Staff Picks

    + +

    Each week the the Google Play editorial staff selects a new set of apps to +promote in its popular Featured and Staff Picks collections. +

    + +The Featured collections highlight the latest and greatest app and game +titles available for Android. Category featuring highlights the best and most +popular apps in the top categories. + +Staff Picks collects all recently featured apps and games on Google +Play. To better reach tablet users, there’s a special Staff Picks +collection that highlights the best apps for Android tablets.

    + +
    + + +
    + +

    App collections

    + +

    From time to time the editorial staff puts together a collection of apps and +games based on a theme or seasonal event. The collections are popular with +customers because they are timely and relevant, and they provide a new way to +showcase great Android apps to users.

    + +

    The editorial staff chooses apps for collection promotions in a similar way +as for featuring—high-quality apps that show the best of Android on phones +and tablets. For collections the staff also looks for apps that can make an +interesting or unique contribution to the collection as a whole.

    + +

    EDITORS' CHOICE

    + +

    Editors’ Choice is a curated collection of apps that highlights some +of the very best apps available on Android. These apps are chosen for high +quality and great UI, long-term popularity, and innovative use of Android +features.

    + +

    Apps chosen for Editors’ Choice also receive a badge that is +displayed wherever the app name is seen in Google Play.

    + +

    TOP DEVELOPER

    + +

    Top Developer is a badge recognizing established, respected developers for +their commitment to launching high-quality and innovative apps on +Android. The Google Play editorial staff selects developers awards a Top +Developer badge from time to time, based on the cumulative work of the +developer.

    + +

    The Top Developer badge appears next to the developer name wherever it is +displayed in Google Play. For a developer, the badge means long-term recognition +of all of your apps. For users, the badge signifies an additional level of trust +and confidence in your products.

    + +

    Rich, colorful product pages

    + +

    In Google Play, your app’s storefront is its product details page +— a rich and colorful page that lets you promote your app, highlight its +ratings and reviews, and show what your app can do. + +

    Your product details page is the one page where your users come to find out +everything about your app. When they see your app listed in search results, top +charts, category listings, and collections, one tap takes them directly to your +product details page.

    + +
    + +
    + +

    You can manage your product details page through the Google Play Android Develeper Console, from any +web browser. Just sign in, upload or update your brand assets, and enter your +product details in the languages of your markets.

    + +

    When you publish, Google Play adds your app’s ratings, reviews, links to your +other products, and more, and makes sure your product details page looks great +on phones, tablets, or in a web browser.

    + +

    You can link web users directly to your product details page from outside +Google Play, such as from your web site, an ad campaign, reviews, social media +posts, and more. See Linking +to Your Products to find out how.

    + +

    To learn more about how to create your product details page, see +Publishing on Google Play.

    diff --git a/docs/html/distribute/googleplay/index.html b/docs/html/distribute/googleplay/index.html new file mode 100644 index 000000000000..46a8ce2c3b67 --- /dev/null +++ b/docs/html/distribute/googleplay/index.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should have been redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/distribute/googleplay/promote/badges.jd b/docs/html/distribute/googleplay/promote/badges.jd new file mode 100644 index 000000000000..de12e2a962c0 --- /dev/null +++ b/docs/html/distribute/googleplay/promote/badges.jd @@ -0,0 +1,203 @@ +page.title=Google Play Badges +@jd:body + +

    Google Play badges give you an officially branded way of promoting your app to Android users. Use the form below to quickly create badges to link users to your products from web pages, ads, reviews, and more. See Linking to your products for more ways to bring users to your apps.

    + +

    Input your app's package or your publisher name, choose the style, size, and language, and click "Build my badge". The form will generate code for an embbeded button that links to your app's product page or a list of your apps.

    + +

    Note that you should not modify the Google Play badges after generating them, including colors, size, text, and logo. See Android Brand Guidelines for more information.

    + + + + + +
    + +   + +

     or

    + +   + +

    + +
    + + +      + + +
    + +
    + + +      + + +
    + + +
    +
    + + diff --git a/docs/html/distribute/googleplay/promote/brand.jd b/docs/html/distribute/googleplay/promote/brand.jd new file mode 100644 index 000000000000..8aafc48fe3dd --- /dev/null +++ b/docs/html/distribute/googleplay/promote/brand.jd @@ -0,0 +1,174 @@ +page.title=Brand Assets, Icons, and Guidelines +@jd:body + +

    We encourage you to use the Android and Google Play brands in your +promotional materials. You can use the icons and other assets on this page in +any way you want, provided that you follow the guidelines described below.

    + +

    Android Brand

    + +
    +
    + +
    + +
    +

    01/ Android Robot

    + +

    Can be used, reproduced, and modified freely in marketing + communications. Our standard color value for print is PMS 376C. Our online hex + color is #A4C639.

    + +

    When using the Android Robot or any modification of it, proper attribution is + required under the terms of the Creative Commons Attribution license. For more + details on proper attribution, please see the Content License document.

    +
    +
    + +
    +
    + +
    + +
    +

    02/ Android Logo

    + +

    The Android logo may not be used.

    +
    +
    + +
    +
    + +
    + +
    +

    03/ Android Custom Typeface

    + +

    The custom typeface may not be used.

    +
    +
    + +
    +
    + +
    + +
    +

    04/ Android in Official Names

    +

    Any name with 'Android' alone may not be used in a name without permission. Any name + with 'Droid' alone may not be used in a name.

    + +

    The word 'Android' may be used only as a descriptor, 'for Android'. If used with your + logo, 'for Android' needs to be smaller in size than your logo. First instance of this + use should be followed by a TM symbol, 'for Android™'.

    + +

    If you are not sure you meet these criteria, please contact us.

    +
    +
    + +
    +
    + +
    + +
    +

    05/ Android in Messaging

    +

    + May be used in text as a descriptor, as long as it is followed by a proper generic term + (e.g. "Android™ application"). First instance of this use should be followed by a TM + symbol. +

    +
    +
    +

    Note: Any usage of #04 or #05 needs to include footer attribution in your + communication:
    + "Android is a trademark of Google Inc." +

    + +

    Google Play Brand

    + +
    +
    +

    + Google Play logo +

    +

    + Get it on Google Play badge, large
    + Download: Small | Large +

    +

    + Android App on Google Play badge, large
    + Download: Small | + Large +

    +
    + +
    +

    06/ Get it on Google Play Badge +

    +

    + The "Get it on Google Play" and "Android App on Google Play" logos are badges that you + can use on your web site and promotional materials, to point to your products on Google + Play. +

    +

    + The logos are available in two sizes: +

    +
      +
    • Large: 60(h) x 172(w)
    • + +
    • Small 45(h) x 129(w) +
    • +
    +

    + Guidelines for usage: +

    +
      +
    • Never separate the phrase “Get it on Google Play” or "Android App on Google Play" + from the Google Play logo, and do not change the color, proportions, spacing or any + other aspect of the logo. +
    • +
    +
    + +
      +
    • When used online, the badge logo should be used to direct users to: +
        +
      • The Google Play landing page:
        play.google.com +
      • +
      • The Google Play Apps landing page:
        + play.google.com/store/apps +
      • +
      • A list of products that include your company name, for example,
        + http://play.google.com/store/search?q=yourCompanyName +
      • +
      • A list of products published by you, for example,
        + play.google.com/store/search?q=publisherNameM/span> +
      • +
      • A specific app product details page within Google Play, for example,
        + play.google.com/store/apps/details?id=packageName +
      • +
      +
    • +
    • When used alongside logos for other application marketplaces, the Google Play logo + should be of equal or greater size
    • +
    + +

    For details on all the ways that you can link to your product details page in Google Play, + see Linking to your products

    + +

    For convenience, if you are using the logos online, you can use the + badge generator + to create the appropriate markup and link to your apps.

    + +

    Other Brands

    + +

    Any other brands or icons depicted on this site are not are the property of their +repective owners and usage is reserved. You must seek the developer for appropriate permission to use them.

    diff --git a/docs/html/distribute/googleplay/promote/index.jd b/docs/html/distribute/googleplay/promote/index.jd new file mode 100644 index 000000000000..68829907fe22 --- /dev/null +++ b/docs/html/distribute/googleplay/promote/index.jd @@ -0,0 +1,43 @@ +page.title=Promoting Your Apps +page.metaDescription=Raise the visibility of your apps in Google Play through deep links and Google Play badges. +header.hide=0 +footer.hide=0 +@jd:body + + + +

    After you publish your app, you can bring Android users to your app's product details page by +providing links in your social network posts, ad campaigns, app reviews and articles, your +web site, and more.

    + +

    You can use the resources in this section to create deep links for your online placements. +Google Play badges are an especially great way let Android users know that your app is available +and link them directly to your download page. With the badge generator, they're also easy to make.

    + + +

    Linking to Your Products

    + diff --git a/docs/html/distribute/googleplay/promote/linking.jd b/docs/html/distribute/googleplay/promote/linking.jd new file mode 100644 index 000000000000..4a1b19834f3f --- /dev/null +++ b/docs/html/distribute/googleplay/promote/linking.jd @@ -0,0 +1,213 @@ +page.title=Linking to Your Products +@jd:body + + + +

    Google Play provides several link formats that let you bring users to your +products in the way you want, from Android apps, web pages, ads, reviews, +articles, social media posts, and more.

    + +

    The link formats let you:

    + + +

    If you are linking from an Android app, you can also control whether the link +launches the Play Store application or the browser, which takes the user +to the Google Play web site.

    + +

    Linking to a Product Details Page

    + +

    Use the format below to deep-link users directly to a specific app's product +details page. At the product details page, users can see the app description, +screenshots, reviews and more, and then install it.

    + +

    To create the link, you need to know the app's fully qualified package +name, which is declared in the app's manifest +file. The package name is also visible in the Developer Console.

    + +
    +
    From a web site:
    +
    +
    http://play.google.com/store/apps/details?id=<package_name>
    +
    +
    From an Android app:
    +
    +
    market://details?id=<package_name>
    +
    +
    + +

    Here's an example:

    + +

    http://play.google.com/store/apps/details?id=com.google.android.apps

    + +

    For details on how to send the link in an Android app, see Linking from an Android App.

    + + + +

    Linking to a Product List

    + +

    Use the format below to link users to a list of apps published by you. The +product list lets users see all of the apps from a specific publisher, with +ratings, editorial badges, and an Install button for each.

    + +

    To create the link, you need to know your publisher name, which is +available from the Developer Console.

    + +
    +
    From a web site:
    +
    +
    http://play.google.com/store/search?q=pub:<publisher_name>
    +
    +
    From an Android app:
    +
    +
    market://search?q=pub:<publisher_name>
    +
    +
    + +

    Here's an example:

    + +

    http://play.google.com/store/search?q=pub:Google Inc.

    + +

    For details on how to send the link in an Android app, see Linking from an Android App.

    + + +

    Linking to a Search Result

    + +

    Use the format below to link users to a search query result on Google Play. +The search result page shows a list of apps (and optionally other content) that +match the query, with ratings, badges, and an Install button for each.

    + +

    To create the link, you just need a search query string. If you want the +query to search outside of the Google Play Apps listings, you can remove the +&c=apps part of the link URL.

    + +
    +
    From a web site:
    +
    +
    http://play.google.com/store/search?q=<search_query>&c=apps
    +
    +
    From an Android app:
    +
    +
    market://search?q=<seach_query>&c=apps
    +
    +
    + +

    Here's an example:

    + +

    http://play.google.com/store/search?q=maps&c=apps

    + +

    For details on how to send the link in an Android app, see Linking from an Android App.

    + + + +

    Linking to a Collection

    + +

    If your app is featured or appears in one of the Google Play Top charts or +collections, you can use the format below to link users directly to the +collection. The collection shows a ranked list of apps in the collection, with +ratings, short descriptions, and an Install button.

    + +
    +
    From a web site:
    +
    +
    http://play.google.com/store/apps/collection/<collection_name>
    +
    +
    From an Android app:
    +
    +
    market://apps/collection/<collection_name>
    +
    +
    + +

    Here's an example:

    + +

    http://play.google.com/store/apps/collection/editors_choice

    + +

    For details on how to send the link in an Android app, see Linking from an Android App.

    + +

    Table 1. Collections on Google Play.

    + + + + + + + + + + + + + + +
    Collectioncollection_name
    Staff Picks (Featured)featured
    Editor's Choiceeditors_choice
    Top Paidtopselling_paid
    Top Freetopselling_free
    Top New Freetopselling_new_free
    Top New Paidtopselling_new_paid
    Top Grossingtopgrossing
    Trendingmovers_shakers
    Best Selling in Gamestopselling_paid_game
    + + +

    Linking from an Android App

    + +

    There are two general formats for links that are accessible to users on +Android devices, The two formats trigger slightly different behaviors on the +device:

    + +
      +
    • market://    Launches the Play Store app to load the +target page.
    • +
    • http://    Lets the user choose whether to launch the +Play Store app or the browser to handle the request. If the browser handles the +request, it loads the target page on the Google Play web site.
    • +
    + +

    In general, you should use http:// format for links on web pages +and market:// for links in Android apps.

    + +

    If you want to link to your products from an Android app, create an {@link +android.content.Intent} that opens an Google Play URL, as shown in the example +below.

    + +
    +Intent intent = new Intent(Intent.ACTION_VIEW);
    +intent.setData(Uri.parse("market://details?id=com.example.android"));
    +startActivity(intent);
    +
    + + +

    Summary of URL formats

    + +

    The table below provides a summary of the URIs currently supported by the Google Play (both on +the web and in an Android application), as discussed in the previous sections.

    + + + + + + + + + + + + + + + + + + + + + +
    For this resultWeb page linkAndroid app link
    Show the product details page for a specific apphttp://play.google.com/store/apps/details?id=<package_name> +market://details?id=<package_name>
    Show apps by a specific publisherhttp://play.google.com/store/search?q=pub:<publisher_name>market://search?q=pub:<publisher_name>
    Search for apps using a general string query.http://play.google.com/store/search?q=<query>market://search?q=<query>
    + diff --git a/docs/html/distribute/googleplay/promote/product-pages.jd b/docs/html/distribute/googleplay/promote/product-pages.jd new file mode 100644 index 000000000000..af5b2d5dc91e --- /dev/null +++ b/docs/html/distribute/googleplay/promote/product-pages.jd @@ -0,0 +1,4 @@ +page.title=Your Product Pages +@jd:body + +

    Placeholder...

    \ No newline at end of file diff --git a/docs/html/distribute/googleplay/publish/console.jd b/docs/html/distribute/googleplay/publish/console.jd new file mode 100644 index 000000000000..72b97abb7473 --- /dev/null +++ b/docs/html/distribute/googleplay/publish/console.jd @@ -0,0 +1,201 @@ +page.title=The Developer Console +@jd:body + + +

    Once you've registered and +received verification by email, you can sign in to your Google Play Android +Developer Console, which will be the home for your app publishing operations and +tools on Google Play. This sections below introduce a few of the key areas +you'll find in the Developer Console.

    + +
    +
    + +
    +

    Developer Console home page: Gives you a quick +overview of your apps, lets you jump to stats, reviews, or product details, or +upload a new app.

    +
    + +

    Your Developer Profile

    + +
    +
    + +
    +

    Developer profile: Specifies your developer +identity and contact information, stores your developer key, and more.

    +
    + +

    Your developer profile identifies you to Google Play and to your customers. +During registration you can provide information for your profile, but you can go +back at any time to edit the information and change your settings.

    + +

    Your developer profile contains:

    +
      +
    • Your developer name — the name you want to show users on your product +details page and elsewhere on Google Play. +
    • Your developer contact information — how Google can contact you if +needed (this information isn't exposed to users. +
    • Merchant information, in-app billing information.
    • +
    • Your developer public key for licensing and In-app Billing.
    • +
    + +

    Multiple user accounts

    + +

    If you are working with a team, you can set up multiple user accounts to +access different parts of your Developer Console. The first account registered +is the account owner, with full access to all parts of the Console. The +owner can add user accounts and manage what parts of the Console they +have access to. For example, an owner can grant users access to publishing and +app configuration, but not access to financial reports.

    + +

    Linking your Merchant Account

    + +

    If you want to sell apps or in-app products, you can link your Google +Checkout Merchant account to your developer profile. Google Play uses the linked +Checkout account for financial and tax identification and monthly payouts of +sales.

    + +
    +
    + +
    +

    Product details page: Lets you upload your +graphic assets, description, support information, and other information to +create the product details page for a specific app.

    +
    + +

    Your product and listing details

    + +

    The Developer Console lets you set up a colorful storefront page for your app +called the product details page. Your product details page is the home +for your app in Google Play — it's the page users see on their mobile +phones or on the web when they want to learn about your app and download it. +

    + +

    You can upload custom brand assets, screen shots, and videos to highlight +what's great about your app, and you can provide a localized description, add +notes about the latest version, and more. You can update your store listing at +any time, even if you don’t have a new version of your application.

    + +

    Uploading and publishing

    + +

    From the Developer Console you can quickly upload a release-ready APK and +publish it when you're ready. The app is a draft until you publish it, +at which time Google Play makes your product details page and app available to +users. You can unpublish the app at any time.

    + +

    Distribution Controls

    + +

    In the Developer Console you can manage what countries and territories the +app is distributed to and, for some countries, you can choose what carriers you +want to target.

    + +

    You can also see the list of devices that your app is currently available to, +based on any distribution rules declared in its manifest file.

    + +

    Selling and pricing your Products

    + +

    The Developer Console gives you tools to set prices for your apps and in-app +products. Your app can either be free to download or priced (charged before +download).

    + + + +
      +
    • If you publish your app as free, it must +remain free. Free apps can be downloaded by any users in Google +Play.
    • +
    • If you publish it as priced, you can change it to free, Priced apps can be +purchased and downloaded only from .
    • +
    + +

    In addition, you can sell in-app products and subscriptions in your app, +whether it is free or priced. You can set prices separately for priced apps, +in-app products, and subscriptions.

    + +

    If you are selling a priced app or in-app products or subscriptions, the +Developer Console lets you set prices in a large number of different currencies. +When users around the world visit your product details page, they see the price +of your app in their own currency. For most countries, the price you set is the +final price charged to users, inclusive of taxes.

    + +

    To help you manage your prices, the Developer Console provides an autofill +capability that uses recent exchange rates to populate the prices in all +supported currencies. You can change prices for apps and in-app products at any +time, just by saving changes in the Develoer Console.

    + +

    In-app Billing

    + + + +

    In-app Billing is a Google Play service that lets you monetize your apps in more ways by selling in-app products and subscriptions. In-app products are one-time purchases, while subscriptions are recurring charges on an monthly or annual basis.

    + +

    From the Developer Console you can create product lists for in-app +products and subscriptions, set prices, and publish.

    + +
    +
    + +
    +

    User +reviews page: Gives you access to user reviews for a specific app. +You can filter reviews in a number of ways to locate issues more easily +and support your customers more effectively.

    +
    + +

    User reviews and error reports

    + +

    Google Play makes it easy for users to submit reviews of your app for the +benefit of other users. The reviews are also extremely important to you, since +they give you usability feedback, support requests, and important functionality +issues direct from your customers.

    + +

    The Developer console also lets you see error reports, with stack trace and +other data, submitted automatically from Android devices, for debugging and +improving your app.

    + +

    App statistics

    + +

    The Developer Console gives you detailed statistics on the install +performance of your app.

    + +

    You can view installations of your app measured by unique users, as well as +by unique devices. For user installations, you can view active installs, total +installs, and daily installs and uninstalls. For devices, you can see active +installs as well as daily installs, uninstalls, and upgrades.

    + +

    You can zoom into the installation numbers along several dimensions, +including Android platform version, device, country, language, app version, and +carrier (mobile operator). You can see the installation data for each dimension +on a timeline charts.

    + +

    At a glance, these charts highlight your app’s installation peaks and +longer-term trends, which you can correlate to promotions, app improvements, or +other factors. You can even focus in on data inside a dimension by adding +specific points (such as individual platform versions or languages) to the +timeline.

    + +
    +
    + +
    +

    App +installation statistics page: Shows you a variety of statistics about a +specific app's installation performance over time.

    +
    diff --git a/docs/html/distribute/googleplay/publish/index.jd b/docs/html/distribute/googleplay/publish/index.jd new file mode 100644 index 000000000000..5a5eaf23f44e --- /dev/null +++ b/docs/html/distribute/googleplay/publish/index.jd @@ -0,0 +1,23 @@ +page.title=Publishing on Google Play +header.hide=1 +footer.hide=1 +page.metaDescription=Get started publishing apps on Google Play. + +@jd:body + +
    + +
    + +
    +

    Upload apps, build your product pages, configure prices and + distribution, and publish. You can manage all phases of publishing + on Google Play through the Developer Console, from any web browser.

    + +

    Get started

    +
    + + + + + diff --git a/docs/html/distribute/googleplay/publish/preparing.jd b/docs/html/distribute/googleplay/publish/preparing.jd new file mode 100644 index 000000000000..e50d3bfb04d6 --- /dev/null +++ b/docs/html/distribute/googleplay/publish/preparing.jd @@ -0,0 +1,570 @@ +page.title=Publishing Checklist for Google Play +@jd:body + + + + +

    Before you publish your app on Google Play and distribute it to users, you +need to get the app ready, test it, and prepare your promotional materials.

    + +

    This document helps you understand the publishing process and get ready for a +successful product launch on Google Play. It summarizes some of the +tasks you'll need to complete before publishing your app on Google Play, such as +creating a signed, release-ready APK, understanding the requirements of the app, +and creating the product page and graphic assets for your app.

    + +

    The preparation and publishing tasks are numbered to give you a rough idea of +sequence. However, you can handle the tasks in any sequence that works for you +or you can skip steps as appropriate.

    + +

    As you move toward publishing, a variety of support resources are available to +you. Relevant links are provided in each step.

    + + +

    1. Understand the publishing process

    + +

    Before you begin the steps in this checklist, you should take a moment to +read and understand the overall publishing workflow and become familiar with how +the process works. In particular, you or your development team will need to +prepare your app for release using a process common to all Android apps. +The Publishing +Workflow documents provide the details on how publishing works and how to +get an APK ready for release.

    + +

    Once you are familiar with publishing in general, read this document to +understand the issues that you should consider when publishing an app on Google +Play.

    + + + + + +

    Related resources:

    + +
    + +

    2. Understand Google Play policies and agreements

    + +

    Make sure that you understand and follow the Google Play program policies +that you accepted when registering. Google Play actively enforces the policies +and any violations can lead to suspension of your app or, for repeated +violations, termination of your developer account.

    + + + + + +

    Related resources:

    + +
    + +

    3. Determine your app's content rating

    + +

    Google Play requires you to set a content rating for your app, which informs +Google Play users of its maturity level. Before you publish, you should confirm +what rating level you want to use. The available content rating levels are:

    + +
      +
    • Everyone
    • +
    • Low maturity
    • +
    • Medium maturity
    • +
    • High maturity
    • +
    + +

    On their Android devices, Android users can set the desired maturity level +for browsing. Google Play then filters apps based on the setting, so the content +rating you select can affect the app's distribution to users. You can assign (or +change) the content rating for your app in the Developer Console, so no changes +are required in your app binary.

    + + + + + +

    Related resources:

    + +
    + +

    4. Determine country distribution

    + +

    Google Play lets you control what countries and territories your app is +distributed to. For widest reach and the largest potential customer base, you +would normally want to distribute to all available countries and territories. +However, because of business needs, app requirements, or launch dependencies, +you might want to exclude one or more countries from your distribution.

    + +

    It's important to determine the exact country distribution early, because it +can affect:

    +
      +
    • The need for localized resources in the app
    • +
    • The need for a localized app description in the Developer Console
    • +
    • Legal requirements for the app that may be specific to certain +countries
    • +
    • Time zone support, local pricing, and so on.
    • +
    + +

    With your country targeting in mind, you should assess what +your localization needs are, both in your app and in its Google Play listing +details, and start the work of localization well in advance of your +launch target date.

    + + + + + +

    Related resources:

    + +
    + +

    5. Confirm the app's overall size

    + +

    The overall size of your app can affect its design and how you publish it on +Google Play. Currently, the maximum size for an APK published on Google Play is +50 MB. If your app exceeds that size, or if you want to offer a +secondary download, you can use APK Expansion Files, +which Google Play will host for free on its server infrastructure and +automatically handle the download to devices.

    + +
      +
    • The maximum size for an APK published on Google Play is 50 MB.
    • +
    • You can use up to two (2) APK Expansion Files, each up to 2 GB in size, for +each APK.
    • +
    + +

    Using APK Expansion files is a convenient, cost-effective method of +distributing large apps. However, the use of APK Expansion Files requires some +changes in your app binary, so you will need to make those changes before +creating your release-ready APK.

    + + + + + +

    Related resources:

    +
      +
    • APK Expansion Files — Developer documentation describing APK Expansion Files and how to support them in your app.
    • +
    +
    + +

    6. Confirm the app's platform and screen compatibility ranges

    + +

    Before publishing, it's important to make sure that your app is designed to +run properly on the Android platform versions and device screen sizes that you +want to target. + +

    From an app-compatibility perspective, Android platform versions are defined +by API level. You should +confirm the minimum version that your app is compatible with (<minSdkVersion>), +as that will affect its distribution to Android +devices once it is published.

    + +

    For screen sizes, you should confirm that the app runs properly and looks +good on the range of screen sizes and densities that you want to support. You +should confirm the minimum screen-size and density support that your app +declares (<supports-screens>), +since that can affect its distribution to +Android devices once it is published.

    + +

    To get a better understanding of the current device penetration of Android +platform versions and screen sizes across all Android devices, see the Device Dashboard +charts.

    + + + + + +

    Related resources:

    +
      +
    • Device Dashboard — A chart showing global percentages of devices by Android version, screen size, and level of OpenGL ES support.
    • +
    • Android API Levels — A definition of API Levels and a list of which Android platform versions they are associated with.
    • +
    +
    + +

    7. Decide whether your app will be free or priced

    + +

    On Google Play, you can publish apps as free to download or priced. Free apps +can be downloaded by any Android user in Google Play. +Paid apps can be downloaded only by users who have registered a form of payment +in Google Play, such as a credit card or Direct Carrier Billing.

    + +

    Deciding whether you app will be free or paid is important because, on Google +Play, free apps must remain free.

    + +
      +
    • Once you publish your app as a free app, you cannot ever change it to being +a priced app. However, you can still sell in-app products and +subscriptions through Google Play's In-app Billing service.
    • +
    • If you publish your app as a priced app, you can change +it at any time to being a free app (but cannot then change it back to +priced). You can also sell in-app products and subscriptions.
    • +
    + +

    If your app is be priced, or if you'll be selling in-app products, +you need set up a Checkout Merchant Account before you can publish.

    + + + + + +

    Related resources:

    +
      +
    • In-app Billing — Developer introduction to Google Play In-app Billing.
    • +
    +
    + +

    8. Consider using In-app Billing

    + +

    Google Play In-app +Billing lets you sell digital content in your applications. You can use the +service to sell a wide range of content, including downloadable content such as +media files or photos, and virtual content such as game levels or potions. +In-app Billing service lets you sell one-time purchases and subscriptions from +inside your app. This can help you to monetize the app over its installed +lifetime.

    + +

    If your are looking for more ways to monetize your app and build engagement, +you should consider In-app Billing. The service has become very popular with +both users and developers. To use In-app Billing, you need to make changes to +your app binary, so you will need to complete and test your implementation +before creating your release-ready APK.

    + + + + + +

    Related resources:

    +
      +
    • In-app Billing — Developer documentation describing In-app Billing and how to support it in your app.
    • +
    +
    + +

    9. Set prices for your products

    + +

    If your app is priced or you will sell in-app products, Google Play lets you +set prices for your products in a variety of currencies, for users in markets +around the world. You can set prices individually in different currencies, so +you have the flexibility to adjust your price according to market conditions and +exchange rates.

    + +

    Before you publish, consider how you will price your products +and what your prices will be in various currencies. Later, you can set prices +in all available currencies through the Developer Console.

    + + + + + +

    Related resources:

    + +
    + +

    10. Start localization

    + +

    With your country targeting in mind, it's a good idea to assess your localization +needs and start the work of localizing well in advance of your target +launch date.

    + +

    There are at least two aspects of localization to consider:

    + +
      +
    • Localizing the strings, images, and other resources in your app
    • +
    • Localizing you app's store listing details on Google Play
    • +
    + +

    To get started localizing your app, work with your development team to extract +any resource or coded strings for translation. Also identify images, icons, or +other assets that should be language- or locale-specific. Hand these off to +a translator.

    + +

    To localize your store listing, first create and finalize your app title, description, +and promotional text. Collect and send all of these for localization. You can optionally +translate the "Recent Changes" text for app updates as well.

    + +

    When your translations are complete, move them into your app resources as needed and test +that they are loaded properly. Save your app's translated listing details for later, +when you upload assets and configure your product details.

    + + + + + +

    Related resources:

    +
      +
    • Localization — How to supply localized resources in your app.
    • +
    +
    + +

    11. Prepare promotional graphics

    + +

    When you publish on Google Play, you can supply a variety of high-quality +graphic assets to showcase your app or brand. After you publish, these appear on +your product details page, in store listings and search results, and elsewhere. +These graphic assets are key parts of a successful product details page that +attracts and engages users, so you should consider having a professional produce +them for you. Screen shots and videos are also very important, because they show +what your app looks like, how it's used or played, and what makes it different. + +

    All of your graphic assets should be designed so that they are easy to see +and highlight your app or brand in a colorful, interesting way. The assets +should reference the same logo and icon as users will actually find in the All +Apps launcher once they have downloaded the app. Your graphic assets should also +fit in well with the graphic assets of other apps published by you, which will +be also be displayed to users on your product details page.

    + +

    Because these assets are so important, you should get started on them well in +advance of your target publishing date.

    + + + + + +

    Related resources:

    + +
    + +

    12. Build and upload the release-ready APK

    + +

    When you are satisfied that your app meets your UI, compatibility, and +quality requirements, you can build the release-ready version of the app. The +release-ready APK is what you you will upload to the Developer Console and +distribute to users. + +

    The process for preparing a release-ready APK is the same for all apps, +regardless of how they are distributed. Generally the process includes basic code cleanup +and optimization, building and signing with your release key, and final testing. +When you are finished preparing your application for release, you'll have a signed +APK file that you can upload to the Developer Console for distribution to +users.

    + +

    For complete details on how to create a release-ready version of your app, +read Preparing for +Release.

    + +

    Once you have the release-ready APK in hand, you can upload it to +the Developer Console. If necessary, you can replace the APK with a more +recent version before publishing.

    + + + + + +

    Related resources:

    +
      +
    • Preparing for Release — Essential information for preparing and packaging your app properly for distribution.
    • +
    +
    + +

    13. Complete the app's product details

    + +

    On Google Play, your app's product information is shown to users on its +product details page, the page that users visit to learn more about your app and +the page from which they will decide to purchase or download your app, on their +Android devices or on the web.

    + +

    Google Play gives you a variety of ways to promote your app and engage with +users on your product details page, from colorful graphics, screenshots, and +videos to localized descriptions, release details, and links to your other apps. +As you prepare to publish your app, make sure that you take advantage of all +that your product details page can offer, making your app as compelling as +possible to users.

    + +

    You should begin planning your product page in advance of your target launch +date, arranging for localized description, high-quality graphic assets, +screenshots and video, and so on.

    + +

    As you get near your target publishing date, you should become familiar with +all the fields, options, and assets associated with the product details configuration +page in the Developer Console. As you collect the information and assets for the +page, make sure that you can enter or upload it to the Developer Console, until +the page is complete and ready for publishing.

    + + + + + +

    Related resources:

    + +
    + +

    14. Use Google Play badges and links in your promotional +campaigns

    + +

    Google Play badges give you an officially branded way of promoting your app +to Android users. Use the Google Play Badge +generator to quickly create badges to link users to your products from web +pages, ads, reviews, and more. You can also use special link formats +to link directly to your product details page, to a list of your products, or to +search results.

    + +

    To help your app get traction after launch, it's strongly recommended that you support +launch with a promotional campaign that announces your product through many channels as +possible, in as many countries as possible. For example, you can promote the launch +using ad placements, social network or blog posts, video and other media, interviews +and reviews, or any other channel available.

    + + + + + +

    Related resources:

    + +
    + +

    15. Final checks and publishing

    + +

    When you think you are ready to publish, sign in to the Developer Console and take a few moments for a few +final checks:

    + +

    Make sure that:

    + +
      +
    • Your developer profile has the correct information and is linked to the proper Google Checkout Merchant account (if you are selling products).
    • +
    • You have the right version of the app uploaded.
    • +
    • All parts of your Product Details are ready, including all graphic assets, screenshots, video, localized descriptions, and so on.
    • +
    • You have set your app's pricing to free or priced.
    • +
    • You have set country (and carrier) targeting and priced your products (if appropriate) in buyer currencies
    • +
    • "Compatible devices" shows that your app is actually reaching the devices that you are targeting. If not, you should check with your development team on the apps requirements and filtering rules.
    • +
    • You have provided the correct link to your web site and the correct support email address.
    • +
    • Your app does not violate content policy guidelines.
    • +
    • You have acknowledged that your app meets the guidelines for Android content on Google Play and also US export laws.
    • +
    + +

    Your app is now ready to publish!

    + +

    If you are releasing an update, make sure to read the requirements for publishing updates.

    + +

    When you are ready, click the Publish button in the Developer Console. Within a few hours, your app will become available to users and your product page will be appear in Google Play for browsing, searching, or linking from your promotional campaigns.

    + + + + + +

    Related resources:

    +
      +
    • Google Play Developer Program Policies — Guidelines for what is acceptable conent in Google Play. Please read and understand the policies before publishing.
    • +
    • Updates — Requirements for app updates in Google Play.
    • +
    • Developer Support — Support resources that you can use to find answers and report issues.
    • +
    +
    + + +

    16. Support users after launch

    + +

    After you publish an app or an app update, it's crucial for you to support +your customers. Prompt and courteous support can provide a better experience for +users that results in better ratings and more positive reviews for your +products. Users are likely to be more engaged with your app and recommend it if +you are responsive to their needs and feedback. This is especially true after +publishing if you are using a coordinated promotional campaign.

    + +

    There are a number of ways that you can keep in touch with users and offer +them support. The most fundamental is to provide your support email +address on your product details page. Beyond that, you can provide support +in any way you choose, such as a forum, mailing list or a Google+ page. The +Google Play team does provide user support for downloading, installing and +payments issues, but issues that fall outside of these topics will fall under +your domain. Examples of issues you can support include: feature requests, +questions about using the app and questions about compatibility settings.

    + +

    After publishing, plan to:

    +
      +
    • Check your ratings and reviews frequently on your app's product details +page. Watch for recurring issues that could signal bugs or other issues.
    • +
    • Be mindful of new Android platform version launches, as compatibility +settings for your apps might need to be updated.
    • +
    • Put a link to your support resources on your web site and set up any other +support such as forums.
    • +
    • Provide an appropriate support email address on your product details page +and respond to users when they take the time to email you.
    • +
    • Beyond the automatic refund window offered by Google Play, be generous with +your own refund policy, as satisfied users will be more likely to purchase in +the future.
    • +
    • Acknowledge and fix issues in your app. It helps to be transparent and +list known issues on your product details page proactively.
    • +
    • Publish updates as frequently as you are able, without sacrificing quality +or annoying users with too-frequent updates.
    • +
    • With each update, make sure to provide a summary of what's changed. You can +enter this information in the Developer Console. Users will read it and +appreciate that you are serious about improving the quality of your app.
    • +
    + + + + + +

    Related resources:

    +
      +
    • Supporting your users + — Help Center document describing options for supporting users.
    • +
    • In-app Billing — Help Center document describing how to correctly set up In-app Billing.
    • +
    • Issuing Refunds — -- Help Center document describing how to issue refunds.
    • +
    +
    + + + diff --git a/docs/html/distribute/googleplay/publish/register.jd b/docs/html/distribute/googleplay/publish/register.jd new file mode 100644 index 000000000000..7ca66969e733 --- /dev/null +++ b/docs/html/distribute/googleplay/publish/register.jd @@ -0,0 +1,72 @@ +page.title=Get Started with Publishing +@jd:body + + + +

    You can set up to start publishing on Google Play in only a few minutes. Here's how you do it:

    + +
      +
    • Register for a Google Play publisher account
    • +
    • If you will sell apps, set up a Google Checkout Merchant Account
    • +
    • Explore the Google Play Android Developer Console and learn about the tools for publishing
    • +
    + + +

    Register for a publisher account

    + +

    The first step is to visit the Google Play Android Developer Console and register for a publisher account.

    + +

    Here's what you will do during registration:

    + + + + +
      +
    1. Visit the Google Play Android Developer Console at https://play.google.com/apps/publish/. +
    2. Enter basic information about your developer identity — developer name, email address, and so on. You can modify this information later.
    3. +
    4. Read and accept the Developer Distribution Agreement that applies to your country or region. Note that apps and store listings that you publish on Google Play must comply with the Developer Program Policies and US export law,
    5. +
    6. Pay a $25 USD registration fee using Google Checkout. If you don't have a Google Checkout account, you can quickly set one up during the process.
    7. +
    + +

    When your registration is verified, you’ll be notified at the email address you specified during registration.

    + +

    Set up a Google Checkout Merchant account

    + +

    If you want to sell products on Google Play — priced apps, in-app products, or subscriptions — you will also need to set up a Google Checkout Merchant Account. You can do that at any time, but make sure to first review the list of merchant countries.

    + +

    To set up a Merchant account from the Developer Console:

    + +
      +
    1. Sign in to your Google Play Android Developer Console at https://play.google.com/apps/publish/ +
    2. Click on the "Edit profile" link. +
    3. Select "Setup a Merchant Account at Google Checkout".
    4. +
    + +

    This will take you to the Google Checkout site to sign up as a Merchant; you'll need to have information about your business handy to complete this step.

    + +

    Explore the Developer Console

    +

    When your registration is verified, you can sign in to your Android Developer Console, which will be the home for your app publishing operations and tools on Google Play.

    diff --git a/docs/html/distribute/googleplay/strategies/app-quality.jd b/docs/html/distribute/googleplay/strategies/app-quality.jd new file mode 100644 index 000000000000..26d71d751bf0 --- /dev/null +++ b/docs/html/distribute/googleplay/strategies/app-quality.jd @@ -0,0 +1,116 @@ +page.title=Improving App Quality +@jd:body + + + +

    +With thousands of new apps being published in Google Play every week, it's important to look for any available way to get the most visibility and the highest ratings possible. One way of improving your app's visibility in the ecosystem is by deploying well-targeted mobile advertising campaigns and cross-app promotions. Another time-tested method of fueling the impression-install-ranking cycle is simply: improve the product!

    +

    +A better app can go a very long way: a higher quality app will translate to higher user ratings, generally better rankings, more downloads, and higher retention (longer install periods). High-quality apps also have a much higher likelihood of getting some unanticipated positive publicity such as being featured in Google Play or getting social media buzz.

    +

    +The upside to having a higher-quality app is obvious. However, it's not always clear how to make an app "better". The path to improving app quality isn't always well-lit. The term "quality" — along with "polish" and "fit and finish" — aren't always well-defined. Here we'll light the path by looking at some of the key factors in app quality and ways of improving your app along these dimensions.

    + +

    Listen to Your Users

    +

    +Most ways of measuring the "success" of an app are dependent on user behavior. User-related metrics such as number of downloads, daily active installs, retention rates, and so on highlight the importance of users. If you aren't doing so already, it's a good idea to start thinking of your app's quality as it relates to your users.

    +

    +The most obvious way to listen to users is by reading and addressing comments on your app in Google Play. Although the comments aren't always productive or constructive, some will provide valuable insight on aspects of your app that you may not have consciously considered before. It's important to remember that users have the opportunity to change their ratings and comments about an app as much as they'd like.

    +

    +One way to reach users and help them address their concerns is to set up your own support and discussion destination(s). There are some great support tools out there that can put you in touch with your users directly such as Google Groups, Zoho Discussions, getsatisfaction.com and uservoice.com. Once you get set up with such a tool, make sure to fill in the support link in your Google Play product details page — users do click through to these.

    +

    +Another way to better listen to your users is by having a public beta or trusted tester program. It's crucial to have some amount of real user testing before releasing something in Google Play. Fortunately, you can distribute your apps to users outside of Google Play via a website; this website can require a login or be publicly accessible — it's entirely up to you. Take advantage of this opportunity by offering your next planned update to some early adopters, before submitting to Google Play. You'll be surprised by how many little, yet impactful, improvements can come out of crowd-sourced, real-user testing.

    + + +

    Improve Stability and Eliminate Bugs

    + +

    +The effect of overall app stability of ratings and user satisfaction is very well-known and there are many tools and techniques for testing and profiling your app on different devices and user scenarios.

    +

    +One noteworthy and yet relatively underused tool for catching stability issues such as crashes is the UI/Application Exerciser Monkey (Monkey). Monkey will send random UI events to your app's activities, allowing you to trigger user flows that can uncover stability problems.

    +

    +Also, with the Google error-reporting features built into most Android devices, users now have a way to report application crashes to developers. The error reports show up in aggregate in the Google Play Developer Console. Make sure to read these reports often and act on them appropriately.

    +

    +Last, keep an external bug and feature request tracker and let users know how to find it. This will enable them to engage with the app at a closer level, by following features and bugs that affect them. User frustration with app problems can be effectively managed with diligent issue tracking and communication. Some of the community support tools listed above offer issue tracking features, and if your project is open source, most popular repository hosting sites such as Google Code and GitHub will offer this as well.

    + +

    Improve UI Responsiveness

    +

    +One sure-fire way to lose your users is to give them a slow, unresponsive UI. Research has shown that speed matters... for any interface, be it desktop, web, or mobile. In fact, the importance of speed is amplified on mobile devices since users often need their information on the go and in a hurry.

    +

    +You can improve your apps's UI responsiveness by moving long-running operations off the main thread to worker threads. Android offers built-in debugging facilities such as StrictMode for analyzing your app's performance and activities on the main thread. You can see more recommendations in Writing Zippy Android Apps, a developer session from Google I/O 2010,

    + + + +

    +A great way to improve UI performance is to minimize the complexity of your layouts. If you open up hierarchyviewer and see that your layouts are more than 5 levels deep, it may be time to simplify your layout. Consider refactoring those deeply nested LinearLayouts into RelativeLayout. The impact of View objects is cumulative — each one costs about 1 to 2 KB of memory, so large view hierarchies can be a recipe for disaster, causing frequent VM garbage collection passes which block the main (UI) thread. You can learn more in World of ListView, another session at Google I/O.

    +

    +Lastly, pointed out in the blog post Traceview War Story, tools like traceview and ddms can be your best friends in improving your app by profiling method calls and monitoring VM memory allocations, respectively.

    + + +

    Improve Usability

    +

    +In usability and in app design too, you should listen carefully to your users. Ask a handful of real Android device users (friends, family, etc.) to try out your app and observe them as they interact with it. Look for cases where they get confused, are unsure of how to proceed, or are surprised by certain behaviors. Minimize these cases by rethinking some of the interactions in your app, perhaps working in some of the user interface patterns the Android UI team discussed at Google I/O.

    +

    +In the same vein, two problems that can plague some Android user interfaces are small tap targets and excessively small font sizes. These are generally easy to fix and can make a big impact on usability and user satisfaction. As a general rule, optimize for ease of use and legibility, while minimizing, or at least carefully balancing, information density.

    + + + +

    +Another way to incrementally improve usability, based on real-world data, is to implement Analytics throughout your app to log usage of particular sections. Consider demoting infrequently used sections to the overflow menu in the Action bar, or removing them altogether. For often-used sections and UI elements, make sure they're immediately obvious and easily accessible in your app's UI so that users can get to them quickly.

    +

    +Lastly, usability is an extensive and well-documented subject, with close ties to interface design, cognitive science, and other disciplines.

    + +

    Professional Appearance and Aesthetics

    +

    +There's no substitute for a real user interface designer — ideally one who's well-versed in mobile and Android, and ideally handy with both interaction and visual design. One popular venue to post openings for designers is jobs.smashingmagazine.com, and leveraging social connections on Twitter and LinkedIn can surface great talent.

    +

    +If you don't have the luxury of working with a UI designer, there are some ways in which you can improve your app's appearance yourself. First, get familiar with Adobe Photoshop, Adobe Fireworks, or some other raster image editing tool. Mastering the art of the pixel in these apps takes time, but honing this skill can help build polish across your interface designs. Also, master the resources framework by studying the framework UI assets and layouts and reading through the new resources documentation. Techniques such as 9-patches and resource directory qualifiers are somewhat unique to Android, and are crucial in building flexible yet aesthetic UIs.

    +

    +Before you get too far in designing your app and writing the code, make sure to visit the Android Design site and learn about the vision, the building blocks, and the tools of designing beautiful and inspiring user interfaces.

    + +

    Deliver the Right Set of Features

    +

    +Having the right set of features in your app is important. It's often easy to fall into the trap of feature-creep, building as much functionality into your app as possible. Providing instant gratification by immediately showing the most important or relevant information is crucial on mobile devices. Providing too much information can be as frustrating (or even more so) than not providing enough of it.

    +

    +Again, listen to your users by collecting and responding to feature requests. Be careful, though, to take feature requests with a grain of salt. Requests can be very useful in aggregate, to get a sense of what kinds of functionality you should be working on, but not every feature request needs to be implemented.

    + +

    Integrate with the System and Third-Party apps

    +

    +A great way to deliver a delightful user experience is to integrate tightly with the operating system. Features like Home screen widgets, rich notifications, global search integration, and {@link android.widget.QuickContactBadge Quick Contacts} are fairly low-hanging fruit in this regard.

    + +

    For some app categories, basic features like home screen widgets are par for the course. Not including them is a sure-fire way to tarnish an otherwise positive user experience. Some apps can achieve even tighter OS integration with Android's contacts, accounts, and sync APIs.

    +

    +Third-party integrations can provide even more user delight and give the user a feeling of device cohesiveness. It's also a really nice way of adding functionality to your app without writing any extra code (by leveraging other apps' functionalities). For example, if you're creating a camera app, you can allow users to edit their photos in Photoshop Express before saving them to their collection, if they have that third-party application installed. More information on this subject is available in the class, Interacting with Other Apps.

    + +

    Pay Attention to Details

    +

    +One particular detail to pay close attention to is your app's icon quality and consistency. Make sure your app icons (especially your launcher icon) are crisp and pixel-perfect at all resolutions, and follow the icon guidelines as much as possible. If you're having trouble or don't have the resources to design the icons yourself, consider using the new Android Asset Studio tool to generate a set.

    diff --git a/docs/html/distribute/googleplay/strategies/featuring.jd b/docs/html/distribute/googleplay/strategies/featuring.jd new file mode 100644 index 000000000000..4c4e67e1dc4f --- /dev/null +++ b/docs/html/distribute/googleplay/strategies/featuring.jd @@ -0,0 +1,4 @@ +page.title=Preparing for Featuring +@jd:body + +

    Placeholder...

    \ No newline at end of file diff --git a/docs/html/distribute/googleplay/strategies/index.jd b/docs/html/distribute/googleplay/strategies/index.jd new file mode 100644 index 000000000000..3794bbfcac2a --- /dev/null +++ b/docs/html/distribute/googleplay/strategies/index.jd @@ -0,0 +1,33 @@ +page.title=Success Strategies +page.metaDescription= +header.hide=1 +footer.hide=1 + +@jd:body + + + + + +
    +
    + Strategies for building ratings, improving reviews, monetizing, and more. +

    + Preparing for Featuring +
    + + + + +
    \ No newline at end of file diff --git a/docs/html/distribute/index.jd b/docs/html/distribute/index.jd new file mode 100644 index 000000000000..ffdeb2f26706 --- /dev/null +++ b/docs/html/distribute/index.jd @@ -0,0 +1,39 @@ +page.title=Distribute Apps +header.hide=1 + +@jd:body + + + +
    + +
    + +
    + +
    +
    +

    Introducing Google Play

    +

    The most visited store in the world for Android apps. Cloud-connected and always synced, it's never been easier for users to find and download your apps.

    + +

    Watch a video

    +
    +
    +
    +
      +
    • Growth Engine
      + A billion downloads a month and growing. Get your apps in front of millions of users at Google's scale.
      + Read More › +
    • Build Your Business
      Sell your app in over 130 countries. Flexible monetization options with in-app purchase, subscriptions, and more.
      + Read More ›
    • +
    • Distribution Control
      Deliver your apps to the users you want, on the devices you want, on your schedule.
      + Read More ›
    • +
    +
    + + + + + + + diff --git a/docs/html/distribute/open.jd b/docs/html/distribute/open.jd new file mode 100644 index 000000000000..edcfc9c8afe2 --- /dev/null +++ b/docs/html/distribute/open.jd @@ -0,0 +1,107 @@ +page.title=Open Distribution +@jd:body + +

    As an open platform, Android offers choice. You +distribute your Android apps to users in any way you want, using any +distribution approach or combination of approaches that meets your needs. +From publishing in an app marketplace to serving your apps from a web site or +emailing them directly users, you are never locked into any +particular distribution platform.

    + +

    The process for building and packaging your app for distribution is the same, +regardless of how you will distribute your app. This saves you time and lets you +automate parts of the process as needed. You can read Preparing +for Release for more information.

    + +

    The sections below highlight some of the alternatives for distributing +your apps to users.

    + +

    Distributing through an App Marketplace

    + +

    Usually, to reach the broadest possible audience, you would distribute your +apps through a marketplace, such as Google Play.

    + +

    Google Play is the premier marketplace for Android apps and is particularly +useful if you want to distribute your applications to a large global audience. +However, you can distribute your apps through any app marketplace you want or +you can use multiple marketplaces.

    + +

    Distributing your application through email

    + +
    + Screenshot showing the graphical user interface users see when you send them an app +

    + Figure 1. Users can simply click Install when you send them + an application via email. +

    +
    + +

    The easiest and quickest way to release your application is to send it to users through +email. To do this, you prepare your application for release and then attach it to an email +and send it to a user. When users open your email message on their Android-powered device, +the Android system will recognize the APK and display an Install Now +button in the email message (see figure 1). Users can install your application by touching the +button.

    + +

    Note: The Install Now button +shown in Figure 1 appears only if users have configured their device to allow +installation from unknown sources and have opened your +email with the native Gmail application.

    + +

    Distributing applications through email is convenient if you are sending your application to +only a few trusted users, but it provides few protections from piracy and unauthorized +distribution; that is, anyone you send your application to can simply forward it to someone else.

    + +

    Distributing through a web site

    + +

    If you do not want to release your app on a marketplace like Google Play, you +can make the app available for download on your own website or server, including +on a private or enterprise server. To do this, you must first prepare your +application for release in the normal way. Then all you need to do is host the +release-ready APK file on your website and provide a download link to users. +

    + +

    When users browse to the download link from their Android-powered devices, +the file is downloaded and Android system automatically starts installing it on +the device. However, the installation process will start automatically only if +users have configured their Settings to allow the installation of apps from +unknown sources.

    + +

    Although it is relatively easy to release your application on your own +website, it can be inefficient. For example, if you want to monetize your +application you will have to process and track all financial transactions +yourself and you will not be able to use Google Play's In-app Billing service +to sell in-app products. In addition, you will not be able to use the Licensing service to +help prevent unauthorized installation and use of your application.

    + + +

    User Opt-In for Apps from Unknown Sources

    + +
    + Screenshot showing the setting for accepting download and install of
+       apps from unknown sources. +

    + Figure 2. Users must enable the Unknown sources + setting before they can install apps not downloaded from Google Play. +

    +
    + +

    Android protects users from inadvertent download and install of apps from +locations other than Google Play (which is trusted). It blocks such installs +until the user opts-in Unknown sources in +Settings > Security, shown in Figure 2. To allow +the installation of applications from other sources, users need to enable the +Unknown sources setting on their devices, and they need to make this +configuration change before they download your application to their +devices.

    + +

    Note that some network providers do not allow users to install +applications from unknown sources.

    + + diff --git a/docs/html/favicon-a.ico b/docs/html/favicon-a.ico new file mode 100644 index 000000000000..d8884b792b29 Binary files /dev/null and b/docs/html/favicon-a.ico differ diff --git a/docs/html/favicon.ico b/docs/html/favicon.ico index d8884b792b29..c1076aab60a3 100644 Binary files a/docs/html/favicon.ico and b/docs/html/favicon.ico differ diff --git a/docs/html/guide/appendix/api-levels.jd b/docs/html/guide/appendix/api-levels.jd deleted file mode 100644 index bc7d83b6db1b..000000000000 --- a/docs/html/guide/appendix/api-levels.jd +++ /dev/null @@ -1,421 +0,0 @@ -page.title=Android API Levels -@jd:body - - - -

    As you develop your application on Android, it's useful to understand the -platform's general approach to API change management. It's also important to -understand the API Level identifier and the role it plays in ensuring your -application's compatibility with devices on which it may be installed.

    - -

    The sections below provide information about API Level and how it affects -your applications.

    - -

    For information about how to use the "Filter by API Level" control -available in the API reference documentation, see -Filtering the documentation at the -end of this document.

    - -

    What is API Level?

    - -

    API Level is an integer value that uniquely identifies the framework API -revision offered by a version of the Android platform.

    - -

    The Android platform provides a framework API that applications can use to -interact with the underlying Android system. The framework API consists of:

    - -
      -
    • A core set of packages and classes
    • -
    • A set of XML elements and attributes for declaring a manifest file
    • -
    • A set of XML elements and attributes for declaring and accessing resources
    • -
    • A set of Intents
    • -
    • A set of permissions that applications can request, as well as permission -enforcements included in the system
    • -
    - -

    Each successive version of the Android platform can include updates to the -Android application framework API that it delivers.

    - -

    Updates to the framework API are designed so that the new API remains -compatible with earlier versions of the API. That is, most changes in the API -are additive and introduce new or replacement functionality. As parts of the API -are upgraded, the older replaced parts are deprecated but are not removed, so -that existing applications can still use them. In a very small number of cases, -parts of the API may be modified or removed, although typically such changes are -only needed to ensure API robustness and application or system security. All -other API parts from earlier revisions are carried forward without -modification.

    - -

    The framework API that an Android platform delivers is specified using an -integer identifier called "API Level". Each Android platform version supports -exactly one API Level, although support is implicit for all earlier API Levels -(down to API Level 1). The initial release of the Android platform provided -API Level 1 and subsequent releases have incremented the API Level.

    - -

    The following table specifies the API Level supported by each version of the -Android platform.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Platform VersionAPI LevelVERSION_CODENotes
    Android 4.0.315{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1}Platform -Highlights
    Android 4.0, 4.0.1, 4.0.214{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}
    Android 3.213{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2}
    Android 3.1.x12{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR1}Platform Highlights
    Android 3.0.x11{@link android.os.Build.VERSION_CODES#HONEYCOMB}Platform Highlights
    Android 2.3.4
    Android 2.3.3
    10{@link android.os.Build.VERSION_CODES#GINGERBREAD_MR1}Platform Highlights
    Android 2.3.2
    Android 2.3.1
    Android 2.3
    9{@link android.os.Build.VERSION_CODES#GINGERBREAD}
    Android 2.2.x8{@link android.os.Build.VERSION_CODES#FROYO}Platform Highlights
    Android 2.1.x7{@link android.os.Build.VERSION_CODES#ECLAIR_MR1}Platform Highlights
    Android 2.0.16{@link android.os.Build.VERSION_CODES#ECLAIR_0_1}
    Android 2.05{@link android.os.Build.VERSION_CODES#ECLAIR}
    Android 1.64{@link android.os.Build.VERSION_CODES#DONUT}Platform Highlights
    Android 1.53{@link android.os.Build.VERSION_CODES#CUPCAKE}Platform Highlights
    Android 1.12{@link android.os.Build.VERSION_CODES#BASE_1_1}
    Android 1.01{@link android.os.Build.VERSION_CODES#BASE}
    - - -

    Uses of API Level in Android

    - -

    The API Level identifier serves a key role in ensuring the best possible -experience for users and application developers: - -

      -
    • It lets the Android platform describe the maximum framework API revision -that it supports
    • -
    • It lets applications describe the framework API revision that they -require
    • -
    • It lets the system negotiate the installation of applications on the user's -device, such that version-incompatible applications are not installed.
    • -
    - -

    Each Android platform version stores its API Level identifier internally, in -the Android system itself.

    - -

    Applications can use a manifest element provided by the framework API — -<uses-sdk> — to describe the minimum and maximum API -Levels under which they are able to run, as well as the preferred API Level that -they are designed to support. The element offers three key attributes:

    - -
      -
    • android:minSdkVersion — Specifies the minimum API Level -on which the application is able to run. The default value is "1".
    • -
    • android:targetSdkVersion — Specifies the API Level -on which the application is designed to run. In some cases, this allows the -application to use manifest elements or behaviors defined in the target -API Level, rather than being restricted to using only those defined -for the minimum API Level.
    • -
    • android:maxSdkVersion — Specifies the maximum API Level -on which the application is able to run. Important: Please read the <uses-sdk> -documentation before using this attribute.
    • -
    - -

    For example, to specify the minimum system API Level that an application -requires in order to run, the application would include in its manifest a -<uses-sdk> element with a android:minSdkVersion -attribute. The value of android:minSdkVersion would be the integer -corresponding to the API Level of the earliest version of the Android platform -under which the application can run.

    - -

    When the user attempts to install an application, or when revalidating an -appplication after a system update, the Android system first checks the -<uses-sdk> attributes in the application's manifest and -compares the values against its own internal API Level. The system allows the -installation to begin only if these conditions are met:

    - -
      -
    • If a android:minSdkVersion attribute is declared, its value -must be less than or equal to the system's API Level integer. If not declared, -the system assumes that the application requires API Level 1.
    • -
    • If a android:maxSdkVersion attribute is declared, its value -must be equal to or greater than the system's API Level integer. -If not declared, the system assumes that the application -has no maximum API Level. Please read the <uses-sdk> -documentation for more information about how the system handles this attribute.
    • -
    - -

    When declared in an application's manifest, a <uses-sdk> -element might look like this:

    - -
    <manifest>
    -  <uses-sdk android:minSdkVersion="5" />
    -  ...
    -</manifest>
    - -

    The principal reason that an application would declare an API Level in -android:minSdkVersion is to tell the Android system that it is -using APIs that were introduced in the API Level specified. If the -application were to be somehow installed on a platform with a lower API Level, -then it would crash at run-time when it tried to access APIs that don't exist. -The system prevents such an outcome by not allowing the application to be -installed if the lowest API Level it requires is higher than that of the -platform version on the target device.

    - -

    For example, the {@link android.appwidget} package was introduced with API -Level 3. If an application uses that API, it must declare a -android:minSdkVersion attribute with a value of "3". The -application will then be installable on platforms such as Android 1.5 (API Level -3) and Android 1.6 (API Level 4), but not on the Android 1.1 (API Level 2) and -Android 1.0 platforms (API Level 1).

    - -

    For more information about how to specify an application's API Level -requirements, see the <uses-sdk> - section of the manifest file documentation.

    - - -

    Development Considerations

    - -

    The sections below provide information related to API level that you should -consider when developing your application.

    - -

    Application forward compatibility

    - -

    Android applications are generally forward-compatible with new versions of -the Android platform.

    - -

    Because almost all changes to the framework API are additive, an Android -application developed using any given version of the API (as specified by its -API Level) is forward-compatible with later versions of the Android platform and -higher API levels. The application should be able to run on all later versions -of the Android platform, except in isolated cases where the application uses a -part of the API that is later removed for some reason.

    - -

    Forward compatibility is important because many Android-powered devices -receive over-the-air (OTA) system updates. The user may install your -application and use it successfully, then later receive an OTA update to a new -version of the Android platform. Once the update is installed, your application -will run in a new run-time version of the environment, but one that has the API -and system capabilities that your application depends on.

    - -

    In some cases, changes below the API, such those in the underlying -system itself, may affect your application when it is run in the new -environment. For that reason it's important for you, as the application -developer, to understand how the application will look and behave in each system -environment. To help you test your application on various versions of the Android -platform, the Android SDK includes multiple platforms that you can download. -Each platform includes a compatible system image that you can run in an AVD, to -test your application.

    - -

    Application backward compatibility

    - -

    Android applications are not necessarily backward compatible with versions of -the Android platform older than the version against which they were compiled. -

    - -

    Each new version of the Android platform can include new framework APIs, such -as those that give applications access to new platform capabilities or replace -existing API parts. The new APIs are accessible to applications when running on -the new platform and, as mentioned above, also when running on later versions of -the platform, as specified by API Level. Conversely, because earlier versions of -the platform do not include the new APIs, applications that use the new APIs are -unable to run on those platforms.

    - -

    Although it's unlikely that an Android-powered device would be downgraded to -a previous version of the platform, it's important to realize that there are -likely to be many devices in the field that run earlier versions of the -platform. Even among devices that receive OTA updates, some might lag and -might not receive an update for a significant amount of time.

    - -

    Selecting a platform version and API Level

    - -

    When you are developing your application, you will need to choose -the platform version against which you will compile the application. In -general, you should compile your application against the lowest possible -version of the platform that your application can support. - -

    You can determine the lowest possible platform version by compiling the -application against successively lower build targets. After you determine the -lowest version, you should create an AVD using the corresponding platform -version (and API Level) and fully test your application. Make sure to declare a -android:minSdkVersion attribute in the application's manifest and -set its value to the API Level of the platform version.

    - -

    Declaring a minimum API Level

    - -

    If you build an application that uses APIs or system features introduced in -the latest platform version, you should set the -android:minSdkVersion attribute to the API Level of the latest -platform version. This ensures that users will only be able to install your -application if their devices are running a compatible version of the Android -platform. In turn, this ensures that your application can function properly on -their devices.

    - -

    If your application uses APIs introduced in the latest platform version but -does not declare a android:minSdkVersion attribute, then -it will run properly on devices running the latest version of the platform, but -not on devices running earlier versions of the platform. In the latter -case, the application will crash at runtime when it tries to use APIs that don't -exist on the earlier versions.

    - -

    Testing against higher API Levels

    - -

    After compiling your application, you should make sure to test it on the -platform specified in the application's android:minSdkVersion -attribute. To do so, create an AVD that uses the platform version required by -your application. Additionally, to ensure forward-compatibility, you should run -and test the application on all platforms that use a higher API Level than that -used by your application.

    - -

    The Android SDK includes multiple platform versions that you can use, -including the latest version, and provides an updater tool that you can use to -download other platform versions as necessary.

    - -

    To access the updater, use the android command-line tool, -located in the <sdk>/tools directory. You can launch the SDK updater by -executing android sdk. You can -also simply double-click the android.bat (Windows) or android (OS X/Linux) file. -In ADT, you can also access the updater by selecting -Window > Android SDK -Manager.

    - -

    To run your application against different platform versions in the emulator, -create an AVD for each platform version that you want to test. For more -information about AVDs, see Creating and Managing Virtual Devices. If -you are using a physical device for testing, ensure that you know the API Level -of the Android platform it runs. See the table at the top of this document for -a list of platform versions and their API Levels.

    - -

    Using a Provisional API Level

    - -

    In some cases, an "Early Look" Android SDK platform may be available. To let -you begin developing on the platform although the APIs may not be final, the -platform's API Level integer will not be specified. You must instead use the -platform's provisional API Level in your application manifest, in order -to build applications against the platform. A provisional API Level is not an -integer, but a string matching the codename of the unreleased platform version. -The provisional API Level will be specified in the release notes for the Early -Look SDK release notes and is case-sensitive.

    - -

    The use of a provisional API Level is designed to protect developers and -device users from inadvertently publishing or installing applications based on -the Early Look framework API, which may not run properly on actual devices -running the final system image.

    - -

    The provisional API Level will only be valid while using the Early Look SDK -and can only be used to run applications in the emulator. An application using -the provisional API Level can never be installed on an Android device. At the -final release of the platform, you must replace any instances of the provisional -API Level in your application manifest with the final platform's actual API -Level integer.

    - - -

    Filtering the Reference Documentation by API Level

    - -

    Reference documentation pages on the Android Developers site offer a "Filter -by API Level" control in the top-right area of each page. You can use the -control to show documentation only for parts of the API that are actually -accessible to your application, based on the API Level that it specifies in -the android:minSdkVersion attribute of its manifest file.

    - -

    To use filtering, select the checkbox to enable filtering, just below the -page search box. Then set the "Filter by API Level" control to the same API -Level as specified by your application. Notice that APIs introduced in a later -API Level are then grayed out and their content is masked, since they would not -be accessible to your application.

    - -

    Filtering by API Level in the documentation does not provide a view -of what is new or introduced in each API Level — it simply provides a way -to view the entire API associated with a given API Level, while excluding API -elements introduced in later API Levels.

    - -

    If you decide that you don't want to filter the API documentation, just -disable the feature using the checkbox. By default, API Level filtering is -disabled, so that you can view the full framework API, regardless of API Level. -

    - -

    Also note that the reference documentation for individual API elements -specifies the API Level at which each element was introduced. The API Level -for packages and classes is specified as "Since <api level>" at the -top-right corner of the content area on each documentation page. The API Level -for class members is specified in their detailed description headers, -at the right margin.

    diff --git a/docs/html/guide/appendix/g-app-intents.jd b/docs/html/guide/appendix/g-app-intents.jd index df9d29bd72ff..10ec01e038f9 100644 --- a/docs/html/guide/appendix/g-app-intents.jd +++ b/docs/html/guide/appendix/g-app-intents.jd @@ -4,7 +4,7 @@ page.title=Intents List: Invoking Google Applications on Android Devices diff --git a/docs/html/guide/appendix/glossary.jd b/docs/html/guide/appendix/glossary.jd index 06fdef286dac..94cb0f08433b 100644 --- a/docs/html/guide/appendix/glossary.jd +++ b/docs/html/guide/appendix/glossary.jd @@ -42,7 +42,7 @@ page.title=Glossary SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging. If you are developing in Eclipse using the ADT Plugin, adb is integrated into your development environment. See - Android Debug Bridge + Android Debug Bridge for more information.
    Application
    @@ -91,7 +91,7 @@ page.title=Glossary with the SDK. It provides screen capture, log dump, and process examination capabilities. If you are developing in Eclipse using the ADT Plugin, DDMS is integrated into your development environment. See Using DDMS to learn more about the program. + href="{@docRoot}tools/debugging/ddms.html">Using DDMS to learn more about the program.
    Dialog
    A floating window that that acts as a lightweight form. A dialog can have button controls only and is intended to perform a @@ -131,7 +131,7 @@ page.title=Glossary is responsible for resolving the best-available receiver for each Intent, based on the criteria supplied in the Intent and the Intent Filters defined by other applications. For more information, see Intents and + href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters.

    Related: Intent Filter, Broadcast Receiver.

    @@ -145,7 +145,7 @@ page.title=Glossary available intent filters in all applications and passes the Intent to the application/activity that best matches the Intent and criteria. For more information, see Intents and + href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters.

    Related: Intent, Broadcast Receiver.

    diff --git a/docs/html/guide/appendix/install-location.jd b/docs/html/guide/appendix/install-location.jd index 63a3817e7c9f..19c4b3900ef1 100644 --- a/docs/html/guide/appendix/install-location.jd +++ b/docs/html/guide/appendix/install-location.jd @@ -174,7 +174,7 @@ external storage, it can never receive this broadcast.
    Copy Protection
    Your application cannot be installed to a device's SD card if it uses Google Play's Copy Protection feature. However, if you use Google Play's - Application Licensing instead, your + Application Licensing instead, your application can be installed to internal or external storage, including SD cards.
    @@ -198,7 +198,7 @@ applications that should allow installation on external storage, because games d provide additional services when inactive. When external storage becomes unavailable and a game process is killed, there should be no visible effect when the storage becomes available again and the user restarts the game (assuming that the game properly saved its state during the normal -Activity lifecycle).

    +Activity lifecycle).

    If your application requires several megabytes for the APK file, you should carefully consider whether to enable the application to install on the external storage so that diff --git a/docs/html/guide/appendix/market-filters.jd b/docs/html/guide/appendix/market-filters.jd deleted file mode 100644 index 3e502d7d5f19..000000000000 --- a/docs/html/guide/appendix/market-filters.jd +++ /dev/null @@ -1,454 +0,0 @@ -page.title=Filters on Google Play -@jd:body - -

    -
    - -

    Quickview

    -
      -
    • Google Play applies filters that control which Android-powered devices can access your -application when the user is visiting the store.
    • -
    • Filtering is determined by comparing device configurations that you declare in you app's -manifest file to the configurations defined by the device, as well as other factors.
    - -

    In this document

    - -
      -
    1. How Filters Work on Google Play
    2. -
    3. Filtering based on Manifest Elements -
        -
      1. Advanced manifest filters
      2. -
      -
    4. -
    5. Other Filters
    6. -
    7. Publishing Multiple APKs with Different Filters
    8. -
    - -

    See also

    -
      -
    1. Android Compatibility
    2. -
    3. <supports-gl-texture>
    4. -
    5. <supports-screens>
    6. -
    7. <uses-configuration>
    8. -
    9. <uses-feature>
    10. -
    11. <uses-library>
    12. -
    13. <uses-permission>
    14. -
    15. <uses-sdk>
    16. -
    - -
    - -
    - -

    Interested in publishing your app on Google Play?

    -

    Go to Google Play to create a publisher -account and upload your app.

    -
    - -
    -
    - - -

    When a user searches or browses on Google Play on an Android device, the results are filtered -based on which applications are compatible with that device. For example, if an application -requires a camera (as specified in the application manifest file), then Google Play will not show -the app on any device that does not have a camera.

    - -

    Declarations in the manifest file that are compared to the device's configuration is not the -only part of how applications are filtered. Filtering might also occur due to the user's country and -carrier, the presence or absence of a SIM card, and other factors.

    - -

    Changes to the Google Play filters are independent of changes to the Android platform itself. -This document is updated periodically to reflect any changes that affect the way Google Play -filters applications.

    - - -

    How Filters Work on Google Play

    - -

    Google Play uses the filter restrictions described below to determine -whether to show your application to a user who is browsing or searching for -applications from the Google Play app. When determining whether to display your app, -Google Play checks the device's hardware and software configuration, as well as it's -carrier, location, and other characteristics. It then compares those against the -restrictions and dependencies expressed by the application's -manifest file and publishing details. If the application is -compatible with the device according to the filter rules, Google Play displays the -application to the user. Otherwise, Google Play hides your application from search -results and category browsing, even if a user specifically requests -the app by clicking a deep link that points directly to the app's ID within Google Play..

    - -

    Note: When users browse the Google Play web site, they can see all published -applications. The Google Play web site compares the application requirements to each of the -user's registered devices for compatibility, though, and only allows them to install the application -if it's compatible with their device.

    - -

    You can use any combination of the available filters for your app. For example, you can set a -minSdkVersion requirement of "4" and set smallScreens="false" -in the app, then when uploading the app to Google Play you could target European countries (carriers) -only. Google Play's filters will thus prevent the application from being available on any device -that does not match all three of these requirements.

    - -

    All filtering restrictions are associated with an application's version and can -change between versions. For example, if a user has installed your application and you publish an -update that makes the app invisible to the user, the user will not see that an update is -available.

    - - -

    Filtering based on Manifest Elements

    - -

    Most filters are triggered by elements within an application's -manifest file, AndroidManifest.xml -(although not everything in the manifest file can trigger filtering). -Table 1 lists the manifest elements that you should use to trigger -filtering, and explains how the filtering for each element works.

    - -

    Table 1. Manifest elements that -trigger filtering on Google Play.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Manifest ElementFilter NameHow It Works
    <supports-screens> - Screen Size - -

    An application indicates the screen sizes that it is capable of supporting by -setting attributes of the <supports-screens> element. When -the application is published, Google Play uses those attributes to determine whether -to show the application to users, based on the screen sizes of their -devices.

    - -

    As a general rule, Google Play assumes that the platform on the device can adapt -smaller layouts to larger screens, but cannot adapt larger layouts to smaller -screens. Thus, if an application declares support for "normal" screen size only, -Google Play makes the application available to both normal- and large-screen devices, -but filters the application so that it is not available to small-screen -devices.

    - -

    If an application does not declare attributes for -<supports-screens>, Google Play uses the default values for those -attributes, which vary by API Level. Specifically:

    - -
      -
    • For applications that set either the android: -minSdkVersion or android: -targetSdkVersion to 3 or lower, the <supports-screens> element itself -is undefined and no attributes are available. In this case, Google Play assumes that -the application is designed for normal-size screens and shows the application to -devices that have normal or larger screens.

      - -
    • When the either the android: -minSdkVersion or android: -targetSdkVersion is set to 4 or higher, the default for all attributes is -"true". In this way, the application is considered to support all screen sizes by -default.
    • -
    - -

    Example 1
    - The manifest declares <uses-sdk android:minSdkVersion="3"> - and does not include a <supports-screens> element. - Result: Google Play will not show the app to a user of a - small-screen device, but will show it to users of normal and large-screen - devices, unless other filters apply.

    -

    Example 2
    -
    The manifest declares <uses-sdk android:minSdkVersion="3" - android:targetSdkVersion="4"> and does not include a - <supports-screens> element. - Result: Google Play will show the app to users on all - devices, unless other filters apply.

    -

    Example 3
    -
    The manifest declares <uses-sdk android:minSdkVersion="4"> - and does not include a <supports-screens> element. - Result: Google Play will show the app to all users, - unless other filters apply.

    -

    For more information on how to declare support for screen sizes in your - application, see <supports-screens> - and Supporting Multiple - Screens.

    -
    <uses-configuration> - Device - Configuration:
    - keyboard, navigation, touch screen

    An application can - request certain hardware features, and Google Play will show the app only on devices that have the required hardware.

    -

    Example 1
    -
    The manifest includes <uses-configuration android:reqFiveWayNav="true" />, and a user is searching for apps on a device that does not have a five-way navigational control. Result: Google Play will not show the app to the user.

    -

    Example 2
    -
    The manifest does not include a <uses-configuration> element. Result: Google Play will show the app to all users, unless other filters apply.

    -

    For more details, see <uses-configuration>.

    <uses-feature> - - Device Features
    - (name)

    An application can require certain device features to be -present on the device. This functionality was introduced in Android 2.0 (API -Level 5).

    -

    Example 1
    -
    The manifest includes <uses-feature -android:name="android.hardware.sensor.light" />, and a user -is searching for apps on a device that does not have a light sensor. -Result: Google Play will not show the app to the user.

    -

    Example 2
    -
    The manifest does not include a <uses-feature> -element. Result: Google Play will show the app to all users, -unless other filters apply.

    -

    For complete information, see <uses-feature> -.

    -

    Filtering based on implied features: In some cases, Google -Play interprets permissions requested through -<uses-permission> elements as feature requirements equivalent -to those declared in <uses-feature> elements. See <uses-permission>, -below.

    -
    OpenGL-ES - Version
    -(openGlEsVersion)

    An application can require that the device support a specific - OpenGL-ES version using the <uses-feature - android:openGlEsVersion="int"> attribute.

    -

    Example 1
    -
    An app - requests multiple OpenGL-ES versions by specifying openGlEsVersion multiple times in the - manifest. Result: Google Play assumes that the app requires the highest of the indicated versions.

    -

    Example 2
    -
    An app - requests OpenGL-ES version 1.1, and a user is searching for apps on a device that supports OpenGL-ES version 2.0. Result: Google Play will show the app to the user, unless other filters apply. If a - device reports that it supports OpenGL-ES version X, Google Play assumes that it - also supports any version earlier than X. -

    -

    Example 3
    -
    A user is searching for apps on a device that does not - report an OpenGL-ES version (for example, a device running Android 1.5 or earlier). Result: Google Play assumes that the device - supports only OpenGL-ES 1.0. Google Play will only show the user apps that do not specify openGlEsVersion, or apps that do not specify an OpenGL-ES version higher than 1.0.

    -

    Example 4
    -
    The manifest does not specify openGlEsVersion. Result: Google Play will show the app to all users, unless other filters apply.

    -

    For more details, see <uses-feature>.

    <uses-library>Software Libraries

    An application can require specific - shared libraries to be present on the device.

    -

    Example 1
    -
    An app requires the com.google.android.maps library, and a user is searching for apps on a device that does not have the com.google.android.maps library. Result: Google Play will not show the app to the user.

    -

    Example 2
    - The manifest does not include a <uses-library> element. Result: Google Play will show the app to all users, unless other filters apply.

    -

    For more details, see <uses-library>.

    <uses-permission> Strictly, Google Play does not filter based on -<uses-permission> elements. However, it does read the -elements to determine whether the application has hardware feature requirements -that may not have been properly declared in <uses-feature> -elements. For example, if an application requests the CAMERA -permission but does not declare a <uses-feature> element for -android.hardware.camera, Google Play considers that the -application requires a camera and should not be shown to users whose devices do -not offer a camera.

    -

    In general, if an application requests hardware-related permissions, -Google Play assumes that the application requires the underlying hardware -features, even though there might be no corresponding to -<uses-feature> declarations. Google Play then sets up -filtering based on the features implied by the <uses-feature> -declarations.

    -

    For a list of permissions that imply hardware features, see -the documentation for the <uses-feature> -element.

    -
    <uses-sdk>Minimum Framework Version (minSdkVersion)

    An application can require a minimum API level.

    -

    Example 1
    - The manifest includes <uses-sdk - android:minSdkVersion="3">, and the app uses APIs that were introduced in API Level 3. A user is searching for apps on a device that has API Level 2. Result: Google Play will not show the app to the user.

    -

    Example 2
    - The manifest does not include minSdkVersion, and the app uses APIs that were introduced in API Level 3. A user is searching for apps on a device that has API Level 2. Result: Google Play assumes that minSdkVersion is "1" and that the app is compatible with all versions of Android. Google Play shows the app to the user and allows the user to download the app. The app crashes at runtime.

    -

    Because you want to avoid this second scenario, we recommend that you always declare a minSdkVersion. For details, see android:minSdkVersion.

    Maximum Framework Version (maxSdkVersion)

    Deprecated. Android - 2.1 and later do not check or enforce the maxSdkVersion attribute, and - the SDK will not compile if maxSdkVersion is set in an app's manifest. For devices already - compiled with maxSdkVersion, Google Play will respect it and use it for - filtering.

    -

    Declaring maxSdkVersion is not recommended. For details, see android:maxSdkVersion.

    - - - -

    Advanced manifest filters

    - -

    In addition to the manifest elements in table 1, Google Play can also -filter applications based on the advanced manifest elements in table 2.

    - -

    These manifest elements and the filtering they trigger are for exceptional use-cases -only. These are designed for certain types of high-performance games and similar applications that -require strict controls on application distribution. Most applications should never use -these filters.

    - -

    Table 2. Advanced manifest elements for -Google Play filtering.

    - - - - - - - - - - -
    Manifest ElementSummary
    {@code -<compatible-screens>} -

    Google Play filters the application if the device screen size and density does not match -any of the screen configurations (declared by a {@code <screen>} element) in the {@code -<compatible-screens>} element.

    -

    Caution: Normally, you should not use -this manifest element. Using this element can dramatically -reduce the potential user base for your application, by excluding all combinations of screen size -and density that you have not listed. You should instead use the {@code -<supports-screens>} manifest element (described above in table -1) to enable screen compatibility mode for screen configurations you have not accounted for -with alternative resources.

    -
    {@code -<supports-gl-texture>} -

    Google Play filters the application unless one or more of the GL texture compression -formats supported by the application are also supported by the device.

    -
    - - - -

    Other Filters

    - -

    Google Play uses other application characteristics to determine whether to show or hide an application for a particular user on a given device, as described in the table below.

    - -

    Table 3. Application and publishing -characteristics that affect filtering on Google Play.

    - - - - - - - - - - -
    Filter Name How It Works
    Publishing Status

    Only published applications will appear in - searches and browsing within Google Play.

    Even if an app is unpublished, it can - be installed if users can see it in their Downloads area among their purchased, - installed, or recently uninstalled apps.

    If an application has been - suspended, users will not be able to reinstall or update it, even if it appears in their Downloads.

    Priced - Status

    Not all users can see paid apps. To show paid apps, a device -must have a SIM card and be running Android 1.1 or later, and it must be in a -country (as determined by SIM carrier) in which paid apps are available.

    Country / Carrier Targeting

    When you upload your app to - Google Play, you can select specific countries to target. The app will only - be visible to the countries (carriers) that you select, as follows:

    -
    • A device's country is determined based on the carrier, if a carrier is - available. If no carrier can be determined, Google Play tries to - determine the country based on IP.

    • Carrier is determined based on - the device's SIM (for GSM devices), not the current roaming carrier.

    -
    Native Platform

    An application that includes native - libraries that target a specific platform (ARM EABI v7 or x86, for example) are - visible only on devices that support that platform. For details about the NDK and using - native libraries, see What is the - Android NDK?

    Copy-Protected Applications

    To - copy protect an application, set copy protection to "On" when you configure publishing -options for your application. Google Play will not show copy-protected applications on -developer devices or unreleased devices.

    - - - -

    Publishing Multiple APKs with Different Filters

    - -

    Some specific Google Play filters allow you to publish multiple APKs for the same -application in order to provide a different APK to different device configurations. For example, if -you're creating a video game that uses high-fidelity graphic assets, you might want to create -two APKs that each support different texture compression formats. This way, you can reduce the -size of the APK file by including only the textures that are required for each device -configuration. Depending on each device's support for your texture compression formats, Google -Play will deliver it the APK that you've declared to support that device.

    - -

    Currently, Google Play allows you to publish multiple APKs for the same application only -when each APK provides different filters based on the following configurations:

    - - -

    All other filters still work the same as usual, but these three are the only filters that can -distinguish one APK from another within the same application listing on Google Play. For example, -you cannot publish multiple APKs for the same application if the APKs differ only based on -whether the device has a camera.

    - -

    Caution: Publishing multiple APKs for the same application is -considered an advanced feature and most application should publish only one -APK that supports a wide range of device configurations. Publishing multiple APKs -requires that you follow specific rules within your filters and that you pay extra attention to the -version codes for each APK to ensure proper update paths for each configuration.

    - -

    If you need more information about how to publish multiple APKs on Google Play, read Multiple APK Support.

    diff --git a/docs/html/guide/appendix/media-formats.jd b/docs/html/guide/appendix/media-formats.jd index 137f13811d11..93e813662249 100644 --- a/docs/html/guide/appendix/media-formats.jd +++ b/docs/html/guide/appendix/media-formats.jd @@ -268,9 +268,9 @@ no dither applied for 24-bit.   - SD (Low quality) - SD (High quality) - HD (Not available on all devices) + SD (Low quality) + SD (High quality) + HD (Not available on all devices) diff --git a/docs/html/guide/basics/what-is-android.jd b/docs/html/guide/basics/what-is-android.jd deleted file mode 100644 index 9393fabfc8fb..000000000000 --- a/docs/html/guide/basics/what-is-android.jd +++ /dev/null @@ -1,141 +0,0 @@ -page.title=What is Android? -@jd:body - -

    Android is a software stack for mobile devices that includes an operating -system, middleware and key applications. The Android SDK -provides the tools and APIs necessary to begin developing applications on the -Android platform using the Java programming language.

    - -

    Features

    - -
      -
    • Application framework enabling reuse and replacement - of components
    • -
    • Dalvik virtual machine optimized for mobile - devices
    • -
    • Integrated browser based on the open source WebKit engine
    • -
    • Optimized graphics powered by a custom 2D graphics library; 3D - graphics based on the OpenGL ES 1.0 specification (hardware acceleration - optional)
    • -
    • SQLite for structured data storage
    • -
    • Media support for common audio, video, and still - image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, - GIF)
    • -
    • GSM Telephony (hardware dependent)
    • -
    • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
    • -
    • Camera, GPS, compass, and accelerometer (hardware dependent)
    • -
    • Rich development environment including a device - emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE
    • -
    - - -

    Android Architecture

    - -

    The following diagram shows the major components of the Android operating -system. Each section is described in more detail below.

    - -

    Android System Architecture

    - - -

    Applications

    - -

    Android will ship with a set of core applications including an email -client, SMS program, calendar, maps, browser, contacts, and -others. All applications are written using the Java programming language.

    - - -

    Application Framework

    - -

    By providing an open development platform, Android -offers developers the ability to build extremely rich and innovative -applications. Developers are free to take advantage of the -device hardware, access location information, run background services, set alarms, -add notifications to the status bar, and much, much more.

    - -

    Developers have full access to the same framework APIs used by the core -applications. The application architecture is designed to simplify the reuse -of components; any application can publish its capabilities and any other -application may then make use of those capabilities (subject to security -constraints enforced by the framework). This same mechanism allows components -to be replaced by the user.

    - -

    Underlying all applications is a set of services and systems, including: -

      -
    • A rich and extensible set of Views that can be used to - build an application, including lists, grids, text boxes, buttons, and even - an embeddable web browser
    • -
    • Content - Providers that enable applications to access data from other - applications (such as Contacts), or to share their own data
    • A Resource - Manager, providing access to non-code resources such as localized - strings, graphics, and layout files
    • -
    • A {@link android.app.NotificationManager Notification Manager} that enables - all applications to display custom alerts in the status bar
    • -
    • An {@link android.app.Activity Activity Manager} that manages the - lifecycle of applications and provides a common navigation backstack
    • -
    - -

    For more details and a walkthrough of an application, see the Notepad Tutorial.

    - - -

    Libraries

    - -

    Android includes a set of C/C++ libraries used by various components of the -Android system. These capabilities are exposed to developers through the -Android application framework. Some of the core libraries are listed below:

    -
      -
    • System C library - a BSD-derived implementation of - the standard C system library (libc), tuned for embedded Linux-based - devices
    • -
    • Media Libraries - based on PacketVideo's OpenCORE; - the libraries support playback and recording of many popular audio and video - formats, as well as static image files, including MPEG4, H.264, MP3, AAC, - AMR, JPG, and PNG
    • -
    • Surface Manager - manages access to the display - subsystem and seamlessly composites 2D and 3D graphic layers from multiple - applications
    • -
    • LibWebCore - a modern web browser engine which - powers both the Android browser and an embeddable web view
    • -
    • SGL - the underlying 2D graphics - engine
    • -
    • 3D libraries - an implementation based on - OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration - (where available) or the included, highly optimized 3D software - rasterizer
    • -
    • FreeType - bitmap and vector font rendering
    • -
    • SQLite - a powerful and lightweight relational - database engine available to all applications
    • -
    - - - -

    Android Runtime

    - -

    Android includes a set of core libraries that provides most of -the functionality available in the core libraries of the Java programming -language.

    - -

    Every Android application runs in its own process, with its own instance of -the Dalvik virtual machine. Dalvik has been written so that a device can run -multiple VMs efficiently. The Dalvik VM executes files in the Dalvik -Executable (.dex) format which is optimized for minimal memory -footprint. The VM is register-based, and runs classes -compiled by a Java language compiler that have been transformed into the .dex -format by the included "dx" tool.

    - -

    The Dalvik VM relies on the Linux kernel for underlying functionality such -as threading and low-level memory management.

    - - - -

    Linux Kernel

    - -

    Android relies on Linux version 2.6 for core system services such as -security, memory management, process management, network stack, and driver -model. The kernel also acts as an abstraction layer between the hardware and -the rest of the software stack.

    diff --git a/docs/html/guide/components/activities.jd b/docs/html/guide/components/activities.jd new file mode 100644 index 000000000000..36f651f04c03 --- /dev/null +++ b/docs/html/guide/components/activities.jd @@ -0,0 +1,776 @@ +page.title=Activities +@jd:body + +
    +
    +

    Quickview

    +
      +
    • An activity provides a user interface for a single screen in your application
    • +
    • Activities can move into the background and then be resumed with their state restored
    • +
    + +

    In this document

    +
      +
    1. Creating an Activity +
        +
      1. Implementing a user interface
      2. +
      3. Declaring the activity in the manifest
      4. +
      +
    2. +
    3. Starting an Activity +
        +
      1. Starting an activity for a result
      2. +
      +
    4. +
    5. Shutting Down an Activity
    6. +
    7. Managing the Activity Lifecycle +
        +
      1. Implementing the lifecycle callbacks
      2. +
      3. Saving activity state
      4. +
      5. Handling configuration changes
      6. +
      7. Coordinating activities
      8. +
      +
    8. +
    + +

    Key classes

    +
      +
    1. {@link android.app.Activity}
    2. +
    + +

    See also

    +
      +
    1. Tasks and Back +Stack
    2. +
    + +
    +
    + + + +

    An {@link android.app.Activity} is an application component that provides a screen with which +users can interact in order to do something, such as dial the phone, take a photo, send an email, or +view a map. Each activity is given a window in which to draw its user interface. The window +typically fills the screen, but may be smaller than the screen and float on top of other +windows.

    + +

    An application usually consists of multiple activities that are loosely bound +to each other. Typically, one activity in an application is specified as the "main" activity, which +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" stack mechanism, +so, when the user is done with the current activity and presses the Back button, it +is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is +discussed more in the Tasks +and Back Stack document.)

    + +

    When an activity is stopped because a new activity starts, it is notified of this change in state +through the activity's lifecycle callback methods. +There are several callback methods that an activity might receive, due to a change in its +state—whether the system is creating it, stopping it, resuming it, or destroying it—and +each callback provides you the opportunity to perform specific work that's +appropriate to that state change. For instance, when stopped, your activity should release any +large objects, such as network or database connections. When the activity resumes, you can +reacquire the necessary resources and resume actions that were interrupted. These state transitions +are all part of the activity lifecycle.

    + +

    The rest of this document discusses the basics of how to build and use an activity, +including a complete discussion of how the activity lifecycle works, so you can properly manage +the transition between various activity states.

    + + + +

    Creating an Activity

    + +

    To create an activity, you must create a subclass of {@link android.app.Activity} (or +an existing subclass of it). In your subclass, you need to implement callback methods that the +system calls when the activity transitions between various states of its lifecycle, such as when +the activity is being created, stopped, resumed, or destroyed. The two most important callback +methods are:

    + +
    +
    {@link android.app.Activity#onCreate onCreate()}
    +
    You must implement this method. The system calls this when creating your + activity. Within your implementation, you should initialize the essential components of your +activity. + Most importantly, this is where you must call {@link android.app.Activity#setContentView + setContentView()} to define the layout for the activity's user interface.
    +
    {@link android.app.Activity#onPause onPause()}
    +
    The system calls this method as the first indication that the user is leaving your +activity (though it does not always mean the activity is being destroyed). This is usually where you +should commit any changes that should be persisted beyond the current user session (because +the user might not come back).
    +
    + +

    There are several other lifecycle callback methods that you should use in order to provide a +fluid user experience between activities and handle unexpected interuptions that cause your activity +to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in +the section about Managing the Activity Lifecycle.

    + + + +

    Implementing a user interface

    + +

    The user interface for an activity is provided by a hierarchy of views—objects derived +from the {@link android.view.View} class. Each view controls a particular rectangular space +within the activity's window and can respond to user interaction. For example, a view might be a +button that initiates an action when the user touches it.

    + +

    Android provides a number of ready-made views that you can use to design and organize your +layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such +as a button, text field, checkbox, or just an image. "Layouts" are views derived from {@link +android.view.ViewGroup} that provide a unique layout model for its child views, such as a linear +layout, a grid layout, or relative layout. You can also subclass the {@link android.view.View} and +{@link android.view.ViewGroup} classes (or existing subclasses) to create your own widgets and +layouts and apply them to your activity layout.

    + +

    The most common way to define a layout using views is with an XML layout file saved in your +application resources. This way, you can maintain the design of your user interface separately from +the source code that defines the activity's behavior. You can set the layout as the UI for your +activity with {@link android.app.Activity#setContentView(int) setContentView()}, passing the +resource ID for the layout. However, you can also create new {@link android.view.View}s in your +activity code and build a view hierarchy by inserting new {@link +android.view.View}s into a {@link android.view.ViewGroup}, then use that layout by passing the root +{@link android.view.ViewGroup} to {@link android.app.Activity#setContentView(View) +setContentView()}.

    + +

    For information about creating a user interface, see the User Interface documentation.

    + + + +

    Declaring the activity in the manifest

    + +

    You must declare your activity in the manifest file in order for it to +be accessible to the system. To declare your activity, open your manifest file and add an {@code <activity>} element +as a child of the {@code <application>} +element. For example:

    + +
    +<manifest ... >
    +  <application ... >
    +      <activity android:name=".ExampleActivity" />
    +      ...
    +  </application ... >
    +  ...
    +</manifest >
    +
    + +

    There are several other attributes that you can include in this element, to define properties +such as the label for the activity, an icon for the activity, or a theme to style the activity's +UI. The {@code android:name} +attribute is the only required attribute—it specifies the class name of the activity. Once +you publish your application, you should not change this name, because if you do, you might break +some functionality, such as application shortcuts (read the blog post, Things +That Cannot Change).

    + +

    See the {@code <activity>} element +reference for more information about declaring your activity in the manifest.

    + + +

    Using intent filters

    + +

    An {@code +<activity>} element can also specify various intent filters—using the {@code +<intent-filter>} element—in order to declare how other application components may +activate it.

    + +

    When you create a new application using the Android SDK tools, the stub activity +that's created for you automatically includes an intent filter that declares the activity +responds to the "main" action and should be placed in the "launcher" category. The intent filter +looks like this:

    + +
    +<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
    +    <intent-filter>
    +        <action android:name="android.intent.action.MAIN" />
    +        <category android:name="android.intent.category.LAUNCHER" />
    +    </intent-filter>
    +</activity>
    +
    + +

    The {@code +<action>} element specifies that this is the "main" entry point to the application. The {@code +<category>} element specifies that this activity should be listed in the +system's application launcher (to allow users to launch this activity).

    + +

    If you intend for your application to be self-contained and not allow other applications to +activate its activities, then you don't need any other intent filters. Only one activity should +have the "main" action and "launcher" category, as in the previous example. Activities that +you don't want to make available to other applications should have no intent filters and you can +start them yourself using explicit intents (as discussed in the following section).

    + +

    However, if you want your activity to respond to implicit intents that are delivered from +other applications (and your own), then you must define additional intent filters for your +activity. For each type of intent to which you want to respond, you must include an {@code +<intent-filter>} that includes an +{@code +<action>} element and, optionally, a {@code +<category>} element and/or a {@code +<data>} element. These elements specify the type of intent to which your activity can +respond.

    + +

    For more information about how your activities can respond to intents, see the Intents and Intent Filters +document.

    + + + +

    Starting an Activity

    + +

    You can start another activity by calling {@link android.app.Activity#startActivity + startActivity()}, passing it an {@link android.content.Intent} that describes the activity you + want to start. The intent specifies either the exact activity you want to start or describes the + type of action you want to perform (and the system selects the appropriate activity for you, +which + can even be from a different application). An intent can also carry small amounts of data to be + used by the activity that is started.

    + +

    When working within your own application, you'll often need to simply launch a known activity. + You can do so by creating an intent that explicitly defines the activity you want to start, +using the class name. For example, here's how one activity starts another activity named {@code +SignInActivity}:

    + +
    +Intent intent = new Intent(this, SignInActivity.class);
    +startActivity(intent);
    +
    + +

    However, your application might also want to perform some action, such as send an email, text + message, or status update, using data from your activity. In this case, your application might + not have its own activities to perform such actions, so you can instead leverage the activities + provided by other applications on the device, which can perform the actions for you. This is where +intents are really valuable—you can create an intent that describes an action you want to +perform and the system + launches the appropriate activity from another application. If there are + multiple activities that can handle the intent, then the user can select which one to use. For + example, if you want to allow the user to send an email message, you can create the + following intent:

    + +
    +Intent intent = new Intent(Intent.ACTION_SEND);
    +intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
    +startActivity(intent);
    +
    + +

    The {@link android.content.Intent#EXTRA_EMAIL} extra added to the intent is a string array of + email addresses to which the email should be sent. When an email application responds to this + intent, it reads the string array provided in the extra and places them in the "to" field of the + email composition form. In this situation, the email application's activity starts and when the + user is done, your activity resumes.

    + + + + +

    Starting an activity for a result

    + +

    Sometimes, you might want to receive a result from the activity that you start. In that case, + start the activity by calling {@link android.app.Activity#startActivityForResult + startActivityForResult()} (instead of {@link android.app.Activity#startActivity + startActivity()}). To then receive the result from the subsequent +activity, implement the {@link android.app.Activity#onActivityResult onActivityResult()} callback + method. When the subsequent activity is done, it returns a result in an {@link +android.content.Intent} to your {@link android.app.Activity#onActivityResult onActivityResult()} +method.

    + +

    For example, perhaps you want the user to pick one of their contacts, so your activity can +do something with the information in that contact. Here's how you can create such an intent and +handle the result:

    + +
    +private void pickContact() {
    +    // Create an intent to "pick" a contact, as defined by the content provider URI
    +    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
    +    startActivityForResult(intent, PICK_CONTACT_REQUEST);
    +}
    +
    +@Override
    +protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    +    // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
    +    if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
    +        // Perform a query to the contact's content provider for the contact's name
    +        Cursor cursor = getContentResolver().query(data.getData(),
    +        new String[] {Contacts.DISPLAY_NAME}, null, null, null);
    +        if (cursor.moveToFirst()) { // True if the cursor is not empty
    +            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
    +            String name = cursor.getString(columnIndex);
    +            // Do something with the selected contact's name...
    +        }
    +    }
    +}
    +
    + +

    This example shows the basic logic you should use in your {@link +android.app.Activity#onActivityResult onActivityResult()} method in order to handle an +activity result. The first condition checks whether the request was successful—if it was, then +the {@code resultCode} will be {@link android.app.Activity#RESULT_OK}—and whether the request +to which this result is responding is known—in this case, the {@code requestCode} matches the +second parameter sent with {@link android.app.Activity#startActivityForResult +startActivityForResult()}. From there, the code handles the activity result by querying the +data returned in an {@link android.content.Intent} (the {@code data} parameter).

    + +

    What happens is, a {@link +android.content.ContentResolver} performs a query against a content provider, which returns a +{@link android.database.Cursor} that allows the queried data to be read. For more information, see +the Content Providers document.

    + +

    For more information about using intents, see the Intents and Intent +Filters document.

    + + +

    Shutting Down an Activity

    + +

    You can shut down an activity by calling its {@link android.app.Activity#finish +finish()} method. You can also shut down a separate activity that you previously started by calling +{@link android.app.Activity#finishActivity finishActivity()}.

    + +

    Note: In most cases, you should not explicitly finish an activity +using these methods. As discussed in the following section about the activity lifecycle, the +Android system manages the life of an activity for you, so you do not need to finish your own +activities. Calling these methods could adversely affect the expected user +experience and should only be used when you absolutely do not want the user to return to this +instance of the activity.

    + + +

    Managing the Activity Lifecycle

    + +

    Managing the lifecycle of your activities by implementing callback methods is +crucial to developing a strong +and flexible application. The lifecycle of an activity is directly affected by its association with +other activities, its task and back stack.

    + +

    An activity can exist in essentially three states:

    + +
    +
    Resumed
    +
    The activity is in the foreground of the screen and has user focus. (This state is +also sometimes referred to as "running".)
    + +
    Paused
    +
    Another activity is in the foreground and has focus, but this one is still visible. That is, +another activity is visible on top of this one and that activity is partially transparent or doesn't +cover the entire screen. A paused activity is completely alive (the {@link android.app.Activity} +object is retained in memory, it maintains all state and member information, and remains attached to +the window manager), but can be killed by the system in extremely low memory situations.
    + +
    Stopped
    +
    The activity is completely obscured by another activity (the activity is now in the +"background"). A stopped activity is also still alive (the {@link android.app.Activity} +object is retained in memory, it maintains all state and member information, but is not +attached to the window manager). However, it is no longer visible to the user and it +can be killed by the system when memory is needed elsewhere.
    +
    + +

    If an activity is paused or stopped, the system can drop it from memory either by asking it to +finish (calling its {@link android.app.Activity#finish finish()} method), or simply killing its +process. When the activity is opened again (after being finished or killed), it must be created all +over.

    + + + +

    Implementing the lifecycle callbacks

    + +

    When an activity transitions into and out of the different states described above, it is notified +through various callback methods. All of the callback methods are hooks that you +can override to do appropriate work when the state of your activity changes. The following skeleton +activity includes each of the fundamental lifecycle methods:

    + + +
    +public class ExampleActivity extends Activity {
    +    @Override
    +    public void {@link android.app.Activity#onCreate onCreate}(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        // The activity is being created.
    +    }
    +    @Override
    +    protected void {@link android.app.Activity#onStart onStart()} {
    +        super.onStart();
    +        // The activity is about to become visible.
    +    }
    +    @Override
    +    protected void {@link android.app.Activity#onResume onResume()} {
    +        super.onResume();
    +        // The activity has become visible (it is now "resumed").
    +    }
    +    @Override
    +    protected void {@link android.app.Activity#onPause onPause()} {
    +        super.onPause();
    +        // Another activity is taking focus (this activity is about to be "paused").
    +    }
    +    @Override
    +    protected void {@link android.app.Activity#onStop onStop()} {
    +        super.onStop();
    +        // The activity is no longer visible (it is now "stopped")
    +    }
    +    @Override
    +    protected void {@link android.app.Activity#onDestroy onDestroy()} {
    +        super.onDestroy();
    +        // The activity is about to be destroyed.
    +    }
    +}
    +
    + +

    Note: Your implementation of these lifecycle methods must +always call the superclass implementation before doing any work, as shown in the examples above.

    + +

    Taken together, these methods define the entire lifecycle of an activity. By implementing these +methods, you can monitor three nested loops in the activity lifecycle:

    + +
      +
    • The entire lifetime of an activity happens between the call to {@link +android.app.Activity#onCreate onCreate()} and the call to {@link +android.app.Activity#onDestroy}. Your activity should perform setup of +"global" state (such as defining layout) in {@link android.app.Activity#onCreate onCreate()}, and +release all remaining resources in {@link android.app.Activity#onDestroy}. For example, if your +activity has a thread running in the background to download data from the network, it might create +that thread in {@link android.app.Activity#onCreate onCreate()} and then stop the thread in {@link +android.app.Activity#onDestroy}.
    • + +
    • The visible lifetime of an activity happens between the call to {@link +android.app.Activity#onStart onStart()} and the call to {@link +android.app.Activity#onStop onStop()}. During this time, the user can see the activity +on-screen and interact with it. For example, {@link android.app.Activity#onStop onStop()} is called +when a new activity starts and this one is no longer visible. Between these two methods, you can +maintain resources that are needed to show the activity to the user. For example, you can register a +{@link android.content.BroadcastReceiver} in {@link +android.app.Activity#onStart onStart()} to monitor changes that impact your UI, and unregister +it in {@link android.app.Activity#onStop onStop()} when the user can no longer see what you are +displaying. The system might call {@link android.app.Activity#onStart onStart()} and {@link +android.app.Activity#onStop onStop()} multiple times during the entire lifetime of the activity, as +the activity alternates between being visible and hidden to the user.

    • + +
    • The foreground lifetime of an activity happens between the call to {@link +android.app.Activity#onResume onResume()} and the call to {@link android.app.Activity#onPause +onPause()}. During this time, the activity is in front of all other activities on screen and has +user input focus. An activity can frequently transition in and out of the foreground—for +example, {@link android.app.Activity#onPause onPause()} is called when the device goes to sleep or +when a dialog appears. Because this state can transition often, the code in these two methods should +be fairly lightweight in order to avoid slow transitions that make the user wait.

    • +
    + +

    Figure 1 illustrates these loops and the paths an activity might take between states. +The rectangles represent the callback methods you can implement to perform operations when +the activity transitions between states.

    + + +

    Figure 1. The activity lifecycle.

    + +

    The same lifecycle callback methods are listed in table 1, which describes each of the callback +methods in more detail and locates each one within the +activity's overall lifecycle, including whether the system can kill the activity after the +callback method completes.

    + +

    Table 1. A summary of the activity lifecycle's +callback methods.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Description Killable after? Next
    {@link android.app.Activity#onCreate onCreate()}Called when the activity is first created. + This is where you should do all of your normal static set up — + create views, bind data to lists, and so on. This method is passed + a Bundle object containing the activity's previous state, if that + state was captured (see Saving Activity State, + later). +

    Always followed by {@code onStart()}.

    No{@code onStart()}
        {@link android.app.Activity#onRestart +onRestart()}Called after the activity has been stopped, just prior to it being + started again. +

    Always followed by {@code onStart()}

    No{@code onStart()}
    {@link android.app.Activity#onStart onStart()}Called just before the activity becomes visible to the user. +

    Followed by {@code onResume()} if the activity comes + to the foreground, or {@code onStop()} if it becomes hidden.

    No{@code onResume()}
    or
    {@code onStop()}
        {@link android.app.Activity#onResume onResume()}Called just before the activity starts + interacting with the user. At this point the activity is at + the top of the activity stack, with user input going to it. +

    Always followed by {@code onPause()}.

    No{@code onPause()}
    {@link android.app.Activity#onPause onPause()}Called when the system is about to start resuming another + activity. This method is typically used to commit unsaved changes to + persistent data, stop animations and other things that may be consuming + CPU, and so on. It should do whatever it does very quickly, because + the next activity will not be resumed until it returns. +

    Followed either by {@code onResume()} if the activity + returns back to the front, or by {@code onStop()} if it becomes + invisible to the user.

    Yes{@code onResume()}
    or
    {@code onStop()}
    {@link android.app.Activity#onStop onStop()}Called when the activity is no longer visible to the user. This + may happen because it is being destroyed, or because another activity + (either an existing one or a new one) has been resumed and is covering it. +

    Followed either by {@code onRestart()} if + the activity is coming back to interact with the user, or by + {@code onDestroy()} if this activity is going away.

    Yes{@code onRestart()}
    or
    {@code onDestroy()}
    {@link android.app.Activity#onDestroy +onDestroy()}Called before the activity is destroyed. This is the final call + that the activity will receive. It could be called either because the + activity is finishing (someone called {@link android.app.Activity#finish + finish()} on it), or because the system is temporarily destroying this + instance of the activity to save space. You can distinguish + between these two scenarios with the {@link + android.app.Activity#isFinishing isFinishing()} method.Yesnothing
    + +

    The column labeled "Killable after?" indicates whether or not the system can +kill the process hosting the activity at any time after the method returns, without +executing another line of the activity's code. Three methods are marked "yes": ({@link +android.app.Activity#onPause +onPause()}, {@link android.app.Activity#onStop onStop()}, and {@link android.app.Activity#onDestroy +onDestroy()}). Because {@link android.app.Activity#onPause onPause()} is the first +of the three, once the activity is created, {@link android.app.Activity#onPause onPause()} is the +last method that's guaranteed to be called before the process can be killed—if +the system must recover memory in an emergency, then {@link +android.app.Activity#onStop onStop()} and {@link android.app.Activity#onDestroy onDestroy()} might +not be called. Therefore, you should use {@link android.app.Activity#onPause onPause()} to write +crucial persistent data (such as user edits) to storage. However, you should be selective about +what information must be retained during {@link android.app.Activity#onPause onPause()}, because any +blocking procedures in this method block the transition to the next activity and slow the user +experience.

    + +

    Methods that are marked "No" in the Killable column protect the process hosting the +activity from being killed from the moment they are called. Thus, an activity is killable +from the time {@link android.app.Activity#onPause onPause()} returns to the time +{@link android.app.Activity#onResume onResume()} is called. It will not again be killable until +{@link android.app.Activity#onPause onPause()} is again called and returns.

    + +

    Note: An activity that's not technically "killable" by this +definition in table 1 might still be killed by the system—but that would happen only in +extreme circumstances when there is no other recourse. When an activity might be killed is +discussed more in the Processes and +Threading document.

    + + +

    Saving activity state

    + +

    The introduction to Managing the Activity Lifecycle briefly mentions +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 so that when the activity returns to the +foreground (when it "resumes"), those changes are still there.

    + +

    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 +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: {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()}.

    + +

    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()} 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).

    + + +

    Figure 2. 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.

    + +

    Note: 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 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()}.

    + +

    However, even if you do nothing and do not implement {@link +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 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 {@code android:id} +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.

    + + + +

    Although the default implementation of {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} saves useful information about +your activity's UI, you still might need to override it to save additional information. +For example, you might need to save member values that changed during the activity's life (which +might correlate to values restored in the UI, but the members that hold those UI values are not +restored, by default).

    + +

    Because the default implementation of {@link +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. 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.

    + +

    Note: Because {@link android.app.Activity#onSaveInstanceState +onSaveInstanceState()} is not guaranteed +to be called, you should use it only to record the transient state of the activity (the state of +the UI)—you should never use it to store persistent data. Instead, you should use {@link +android.app.Activity#onPause onPause()} to store persistent data (such as data that should be saved +to a database) when the user leaves the activity.

    + +

    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 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.

    + + +

    Handling configuration changes

    + +

    Some device configurations can change during runtime (such as screen orientation, keyboard +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 (such as different layouts for +different screen orientations and sizes).

    + +

    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.

    + +

    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.

    + +

    For more information about configuration changes that happen at runtime and how you can handle +them, read the guide to Handling +Runtime Changes.

    + + + +

    Coordinating activities

    + +

    When one activity starts another, they both experience lifecycle transitions. The first activity +pauses and stops (though, it won't stop if it's still visible in the background), while the other +activity is created. In case these activities share data saved to disc or elsewhere, it's important +to understand that the first activity is not completely stopped before the second one is created. +Rather, the process of starting the second one overlaps with the process of stopping the first +one.

    + +

    The order of lifecycle callbacks is well defined, particularly when the two activities are in the +same process and one is starting the other. Here's the order of operations that occur when Activity +A starts Acivity B:

    + +
      +
    1. Activity A's {@link android.app.Activity#onPause onPause()} method executes.
    2. + +
    3. Activity B's {@link android.app.Activity#onCreate onCreate()}, {@link +android.app.Activity#onStart onStart()}, and {@link android.app.Activity#onResume onResume()} +methods execute in sequence. (Activity B now has user focus.)
    4. + +
    5. Then, if Activity A is no longer visible on screen, its {@link +android.app.Activity#onStop onStop()} method executes.
    6. +
    + +

    This predictable sequence of lifecycle callbacks allows you to manage the transition of +information from one activity to another. For example, if you must write to a database when the +first activity stops so that the following activity can read it, then you should write to the +database during {@link android.app.Activity#onPause onPause()} instead of during {@link +android.app.Activity#onStop onStop()}.

    + + \ No newline at end of file diff --git a/docs/html/guide/components/bound-services.jd b/docs/html/guide/components/bound-services.jd new file mode 100644 index 000000000000..b6a251286c05 --- /dev/null +++ b/docs/html/guide/components/bound-services.jd @@ -0,0 +1,675 @@ +page.title=Bound Services +parent.title=Services +parent.link=services.html +@jd:body + + +
    +
      +

      Quickview

      +
        +
      • A bound service allows other components to bind to it, in order to interact with it and +perform interprocess communication
      • +
      • A bound service is destroyed once all clients unbind, unless the service was also started
      • +
      +

      In this document

      +
        +
      1. The Basics
      2. +
      3. Creating a Bound Service +
          +
        1. Extending the Binder class
        2. +
        3. Using a Messenger
        4. +
        +
      4. +
      5. Binding to a Service
      6. +
      7. Managing the Lifecycle of a Bound Service
      8. +
      + +

      Key classes

      +
        +
      1. {@link android.app.Service}
      2. +
      3. {@link android.content.ServiceConnection}
      4. +
      5. {@link android.os.IBinder}
      6. +
      + +

      Samples

      +
        +
      1. {@code + RemoteService}
      2. +
      3. {@code + LocalService}
      4. +
      + +

      See also

      +
        +
      1. Services
      2. +
      +
    + + +

    A bound service is the server in a client-server interface. A bound service allows components +(such as activities) to bind to the service, send requests, receive responses, and even perform +interprocess communication (IPC). A bound service typically lives only while it serves another +application component and does not run in the background indefinitely.

    + +

    This document shows you how to create a bound service, including how to bind +to the service from other application components. However, you should also refer to the Services document for additional +information about services in general, such as how to deliver notifications from a service, set +the service to run in the foreground, and more.

    + + +

    The Basics

    + +

    A bound service is an implementation of the {@link android.app.Service} class that allows +other applications to bind to it and interact with it. To provide binding for a +service, you must implement the {@link android.app.Service#onBind onBind()} callback method. This +method returns an {@link android.os.IBinder} object that defines the programming interface that +clients can use to interact with the service.

    + + + +

    A client can bind to the service by calling {@link android.content.Context#bindService +bindService()}. When it does, it must provide an implementation of {@link +android.content.ServiceConnection}, which monitors the connection with the service. The {@link +android.content.Context#bindService bindService()} method returns immediately without a value, but +when the Android system creates the connection between the +client and service, it calls {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link +android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that +the client can use to communicate with the service.

    + +

    Multiple clients can connect to the service at once. However, the system calls your service's +{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only +when the first client binds. The system then delivers the same {@link android.os.IBinder} to any +additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.

    + +

    When the last client unbinds from the service, the system destroys the service (unless the +service was also started by {@link android.content.Context#startService startService()}).

    + +

    When you implement your bound service, the most important part is defining the interface +that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few +different ways you can define your service's {@link android.os.IBinder} interface and the following +section discusses each technique.

    + + + +

    Creating a Bound Service

    + +

    When creating a service that provides binding, you must provide an {@link android.os.IBinder} +that provides the programming interface that clients can use to interact with the service. There +are three ways you can define the interface:

    + +
    +
    Extending the Binder class
    +
    If your service is private to your own application and runs in the same process as the client +(which is common), you should create your interface by extending the {@link android.os.Binder} class +and returning an instance of it from +{@link android.app.Service#onBind onBind()}. The client receives the {@link android.os.Binder} and +can use it to directly access public methods available in either the {@link android.os.Binder} +implementation or even the {@link android.app.Service}. +

    This is the preferred technique when your service is merely a background worker for your own +application. The only reason you would not create your interface this way is because +your service is used by other applications or across separate processes.

    + +
    Using a Messenger
    +
    If you need your interface to work across different processes, you can create +an interface for the service with a {@link android.os.Messenger}. In this manner, the service +defines a {@link android.os.Handler} that responds to different types of {@link +android.os.Message} objects. This {@link android.os.Handler} +is the basis for a {@link android.os.Messenger} that can then share an {@link android.os.IBinder} +with the client, allowing the client to send commands to the service using {@link +android.os.Message} objects. Additionally, the client can define a {@link android.os.Messenger} of +its own so the service can send messages back. +

    This is the simplest way to perform interprocess communication (IPC), because the {@link +android.os.Messenger} queues all requests into a single thread so that you don't have to design +your service to be thread-safe.

    +
    + +
    Using AIDL
    +
    AIDL (Android Interface Definition Language) performs all the work to decompose objects into +primitives that the operating system can understand and marshall them across processes to perform +IPC. The previous technique, using a {@link android.os.Messenger}, is actually based on AIDL as +its underlying structure. As mentioned above, the {@link android.os.Messenger} creates a queue of +all the client requests in a single thread, so the service receives requests one at a time. If, +however, you want your service to handle multiple requests simultaneously, then you can use AIDL +directly. In this case, your service must be capable of multi-threading and be built thread-safe. +

    To use AIDL directly, you must +create an {@code .aidl} file that defines the programming interface. The Android SDK tools use +this file to generate an abstract class that implements the interface and handles IPC, which you +can then extend within your service.

    +
    +
    + +

    Note: Most applications should not use AIDL to +create a bound service, because it may require multithreading capabilities and +can result in a more complicated implementation. As such, AIDL is not suitable for most applications +and this document does not discuss how to use it for your service. If you're certain that you need +to use AIDL directly, see the AIDL +document.

    + + + + +

    Extending the Binder class

    + +

    If your service is used only by the local application and does not need to work across processes, +then you can implement your own {@link android.os.Binder} class that provides your client direct +access to public methods in the service.

    + +

    Note: This works only if the client and service are in the same +application and process, which is most common. For example, this would work well for a music +application that needs to bind an activity to its own service that's playing music in the +background.

    + +

    Here's how to set it up:

    +
      +
    1. In your service, create an instance of {@link android.os.Binder} that either: +
        +
      • contains public methods that the client can call
      • +
      • returns the current {@link android.app.Service} instance, which has public methods the +client can call
      • +
      • or, returns an instance of another class hosted by the service with public methods the +client can call
      • +
      +
    2. Return this instance of {@link android.os.Binder} from the {@link +android.app.Service#onBind onBind()} callback method.
    3. +
    4. In the client, receive the {@link android.os.Binder} from the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method and +make calls to the bound service using the methods provided.
    5. +
    + +

    Note: The reason the service and client must be in the same +application is so the client can cast the returned object and properly call its APIs. The service +and client must also be in the same process, because this technique does not perform any +marshalling across processes.

    + +

    For example, here's a service that provides clients access to methods in the service through +a {@link android.os.Binder} implementation:

    + +
    +public class LocalService extends Service {
    +    // Binder given to clients
    +    private final IBinder mBinder = new LocalBinder();
    +    // Random number generator
    +    private final Random mGenerator = new Random();
    +
    +    /**
    +     * Class used for the client Binder.  Because we know this service always
    +     * runs in the same process as its clients, we don't need to deal with IPC.
    +     */
    +    public class LocalBinder extends Binder {
    +        LocalService getService() {
    +            // Return this instance of LocalService so clients can call public methods
    +            return LocalService.this;
    +        }
    +    }
    +
    +    @Override
    +    public IBinder onBind(Intent intent) {
    +        return mBinder;
    +    }
    +
    +    /** method for clients */
    +    public int getRandomNumber() {
    +      return mGenerator.nextInt(100);
    +    }
    +}
    +
    + +

    The {@code LocalBinder} provides the {@code getService()} method for clients to retrieve the +current instance of {@code LocalService}. This allows clients to call public methods in the +service. For example, clients can call {@code getRandomNumber()} from the service.

    + +

    Here's an activity that binds to {@code LocalService} and calls {@code getRandomNumber()} +when a button is clicked:

    + +
    +public class BindingActivity extends Activity {
    +    LocalService mService;
    +    boolean mBound = false;
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main);
    +    }
    +
    +    @Override
    +    protected void onStart() {
    +        super.onStart();
    +        // Bind to LocalService
    +        Intent intent = new Intent(this, LocalService.class);
    +        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    +    }
    +
    +    @Override
    +    protected void onStop() {
    +        super.onStop();
    +        // Unbind from the service
    +        if (mBound) {
    +            unbindService(mConnection);
    +            mBound = false;
    +        }
    +    }
    +
    +    /** Called when a button is clicked (the button in the layout file attaches to
    +      * this method with the android:onClick attribute) */
    +    public void onButtonClick(View v) {
    +        if (mBound) {
    +            // Call a method from the LocalService.
    +            // However, if this call were something that might hang, then this request should
    +            // occur in a separate thread to avoid slowing down the activity performance.
    +            int num = mService.getRandomNumber();
    +            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    +        }
    +    }
    +
    +    /** Defines callbacks for service binding, passed to bindService() */
    +    private ServiceConnection mConnection = new ServiceConnection() {
    +
    +        @Override
    +        public void onServiceConnected(ComponentName className,
    +                IBinder service) {
    +            // We've bound to LocalService, cast the IBinder and get LocalService instance
    +            LocalBinder binder = (LocalBinder) service;
    +            mService = binder.getService();
    +            mBound = true;
    +        }
    +
    +        @Override
    +        public void onServiceDisconnected(ComponentName arg0) {
    +            mBound = false;
    +        }
    +    };
    +}
    +
    + +

    The above sample shows how the client binds to the service using an implementation of +{@link android.content.ServiceConnection} and the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. The next +section provides more information about this process of binding to the service.

    + +

    Note: The example above doesn't explicitly unbind from the service, +but all clients should unbind at an appropriate time (such as when the activity pauses).

    + +

    For more sample code, see the {@code +LocalService.java} class and the {@code +LocalServiceActivities.java} class in ApiDemos.

    + + + + + +

    Using a Messenger

    + + + +

    If you need your service to communicate with remote processes, then you can use a +{@link android.os.Messenger} to provide the interface for your service. This technique allows +you to perform interprocess communication (IPC) without the need to use AIDL.

    + +

    Here's a summary of how to use a {@link android.os.Messenger}:

    + +
      +
    • The service implements a {@link android.os.Handler} that receives a callback for each +call from a client.
    • +
    • The {@link android.os.Handler} is used to create a {@link android.os.Messenger} object +(which is a reference to the {@link android.os.Handler}).
    • +
    • The {@link android.os.Messenger} creates an {@link android.os.IBinder} that the service +returns to clients from {@link android.app.Service#onBind onBind()}.
    • +
    • Clients use the {@link android.os.IBinder} to instantiate the {@link android.os.Messenger} +(that references the service's {@link android.os.Handler}), which the client uses to send +{@link android.os.Message} objects to the service.
    • +
    • The service receives each {@link android.os.Message} in its {@link +android.os.Handler}—specifically, in the {@link android.os.Handler#handleMessage +handleMessage()} method.
    • +
    + + +

    In this way, there are no "methods" for the client to call on the service. Instead, the +client delivers "messages" ({@link android.os.Message} objects) that the service receives in +its {@link android.os.Handler}.

    + +

    Here's a simple example service that uses a {@link android.os.Messenger} interface:

    + +
    +public class MessengerService extends Service {
    +    /** Command to the service to display a message */
    +    static final int MSG_SAY_HELLO = 1;
    +
    +    /**
    +     * Handler of incoming messages from clients.
    +     */
    +    class IncomingHandler extends Handler {
    +        @Override
    +        public void handleMessage(Message msg) {
    +            switch (msg.what) {
    +                case MSG_SAY_HELLO:
    +                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
    +                    break;
    +                default:
    +                    super.handleMessage(msg);
    +            }
    +        }
    +    }
    +
    +    /**
    +     * Target we publish for clients to send messages to IncomingHandler.
    +     */
    +    final Messenger mMessenger = new Messenger(new IncomingHandler());
    +
    +    /**
    +     * When binding to the service, we return an interface to our messenger
    +     * for sending messages to the service.
    +     */
    +    @Override
    +    public IBinder onBind(Intent intent) {
    +        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
    +        return mMessenger.getBinder();
    +    }
    +}
    +
    + +

    Notice that the {@link android.os.Handler#handleMessage handleMessage()} method in the +{@link android.os.Handler} is where the service receives the incoming {@link android.os.Message} +and decides what to do, based on the {@link android.os.Message#what} member.

    + +

    All that a client needs to do is create a {@link android.os.Messenger} based on the {@link +android.os.IBinder} returned by the service and send a message using {@link +android.os.Messenger#send send()}. For example, here's a simple activity that binds to the +service and delivers the {@code MSG_SAY_HELLO} message to the service:

    + +
    +public class ActivityMessenger extends Activity {
    +    /** Messenger for communicating with the service. */
    +    Messenger mService = null;
    +
    +    /** Flag indicating whether we have called bind on the service. */
    +    boolean mBound;
    +
    +    /**
    +     * Class for interacting with the main interface of the service.
    +     */
    +    private ServiceConnection mConnection = new ServiceConnection() {
    +        public void onServiceConnected(ComponentName className, IBinder service) {
    +            // This is called when the connection with the service has been
    +            // established, giving us the object we can use to
    +            // interact with the service.  We are communicating with the
    +            // service using a Messenger, so here we get a client-side
    +            // representation of that from the raw IBinder object.
    +            mService = new Messenger(service);
    +            mBound = true;
    +        }
    +
    +        public void onServiceDisconnected(ComponentName className) {
    +            // This is called when the connection with the service has been
    +            // unexpectedly disconnected -- that is, its process crashed.
    +            mService = null;
    +            mBound = false;
    +        }
    +    };
    +
    +    public void sayHello(View v) {
    +        if (!mBound) return;
    +        // Create and send a message to the service, using a supported 'what' value
    +        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
    +        try {
    +            mService.send(msg);
    +        } catch (RemoteException e) {
    +            e.printStackTrace();
    +        }
    +    }
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main);
    +    }
    +
    +    @Override
    +    protected void onStart() {
    +        super.onStart();
    +        // Bind to the service
    +        bindService(new Intent(this, MessengerService.class), mConnection,
    +            Context.BIND_AUTO_CREATE);
    +    }
    +
    +    @Override
    +    protected void onStop() {
    +        super.onStop();
    +        // Unbind from the service
    +        if (mBound) {
    +            unbindService(mConnection);
    +            mBound = false;
    +        }
    +    }
    +}
    +
    + +

    Notice that this example does not show how the service can respond to the client. If you want the +service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then +when the client receives the {@link android.content.ServiceConnection#onServiceConnected +onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes +the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter +of the {@link android.os.Messenger#send send()} method.

    + +

    You can see an example of how to provide two-way messaging in the {@code +MessengerService.java} (service) and {@code +MessengerServiceActivities.java} (client) samples.

    + + + + + +

    Binding to a Service

    + +

    Application components (clients) can bind to a service by calling +{@link android.content.Context#bindService bindService()}. The Android +system then calls the service's {@link android.app.Service#onBind +onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.

    + +

    The binding is asynchronous. {@link android.content.Context#bindService +bindService()} returns immediately and does not return the {@link android.os.IBinder} to +the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link +android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService +bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the +system calls to deliver the {@link android.os.IBinder}.

    + +

    Note: Only activities, services, and content providers can bind +to a service—you cannot bind to a service from a broadcast receiver.

    + +

    So, to bind to a service from your client, you must:

    +
      +
    1. Implement {@link android.content.ServiceConnection}. +

      Your implementation must override two callback methods:

      +
      +
      {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}
      +
      The system calls this to deliver the {@link android.os.IBinder} returned by +the service's {@link android.app.Service#onBind onBind()} method.
      +
      {@link android.content.ServiceConnection#onServiceDisconnected +onServiceDisconnected()}
      +
      The Android system calls this when the connection to the service is unexpectedly +lost, such as when the service has crashed or has been killed. This is not called when the +client unbinds.
      +
      +
    2. +
    3. Call {@link +android.content.Context#bindService bindService()}, passing the {@link +android.content.ServiceConnection} implementation.
    4. +
    5. When the system calls your {@link android.content.ServiceConnection#onServiceConnected +onServiceConnected()} callback method, you can begin making calls to the service, using +the methods defined by the interface.
    6. +
    7. To disconnect from the service, call {@link +android.content.Context#unbindService unbindService()}. +

      When your client is destroyed, it will unbind from the service, but you should always unbind +when you're done interacting with the service or when your activity pauses so that the service can +shutdown while its not being used. (Appropriate times to bind and unbind is discussed +more below.)

      +
    8. +
    + +

    For example, the following snippet connects the client to the service created above by +extending the Binder class, so all it must do is cast the returned +{@link android.os.IBinder} to the {@code LocalService} class and request the {@code +LocalService} instance:

    + +
    +LocalService mService;
    +private ServiceConnection mConnection = new ServiceConnection() {
    +    // Called when the connection with the service is established
    +    public void onServiceConnected(ComponentName className, IBinder service) {
    +        // Because we have bound to an explicit
    +        // service that is running in our own process, we can
    +        // cast its IBinder to a concrete class and directly access it.
    +        LocalBinder binder = (LocalBinder) service;
    +        mService = binder.getService();
    +        mBound = true;
    +    }
    +
    +    // Called when the connection with the service disconnects unexpectedly
    +    public void onServiceDisconnected(ComponentName className) {
    +        Log.e(TAG, "onServiceDisconnected");
    +        mBound = false;
    +    }
    +};
    +
    + +

    With this {@link android.content.ServiceConnection}, the client can bind to a service by passing +this it to {@link android.content.Context#bindService bindService()}. For example:

    + +
    +Intent intent = new Intent(this, LocalService.class);
    +bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    +
    + +
      +
    • The first parameter of {@link android.content.Context#bindService bindService()} is an +{@link android.content.Intent} that explicitly names the service to bind (thought the intent +could be implicit).
    • +
    • The second parameter is the {@link android.content.ServiceConnection} object.
    • +
    • The third parameter is a flag indicating options for the binding. It should usually be {@link +android.content.Context#BIND_AUTO_CREATE} in order to create the service if its not already alive. +Other possible values are {@link android.content.Context#BIND_DEBUG_UNBIND} +and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.
    • +
    + + +

    Additional notes

    + +

    Here are some important notes about binding to a service:

    +
      +
    • You should always trap {@link android.os.DeadObjectException} exceptions, which are thrown +when the connection has broken. This is the only exception thrown by remote methods.
    • +
    • Objects are reference counted across processes.
    • +
    • You should usually pair the binding and unbinding during +matching bring-up and tear-down moments of the client's lifecycle. For example: +
        +
      • If you only need to interact with the service while your activity is visible, you +should bind during {@link android.app.Activity#onStart onStart()} and unbind during {@link +android.app.Activity#onStop onStop()}.
      • +
      • If you want your activity to receive responses even while it is stopped in the +background, then you can bind during {@link android.app.Activity#onCreate onCreate()} and unbind +during {@link android.app.Activity#onDestroy onDestroy()}. Beware that this implies that your +activity needs to use the service the entire time it's running (even in the background), so if +the service is in another process, then you increase the weight of the process and it becomes +more likely that the system will kill it.
      • +
      +

      Note: You should usually not bind and unbind +during your activity's {@link android.app.Activity#onResume onResume()} and {@link +android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition +and you should keep the processing that occurs at these transitions to a minimum. Also, if +multiple activities in your application bind to the same service and there is a transition between +two of those activities, the service may be destroyed and recreated as the current activity unbinds +(during pause) before the next one binds (during resume). (This activity transition for how +activities coordinate their lifecycles is described in the Activities +document.)

      +
    + +

    For more sample code, showing how to bind to a service, see the {@code +RemoteService.java} class in ApiDemos.

    + + + + + +

    Managing the Lifecycle of a Bound Service

    + +
    + +

    Figure 1. The lifecycle for a service that is started +and also allows binding.

    +
    + +

    When a service is unbound from all clients, the Android system destroys it (unless it was also +started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have +to manage the lifecycle of your service if it's purely a bound +service—the Android system manages it for you based on whether it is bound to any clients.

    + +

    However, if you choose to implement the {@link android.app.Service#onStartCommand +onStartCommand()} callback method, then you must explicitly stop the service, because the +service is now considered to be started. In this case, the service runs until the service +stops itself with {@link android.app.Service#stopSelf()} or another component calls {@link +android.content.Context#stopService stopService()}, regardless of whether it is bound to any +clients.

    + +

    Additionally, if your service is started and accepts binding, then when the system calls +your {@link android.app.Service#onUnbind onUnbind()} method, you can optionally return +{@code true} if you would like to receive a call to {@link android.app.Service#onRebind +onRebind()} the next time a client binds to the service (instead of receiving a call to {@link +android.app.Service#onBind onBind()}). {@link android.app.Service#onRebind +onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its +{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. +Below, figure 1 illustrates the logic for this kind of lifecycle.

    + +

    For more information about the lifecycle of an started service, see the Services document.

    + + + + diff --git a/docs/html/guide/components/fragments.jd b/docs/html/guide/components/fragments.jd new file mode 100644 index 000000000000..938e0ab02ea6 --- /dev/null +++ b/docs/html/guide/components/fragments.jd @@ -0,0 +1,836 @@ +page.title=Fragments +parent.title=Activities +parent.link=activities.html +@jd:body + +
    +
    + +

    Quickview

    +
      +
    • Fragments decompose application functionality and UI into reusable modules
    • +
    • Add multiple fragments to a screen to avoid switching activities
    • +
    • Fragments have their own lifecycle, state, and back stack
    • +
    • Fragments require API Level 11 or greater
    • +
    + +

    In this document

    +
      +
    1. Design Philosophy
    2. +
    3. Creating a Fragment +
        +
      1. Adding a user interface
      2. +
      3. Adding a fragment to an activity
      4. +
      +
    4. +
    5. Managing Fragments
    6. +
    7. Performing Fragment Transactions
    8. +
    9. Communicating with the Activity +
        +
      1. Creating event callbacks to the activity
      2. +
      3. Adding items to the Action Bar
      4. +
      +
    10. +
    11. Handling the Fragment Lifecycle +
        +
      1. Coordinating with the activity lifecycle
      2. +
      +
    12. +
    13. Example
    14. +
    + +

    Key classes

    +
      +
    1. {@link android.app.Fragment}
    2. +
    3. {@link android.app.FragmentManager}
    4. +
    5. {@link android.app.FragmentTransaction}
    6. +
    + +

    Related samples

    +
      +
    1. Honeycomb Gallery
    2. +
    3. ApiDemos
    4. +
    + +

    See also

    +
      +
    1. Supporting Tablets +and Handsets
    2. +
    +
    +
    + +

    A {@link android.app.Fragment} represents a behavior or a portion of user interface in an +{@link android.app.Activity}. You can combine multiple fragments in a single activity to build a +multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a +modular section of an activity, which has its own lifecycle, receives its own input events, and +which you can add or remove while the activity is running (sort of like a "sub activity" that +you can reuse in different activities).

    + +

    A fragment must always be embedded in an activity and the fragment's lifecycle is directly +affected by the host activity's lifecycle. For example, when the activity is paused, so are all +fragments in it, and when the activity is destroyed, so are all fragments. However, while an +activity is running (it is in the resumed lifecycle state), you can +manipulate each fragment independently, such as add or remove them. When you perform such a +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.

    + +

    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 +layout. +You can insert a fragment into your activity layout by declaring the fragment in the activity's +layout file, as a {@code <fragment>} element, or from your application code by adding it to an +existing {@link android.view.ViewGroup}. However, a fragment is not required to be a part of the +activity layout; you may also use a fragment without its own UI as an invisible worker for the +activity.

    + +

    This document describes how to build your application to use fragments, including +how fragments can maintain their state when added to the activity's back stack, share +events with the activity and other fragments in the activity, contribute to the activity's action +bar, and more.

    + + +

    Design Philosophy

    + +

    Android introduced fragments in Android 3.0 (API level 11), primarily to support more +dynamic and flexible UI designs on large screens, such as tablets. Because a +tablet's screen is much larger than that of a handset, there's more room to combine and +interchange UI components. Fragments allow such designs without the need for you to manage complex +changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able +to modify the activity's appearance at runtime and preserve those changes in a back stack +that's managed by the activity.

    + +

    For example, a news application can use one fragment to show a list of articles on the +left and another fragment to display an article on the right—both fragments appear in one +activity, side by side, and each fragment has its own set of lifecycle callback methods and handle +their own user input events. Thus, instead of using one activity to select an article and another +activity to read the article, the user can select an article and read it all within the same +activity, as illustrated in the tablet layout in figure 1.

    + +

    You should design each fragment as a modular and reusable activity component. That is, because +each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can +include one fragment in multiple activities, so you should design for reuse and avoid directly +manipulating one fragment from another fragment. This is especially important because a modular +fragment allows you to change your fragment combinations for different screen sizes. When designing +your application to support both tablets and handsets, you can reuse your fragments in different +layout configurations to optimize the user experience based on the available screen space. For +example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when +more than one cannot fit within the same activity.

    + + +

    Figure 1. An example of how two UI modules defined by +fragments can be combined into one activity for a tablet design, but separated for a +handset design.

    + +

    For example—to continue with the news application example—the application can embed +two fragments in Activity A, when running on a tablet-sized device. However, on a +handset-sized screen, there's not enough room for both fragments, so Activity A includes +only the fragment for the list of articles, and when the user selects an article, it starts +Activity B, 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 +figure 1.

    + +

    For more information about designing your application with different fragment combinations for +different screen configurations, see the guide to Supporting Tablets and Handsets.

    + + + +

    Creating a Fragment

    + +
    + +

    Figure 2. The lifecycle of a fragment (while its +activity is running).

    +
    + +

    To create a fragment, you must create a subclass of {@link android.app.Fragment} (or an existing +subclass of it). The {@link android.app.Fragment} class has code that looks a lot like +an {@link android.app.Activity}. It contains callback methods similar to an activity, such +as {@link android.app.Fragment#onCreate onCreate()}, {@link android.app.Fragment#onStart onStart()}, +{@link android.app.Fragment#onPause onPause()}, and {@link android.app.Fragment#onStop onStop()}. In +fact, if you're converting an existing Android application to use fragments, you might simply move +code from your activity's callback methods into the respective callback methods of your +fragment.

    + +

    Usually, you should implement at least the following lifecycle methods:

    + +
    +
    {@link android.app.Fragment#onCreate onCreate()}
    +
    The system calls this when creating the fragment. Within your implementation, you should +initialize essential components of the fragment that you want to retain when the fragment is +paused or stopped, then resumed.
    +
    {@link android.app.Fragment#onCreateView onCreateView()}
    +
    The system calls this when it's time for the fragment to draw its user interface for the +first time. To draw a UI for your fragment, you must return a {@link android.view.View} from this +method that is the root of your fragment's layout. You can return null if the fragment does not +provide a UI.
    +
    {@link android.app.Activity#onPause onPause()}
    +
    The system calls this method as the first indication that the user is leaving the +fragment (though it does not always mean the fragment is being destroyed). This is usually where you +should commit any changes that should be persisted beyond the current user session (because +the user might not come back).
    +
    + +

    Most applications should implement at least these three methods for every fragment, but there are +several other callback methods you should also use to handle various stages of the +fragment lifecycle. All the lifecycle callback methods are discussed more later, in the section +about Handling the Fragment Lifecycle.

    + + +

    There are also a few subclasses that you might want to extend, instead of the base {@link +android.app.Fragment} class:

    + +
    +
    {@link android.app.DialogFragment}
    +
    Displays a floating dialog. Using this class to create a dialog is a good alternative to using +the dialog helper methods in the {@link android.app.Activity} class, because you can +incorporate a fragment dialog into the back stack of fragments managed by the activity, +allowing the user to return to a dismissed fragment.
    + +
    {@link android.app.ListFragment}
    +
    Displays a list of items that are managed by an adapter (such as a {@link +android.widget.SimpleCursorAdapter}), similar to {@link android.app.ListActivity}. It provides +several methods for managing a list view, such as the {@link +android.app.ListFragment#onListItemClick(ListView,View,int,long) onListItemClick()} callback to +handle click events.
    + +
    {@link android.preference.PreferenceFragment}
    +
    Displays a hierarchy of {@link android.preference.Preference} objects as a list, similar to +{@link android.preference.PreferenceActivity}. This is useful when creating a "settings" +activity for your application.
    +
    + + +

    Adding a user interface

    + +

    A fragment is usually used as part of an activity's user interface and contributes its own +layout to the activity.

    + +

    To provide a layout for a fragment, you must implement the {@link +android.app.Fragment#onCreateView onCreateView()} callback method, which the Android system calls +when it's time for the fragment to draw its layout. Your implementation of this method must return a +{@link android.view.View} that is the root of your fragment's layout.

    + +

    Note: If your fragment is a subclass of {@link +android.app.ListFragment}, the default implementation returns a {@link android.widget.ListView} from +{@link android.app.Fragment#onCreateView onCreateView()}, so you don't need to implement it.

    + +

    To return a layout from {@link +android.app.Fragment#onCreateView onCreateView()}, you can inflate it from a layout resource defined in XML. To +help you do so, {@link android.app.Fragment#onCreateView onCreateView()} provides a +{@link android.view.LayoutInflater} object.

    + +

    For example, here's a subclass of {@link android.app.Fragment} that loads a layout from the +{@code example_fragment.xml} file:

    + +
    +public static class ExampleFragment extends Fragment {
    +    @Override
    +    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    +                             Bundle savedInstanceState) {
    +        // Inflate the layout for this fragment
    +        return inflater.inflate(R.layout.example_fragment, container, false);
    +    }
    +}
    +
    + + + +

    The {@code container} parameter passed to {@link android.app.Fragment#onCreateView +onCreateView()} is the parent {@link android.view.ViewGroup} (from the activity's layout) in which +your fragment layout +will be inserted. The {@code savedInstanceState} parameter is a {@link android.os.Bundle} that +provides data about the previous instance of the fragment, if the fragment is being resumed +(restoring state is discussed more in the section about Handling the +Fragment Lifecycle).

    + +

    The {@link android.view.LayoutInflater#inflate(int,ViewGroup,boolean) inflate()} method takes +three arguments:

    +
      +
    • The resource ID of the layout you want to inflate.
    • +
    • The {@link android.view.ViewGroup} to be the parent of the inflated layout. Passing the {@code +container} is important in order for the system to apply layout parameters to the root view of the +inflated layout, specified by the parent view in which it's going.
    • +
    • A boolean indicating whether the inflated layout should be attached to the {@link +android.view.ViewGroup} (the second parameter) during inflation. (In this case, this +is false because the system is already inserting the inflated layout into the {@code +container}—passing true would create a redundant view group in the final layout.)
    • +
    + +

    Now you've seen how to create a fragment that provides a layout. Next, you need to add +the fragment to your activity.

    + + + +

    Adding a fragment to an activity

    + +

    Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part +of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity +layout:

    + +
      +
    • Declare the fragment inside the activity's layout file. +

      In this case, you can +specify layout properties for the fragment as if it were a view. For example, here's the layout +file for an activity with two fragments:

      +
      +<?xml version="1.0" encoding="utf-8"?>
      +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      +    android:orientation="horizontal"
      +    android:layout_width="match_parent"
      +    android:layout_height="match_parent">
      +    <fragment android:name="com.example.news.ArticleListFragment"
      +            android:id="@+id/list"
      +            android:layout_weight="1"
      +            android:layout_width="0dp"
      +            android:layout_height="match_parent" />
      +    <fragment android:name="com.example.news.ArticleReaderFragment"
      +            android:id="@+id/viewer"
      +            android:layout_weight="2"
      +            android:layout_width="0dp"
      +            android:layout_height="match_parent" />
      +</LinearLayout>
      +
      +

      The {@code android:name} attribute in the {@code <fragment>} specifies the {@link +android.app.Fragment} class to instantiate in the layout.

      + +

      When the system creates this activity layout, it instantiates each fragment specified in the +layout and calls the {@link android.app.Fragment#onCreateView onCreateView()} method for each one, +to retrieve each fragment's layout. The system inserts the {@link android.view.View} returned by the +fragment directly in place of the {@code <fragment>} element.

      + +
      +

      Note: Each fragment requires a unique identifier that +the system can use to restore the fragment if the activity is restarted (and which you can use to +capture the fragment to perform transactions, such as remove it). There are three ways to provide an +ID for a fragment:

      +
        +
      • Supply the {@code android:id} attribute with a unique ID.
      • +
      • Supply the {@code android:tag} attribute with a unique string.
      • +
      • If you provide neither of the previous two, the system uses the ID of the container +view.
      • +
      +
      +
    • + +
    • Or, programmatically add the fragment to an existing {@link android.view.ViewGroup}. +

      At any time while your activity is running, you can add fragments to your activity layout. You +simply need to specify a {@link +android.view.ViewGroup} in which to place the fragment.

      +

      To make fragment transactions in your activity (such as add, remove, or replace a +fragment), you must use APIs from {@link android.app.FragmentTransaction}. You can get an instance +of {@link android.app.FragmentTransaction} from your {@link android.app.Activity} like this:

      + +
      +FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()}
      +FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
      +
      + +

      You can then add a fragment using the {@link +android.app.FragmentTransaction#add(int,Fragment) add()} method, specifying the fragment to add and +the view in which to insert it. For example:

      + +
      +ExampleFragment fragment = new ExampleFragment();
      +fragmentTransaction.add(R.id.fragment_container, fragment);
      +fragmentTransaction.commit();
      +
      + +

      The first argument passed to {@link android.app.FragmentTransaction#add(int,Fragment) add()} +is the {@link android.view.ViewGroup} in which the fragment should be placed, specified by +resource ID, and the second parameter is the fragment to add.

      +

      Once you've made your changes with +{@link android.app.FragmentTransaction}, you must +call {@link android.app.FragmentTransaction#commit} for the changes to take effect.

      +
    • +
    + + +

    Adding a fragment without a UI

    + +

    The examples above show how to add a fragment to your activity in order to provide a UI. However, +you can also use a fragment to provide a background behavior for the activity without presenting +additional UI.

    + +

    To add a fragment without a UI, add the fragment from the activity using {@link +android.app.FragmentTransaction#add(Fragment,String)} (supplying a unique string "tag" for the +fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a +view in the activity layout, it does not receive a call to {@link +android.app.Fragment#onCreateView onCreateView()}. So you don't need to implement that method.

    + +

    Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also +supply string tags to fragments that do have a UI—but if the fragment does not have a +UI, then the string tag is the only way to identify it. If you want to get the fragment from the +activity later, you need to use {@link android.app.FragmentManager#findFragmentByTag +findFragmentByTag()}.

    + +

    For an example activity that uses a fragment as a background worker, without a UI, see the {@code +FragmentRetainInstance.java} sample.

    + + + +

    Managing Fragments

    + +

    To manage the fragments in your activity, you need to use {@link android.app.FragmentManager}. To +get it, call {@link android.app.Activity#getFragmentManager()} from your activity.

    + +

    Some things that you can do with {@link android.app.FragmentManager} include:

    + +
      +
    • Get fragments that exist in the activity, with {@link +android.app.FragmentManager#findFragmentById findFragmentById()} (for fragments that provide a UI in +the activity layout) or {@link android.app.FragmentManager#findFragmentByTag +findFragmentByTag()} (for fragments that do or don't provide a UI).
    • +
    • Pop fragments off the back stack, with {@link +android.app.FragmentManager#popBackStack()} (simulating a Back command by the user).
    • +
    • Register a listener for changes to the back stack, with {@link +android.app.FragmentManager#addOnBackStackChangedListener addOnBackStackChangedListener()}.
    • +
    + +

    For more information about these methods and others, refer to the {@link +android.app.FragmentManager} class documentation.

    + +

    As demonstrated in the previous section, you can also use {@link android.app.FragmentManager} +to open a {@link android.app.FragmentTransaction}, which allows you to perform transactions, such as +add and remove fragments.

    + + +

    Performing Fragment Transactions

    + +

    A great feature about using fragments in your activity is the ability to add, remove, replace, +and perform other actions with them, in response to user interaction. Each set of changes that you +commit to the activity is called a transaction and you can perform one using APIs in {@link +android.app.FragmentTransaction}. You can also save each transaction to a back stack managed by the +activity, allowing the user to navigate backward through the fragment changes (similar to navigating +backward through activities).

    + +

    You can acquire an instance of {@link android.app.FragmentTransaction} from the {@link +android.app.FragmentManager} like this:

    + +
    +FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()};
    +FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
    +
    + +

    Each transaction is a set of changes that you want to perform at the same time. You can set +up all the changes you want to perform for a given transaction using methods such as {@link +android.app.FragmentTransaction#add add()}, {@link android.app.FragmentTransaction#remove remove()}, +and {@link android.app.FragmentTransaction#replace replace()}. Then, to apply the transaction +to the activity, you must call {@link android.app.FragmentTransaction#commit()}.

    + + +

    Before you call {@link +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 button.

    + +

    For example, here's how you can replace one fragment with another, and preserve the previous +state in the back stack:

    + +
    +// Create new fragment and transaction
    +Fragment newFragment = new ExampleFragment();
    +FragmentTransaction transaction = getFragmentManager().beginTransaction();
    +
    +// Replace whatever is in the fragment_container view with this fragment,
    +// and add the transaction to the back stack
    +transaction.replace(R.id.fragment_container, newFragment);
    +transaction.addToBackStack(null);
    +
    +// Commit the transaction
    +transaction.commit();
    +
    + +

    In this example, {@code newFragment} replaces whatever fragment (if any) is currently in the +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 button.

    + +

    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 button will reverse them all together.

    + +

    The order in which you add changes to a {@link android.app.FragmentTransaction} doesn't matter, +except:

    +
      +
    • You must call {@link android.app.FragmentTransaction#commit()} last
    • +
    • If you're adding multiple fragments to the same container, then the order in which +you add them determines the order they appear in the view hierarchy
    • +
    + +

    If you do not call {@link android.app.FragmentTransaction#addToBackStack(String) +addToBackStack()} when you perform a transaction that removes a fragment, then that fragment is +destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you +do call {@link android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} when +removing a fragment, then the fragment is stopped and will be resumed if the user navigates +back.

    + +

    Tip: For each fragment transaction, you can apply a transition +animation, by calling {@link android.app.FragmentTransaction#setTransition setTransition()} before +you commit.

    + +

    Calling {@link android.app.FragmentTransaction#commit()} does not perform the transaction +immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon +as the thread is able to do so. If necessary, however, you may call {@link +android.app.FragmentManager#executePendingTransactions()} from your UI thread to immediately execute +transactions submitted by {@link android.app.FragmentTransaction#commit()}. Doing so is +usually not necessary unless the transaction is a dependency for jobs in other threads.

    + +

    Caution: You can commit a transaction using {@link +android.app.FragmentTransaction#commit commit()} only prior to the activity saving its +state (when the user leaves the activity). If you attempt to commit after that point, an +exception will be thrown. This is because the state after the commit can be lost if the activity +needs to be restored. For situations in which its okay that you lose the commit, use {@link +android.app.FragmentTransaction#commitAllowingStateLoss()}.

    + + + + +

    Communicating with the Activity

    + +

    Although a {@link android.app.Fragment} is implemented as an object that's independent from an +{@link android.app.Activity} and can be used inside multiple activities, a given instance of +a fragment is directly tied to the activity that contains it.

    + +

    Specifically, the fragment can access the {@link android.app.Activity} instance with {@link +android.app.Fragment#getActivity()} and easily perform tasks such as find a view in the +activity layout:

    + +
    +View listView = {@link android.app.Fragment#getActivity()}.{@link android.app.Activity#findViewById findViewById}(R.id.list);
    +
    + +

    Likewise, your activity can call methods in the fragment by acquiring a reference to the +{@link android.app.Fragment} from {@link android.app.FragmentManager}, using {@link +android.app.FragmentManager#findFragmentById findFragmentById()} or {@link +android.app.FragmentManager#findFragmentByTag findFragmentByTag()}. For example:

    + +
    +ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
    +
    + + +

    Creating event callbacks to the activity

    + +

    In some cases, you might need a fragment to share events with the activity. A good way to do that +is to define a callback interface inside the fragment and require that the host activity implement +it. When the activity receives a callback through the interface, it can share the information with +other fragments in the layout as necessary.

    + +

    For example, if a news application has two fragments in an activity—one to show a list of +articles (fragment A) and another to display an article (fragment B)—then fragment A must tell +the activity when a list item is selected so that it can tell fragment B to display the article. In +this case, the {@code OnArticleSelectedListener} interface is declared inside fragment A:

    + +
    +public static class FragmentA extends ListFragment {
    +    ...
    +    // Container Activity must implement this interface
    +    public interface OnArticleSelectedListener {
    +        public void onArticleSelected(Uri articleUri);
    +    }
    +    ...
    +}
    +
    + +

    Then the activity that hosts the fragment implements the {@code OnArticleSelectedListener} +interface and +overrides {@code onArticleSelected()} to notify fragment B of the event from fragment A. To ensure +that the host activity implements this interface, fragment A's {@link +android.app.Fragment#onAttach onAttach()} callback method (which the system calls when adding +the fragment to the activity) instantiates an instance of {@code OnArticleSelectedListener} by +casting the {@link android.app.Activity} that is passed into {@link android.app.Fragment#onAttach +onAttach()}:

    + +
    +public static class FragmentA extends ListFragment {
    +    OnArticleSelectedListener mListener;
    +    ...
    +    @Override
    +    public void onAttach(Activity activity) {
    +        super.onAttach(activity);
    +        try {
    +            mListener = (OnArticleSelectedListener) activity;
    +        } catch (ClassCastException e) {
    +            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
    +        }
    +    }
    +    ...
    +}
    +
    + +

    If the activity has not implemented the interface, then the fragment throws a +{@link java.lang.ClassCastException}. +On success, the {@code mListener} member holds a reference to activity's implementation of +{@code OnArticleSelectedListener}, so that fragment A can share events with the activity by calling +methods defined by the {@code OnArticleSelectedListener} interface. For example, if fragment A is an +extension of {@link android.app.ListFragment}, each time +the user clicks a list item, the system calls {@link android.app.ListFragment#onListItemClick +onListItemClick()} in the fragment, which then calls {@code onArticleSelected()} to share +the event with the activity:

    + +
    +public static class FragmentA extends ListFragment {
    +    OnArticleSelectedListener mListener;
    +    ...
    +    @Override
    +    public void onListItemClick(ListView l, View v, int position, long id) {
    +        // Append the clicked item's row ID with the content provider Uri
    +        Uri noteUri = ContentUris.{@link android.content.ContentUris#withAppendedId withAppendedId}(ArticleColumns.CONTENT_URI, id);
    +        // Send the event and Uri to the host activity
    +        mListener.onArticleSelected(noteUri);
    +    }
    +    ...
    +}
    +
    + +

    The {@code id} parameter passed to {@link +android.app.ListFragment#onListItemClick onListItemClick()} is the row ID of the clicked item, +which the activity (or other fragment) uses to fetch the article from the application's {@link +android.content.ContentProvider}.

    + +

    More information about +using a content provider is available in the Content Providers document.

    + + + +

    Adding items to the Action Bar

    + +

    Your fragments can contribute menu items to the activity's Options Menu (and, consequently, the Action Bar) by implementing +{@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. In order +for this method to receive calls, however, you must call {@link +android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} during {@link +android.app.Fragment#onCreate(Bundle) onCreate()}, to indicate that the fragment +would like to add items to the Options Menu (otherwise, the fragment will not receive a call to +{@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()}).

    + +

    Any items that you then add to the Options Menu from the fragment are appended to the existing +menu items. The fragment also receives callbacks to {@link +android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} when a menu item +is selected.

    + +

    You can also register a view in your fragment layout to provide a context menu by calling {@link +android.app.Fragment#registerForContextMenu(View) registerForContextMenu()}. When the user opens +the context menu, the fragment receives a call to {@link +android.app.Fragment#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo) +onCreateContextMenu()}. When the user selects an item, the fragment receives a call to {@link +android.app.Fragment#onContextItemSelected(MenuItem) onContextItemSelected()}.

    + +

    Note: Although your fragment receives an on-item-selected callback +for each menu item it adds, the activity is first to receive the respective callback when the user +selects a menu item. If the activity's implementation of the on-item-selected callback does not +handle the selected item, then the event is passed to the fragment's callback. This is true for +the Options Menu and context menus.

    + +

    For more information about menus, see the Menus and Action Bar developer guides.

    + + + + +

    Handling the Fragment Lifecycle

    + +
    + +

    Figure 3. The effect of the activity lifecycle on the fragment +lifecycle.

    +
    + +

    Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like +an activity, a fragment can exist in three states:

    + +
    +
    Resumed
    +
    The fragment is visible in the running activity.
    + +
    Paused
    +
    Another activity is in the foreground and has focus, but the activity in which this +fragment lives is still visible (the foreground activity is partially transparent or doesn't +cover the entire screen).
    + +
    Stopped
    +
    The fragment is not visible. Either the host activity has been stopped or the +fragment has been removed from the activity but added to the back stack. A stopped fragment is +still alive (all state and member information is retained by the system). However, it is no longer +visible to the user and will be killed if the activity is killed.
    +
    + +

    Also like an activity, you can retain the state of a fragment using a {@link +android.os.Bundle}, in case the activity's process is killed and you need to restore the +fragment state when the activity is recreated. You can save the state during the fragment's {@link +android.app.Fragment#onSaveInstanceState onSaveInstanceState()} callback and restore it during +either {@link android.app.Fragment#onCreate onCreate()}, {@link +android.app.Fragment#onCreateView onCreateView()}, or {@link +android.app.Fragment#onActivityCreated onActivityCreated()}. For more information about saving +state, see the Activities +document.

    + +

    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 button, as discussed in Tasks and Back Stack). +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 +android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} during a transaction that +removes the fragment.

    + +

    Otherwise, managing the fragment lifecycle is very similar to managing the activity +lifecycle. So, the same practices for managing the activity +lifecycle also apply to fragments. What you also need to understand, though, is how the life +of the activity affects the life of the fragment.

    + + +

    Coordinating with the activity lifecycle

    + +

    The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the +fragment, such that each lifecycle callback for the activity results in a similar callback for each +fragment. For example, when the activity receives {@link android.app.Activity#onPause}, each +fragment in the activity receives {@link android.app.Fragment#onPause}.

    + +

    Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the +activity in order to perform actions such as build and destroy the fragment's UI. These additional +callback methods are:

    + +
    +
    {@link android.app.Fragment#onAttach onAttach()}
    +
    Called when the fragment has been associated with the activity (the {@link +android.app.Activity} is passed in here).
    +
    {@link android.app.Fragment#onCreateView onCreateView()}
    +
    Called to create the view hierarchy associated with the fragment.
    +
    {@link android.app.Fragment#onActivityCreated onActivityCreated()}
    +
    Called when the activity's {@link android.app.Activity#onCreate +onCreate()} method has returned.
    +
    {@link android.app.Fragment#onDestroyView onDestroyView()}
    +
    Called when the view hierarchy associated with the fragment is being removed.
    +
    {@link android.app.Fragment#onDetach onDetach()}
    +
    Called when the fragment is being disassociated from the activity.
    +
    + +

    The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated +by figure 3. In this figure, you can see how each successive state of the activity determines which +callback methods a fragment may receive. For example, when the activity has received its {@link +android.app.Activity#onCreate onCreate()} callback, a fragment in the activity receives no more than +the {@link android.app.Fragment#onActivityCreated onActivityCreated()} callback.

    + +

    Once the activity reaches the resumed state, you can freely add and remove fragments to the +activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment +change independently.

    + +

    However, when the activity leaves the resumed state, the fragment again is pushed through its +lifecycle by the activity.

    + + + + +

    Example

    + +

    To bring everything discussed in this document together, here's an example of an activity +using two fragments to create a two-pane layout. The activity below includes one fragment to +show a list of Shakespeare play titles and another to show a summary of the play when selected +from the list. It also demonstrates how to provide different configurations of the fragments, +based on the screen configuration.

    + +

    Note: The complete source code for this activity is available in +{@code +FragmentLayout.java}.

    + +

    The main activity applies a layout in the usual way, during {@link +android.app.Activity#onCreate onCreate()}:

    + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java main} + +

    The layout applied is {@code fragment_layout.xml}:

    + +{@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout} + +

    Using this layout, the system instantiates the {@code TitlesFragment} (which lists the play +titles) as soon as the activity loads the layout, while the {@link android.widget.FrameLayout} +(where the fragment for showing the play summary will go) consumes space on the right side of the +screen, but remains empty at first. As you'll see below, it's not until the user selects an item +from the list that a fragment is placed into the {@link android.widget.FrameLayout}.

    + +

    However, not all screen configurations are wide enough to show both the list of +plays and the summary, side by side. So, the layout above is used only for the landscape +screen configuration, by saving it at {@code res/layout-land/fragment_layout.xml}.

    + +

    Thus, when the screen is in portrait orientation, the system applies the following layout, which +is saved at {@code res/layout/fragment_layout.xml}:

    + +{@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout} + +

    This layout includes only {@code TitlesFragment}. This means that, when the device is in +portrait orientation, only the list of play titles is visible. So, when the user clicks a list +item in this configuration, the application will start a new activity to show the summary, +instead of loading a second fragment.

    + +

    Next, you can see how this is accomplished in the fragment classes. First is {@code +TitlesFragment}, which shows the list of Shakespeare play titles. This fragment extends {@link +android.app.ListFragment} and relies on it to handle most of the list view work.

    + +

    As you inspect this code, notice that there are two possible behaviors when the user clicks a +list item: depending on which of the two layouts is active, it can either create and display a new +fragment to show the details in the same activity (adding the fragment to the {@link +android.widget.FrameLayout}), or start a new activity (where the fragment can be shown).

    + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java titles} + +

    The second fragment, {@code DetailsFragment} shows the play summary for the item selected from +the list from {@code TitlesFragment}:

    + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details} + +

    Recall from the {@code TitlesFragment} class, that, if the user clicks a list item and the +current layout does not include the {@code R.id.details} view (which is where the +{@code DetailsFragment} belongs), then the application starts the {@code DetailsActivity} +activity to display the content of the item.

    + +

    Here is the {@code DetailsActivity}, which simply embeds the {@code DetailsFragment} to display +the selected play summary when the screen is in portrait orientation:

    + +{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java +details_activity} + +

    Notice that this activity finishes itself if the configuration is landscape, so that the main +activity can take over and display the {@code DetailsFragment} alongside the {@code TitlesFragment}. +This can happen if the user begins the {@code DetailsActivity} while in portrait orientation, but +then rotates to landscape (which restarts the current activity).

    + + +

    For more samples using fragments (and complete source files for this example), +see the sample code available in +ApiDemos (available for download from the Samples SDK component).

    + + diff --git a/docs/html/guide/components/fundamentals.jd b/docs/html/guide/components/fundamentals.jd new file mode 100644 index 000000000000..1717782129b4 --- /dev/null +++ b/docs/html/guide/components/fundamentals.jd @@ -0,0 +1,518 @@ +page.title=Application Fundamentals +@jd:body + +
    +
    + +

    Quickview

    +
      +
    • Android applications are composed of one or more application components (activities, +services, content providers, and broadcast receivers)
    • +
    • Each component performs a different role in the overall application behavior, and each +one can be activated individually (even by other applications)
    • +
    • The manifest file must declare all components in the application and should also declare +all application requirements, such as the minimum version of Android required and any hardware +configurations required
    • +
    • Non-code application resources (images, strings, layout files, etc.) should include +alternatives for different device configurations (such as different strings for different +languages and different layouts for different screen sizes)
    • +
    + + +

    In this document

    +
      +
    1. Application Components +
        +
      1. Activating components
      2. +
      +
    2. +
    3. The Manifest File +
        +
      1. Declaring components
      2. +
      3. Declaring application requirements
      4. +
      +
    4. +
    5. Application Resources
    6. +
    +
    +
    + +

    Android applications are written in the Java programming language. The Android SDK tools compile +the code—along with any data and resource files—into an Android package, an +archive file with an {@code .apk} suffix. All the code in a single {@code .apk} file is considered +to be one application and is the file that Android-powered devices use to install the +application.

    + +

    Once installed on a device, each Android application lives in its own security sandbox:

    + +
      +
    • The Android operating system is a multi-user Linux system in which each application is a +different user.
    • + +
    • By default, the system assigns each application a unique Linux user ID (the ID is used only by +the system and is unknown to the application). The system sets permissions for all the files in an +application so that only the user ID assigned to that application can access them.
    • + +
    • Each process has its own virtual machine (VM), so an application's code runs in isolation from +other applications.
    • + +
    • By default, every application runs in its own Linux process. Android starts the process when any +of the application's components need to be executed, then shuts down the process when it's no longer +needed or when the system must recover memory for other applications.
    • +
    + +

    In this way, the Android system implements the principle of least privilege. That is, +each application, by default, has access only to the components that it requires to do its work and +no more. This creates a very secure environment in which an application cannot access parts of +the system for which it is not given permission.

    + +

    However, there are ways for an application to share data with other applications and for an +application to access system services:

    + +
      +
    • It's possible to arrange for two applications to share the same Linux user ID, in which case +they are able to access each other's files. To conserve system resources, applications with the +same user ID can also arrange to run in the same Linux process and share the same VM (the +applications must also be signed with the same certificate).
    • +
    • An application can request permission to access device data such as the user's +contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All +application permissions must be granted by the user at install time.
    • +
    + +

    That covers the basics regarding how an Android application exists within the system. The rest of +this document introduces you to:

    +
      +
    • The core framework components that define your application.
    • +
    • The manifest file in which you declare components and required device features for your +application.
    • +
    • Resources that are separate from the application code and allow your application to +gracefully optimize its behavior for a variety of device configurations.
    • +
    + + + + +

    Application Components

    + +

    Application components are the essential building blocks of an Android application. Each +component is a different point through which the system can enter your application. Not all +components are actual entry points for the user and some depend on each other, but each one exists +as its own entity and plays a specific role—each one is a unique building block that +helps define your application's overall behavior.

    + +

    There are four different types of application components. Each type serves a distinct purpose +and has a distinct lifecycle that defines how the component is created and destroyed.

    + +

    Here are the four types of application components:

    + +
    + +
    Activities
    + +
    An activity represents a single screen with a user interface. For example, +an email application might have one activity that shows a list of new +emails, another activity to compose an email, and another activity for reading emails. Although +the activities work together to form a cohesive user experience in the email application, each one +is independent of the others. As such, a different application can start any one of these +activities (if the email application allows it). For example, a camera application can start the +activity in the email application that composes new mail, in order for the user to share a picture. + +

    An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more +about it in the Activities +developer guide.

    +
    + + +
    Services
    + +
    A service is a component that runs in the background to perform long-running +operations or to perform work for remote processes. A service +does not provide a user interface. For example, a service might play music in the background while +the user is in a different application, or it might fetch data over the network without +blocking user interaction with an activity. Another component, such as an activity, can start the +service and let it run or bind to it in order to interact with it. + +

    A service is implemented as a subclass of {@link android.app.Service} and you can learn more +about it in the Services developer +guide.

    +
    + + +
    Content providers
    + +
    A content provider manages a shared set of application data. You can store the data in +the file system, an SQLite database, on the web, or any other persistent storage location your +application can access. Through the content provider, other applications can query or even modify +the data (if the content provider allows it). For example, the Android system provides a content +provider that manages the user's contact information. As such, any application with the proper +permissions can query part of the content provider (such as {@link +android.provider.ContactsContract.Data}) to read and write information about a particular person. + +

    Content providers are also useful for reading and writing data that is private to your +application and not shared. For example, the Note Pad sample application uses a +content provider to save notes.

    + +

    A content provider is implemented as a subclass of {@link android.content.ContentProvider} +and must implement a standard set of APIs that enable other applications to perform +transactions. For more information, see the Content Providers developer +guide.

    +
    + + +
    Broadcast receivers
    + +
    A broadcast receiver is a component that responds to system-wide broadcast +announcements. Many broadcasts originate from the system—for example, a broadcast announcing +that the screen has turned off, the battery is low, or a picture was captured. +Applications can also initiate broadcasts—for example, to let other applications know that +some data has been downloaded to the device and is available for them to use. Although broadcast +receivers don't display a user interface, they may create a status bar notification +to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is +just a "gateway" to other components and is intended to do a very minimal amount of work. For +instance, it might initiate a service to perform some work based on the event. + +

    A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver} +and each broadcast is delivered as an {@link android.content.Intent} object. For more information, +see the {@link android.content.BroadcastReceiver} class.

    +
    + +
    + + + +

    A unique aspect of the Android system design is that any application can start another +application’s component. For example, if you want the user to capture a +photo with the device camera, there's probably another application that does that and your +application can use it, instead of developing an activity to capture a photo yourself. You don't +need to incorporate or even link to the code from the camera application. +Instead, you can simply start the activity in the camera application that captures a +photo. When complete, the photo is even returned to your application so you can use it. To the user, +it seems as if the camera is actually a part of your application.

    + +

    When the system starts a component, it starts the process for that application (if it's not +already running) and instantiates the classes needed for the component. For example, if your +application starts the activity in the camera application that captures a photo, that activity +runs in the process that belongs to the camera application, not in your application's process. +Therefore, unlike applications on most other systems, Android applications don't have a single entry +point (there's no {@code main()} function, for example).

    + +

    Because the system runs each application in a separate process with file permissions that +restrict access to other applications, your application cannot directly activate a component from +another application. The Android system, however, can. So, to activate a component in +another application, you must deliver a message to the system that specifies your intent to +start a particular component. The system then activates the component for you.

    + + +

    Activating Components

    + +

    Three of the four component types—activities, services, and +broadcast receivers—are activated by an asynchronous message called an intent. +Intents bind individual components to each other at runtime (you can think of them +as the messengers that request an action from other components), whether the component belongs +to your application or another.

    + +

    An intent is created with an {@link android.content.Intent} object, which defines a message to +activate either a specific component or a specific type of component—an intent +can be either explicit or implicit, respectively.

    + +

    For activities and services, an intent defines the action to perform (for example, to "view" or +"send" something) and may specify the URI of the data to act on (among other things that the +component being started might need to know). For example, an intent might convey a request for an +activity to show an image or to open a web page. In some cases, you can start an +activity to receive a result, in which case, the activity also returns +the result in an {@link android.content.Intent} (for example, you can issue an intent to let +the user pick a personal contact and have it returned to you—the return intent includes a +URI pointing to the chosen contact).

    + +

    For broadcast receivers, the intent simply defines the +announcement being broadcast (for example, a broadcast to indicate the device battery is low +includes only a known action string that indicates "battery is low").

    + +

    The other component type, content provider, is not activated by intents. Rather, it is +activated when targeted by a request from a {@link android.content.ContentResolver}. The content +resolver handles all direct transactions with the content provider so that the component that's +performing transactions with the provider doesn't need to and instead calls methods on the {@link +android.content.ContentResolver} object. This leaves a layer of abstraction between the content +provider and the component requesting information (for security).

    + +

    There are separate methods for activating each type of component:

    +
      +
    • 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 +startActivity()} or {@link android.app.Activity#startActivityForResult startActivityForResult()} +(when you want the activity to return a result).
    • +
    • You can start a service (or give new instructions to an ongoing service) by +passing an {@link android.content.Intent} to {@link android.content.Context#startService +startService()}. Or you can bind to the service by passing an {@link android.content.Intent} to +{@link android.content.Context#bindService bindService()}.
    • +
    • You can initiate a broadcast by passing an {@link android.content.Intent} to methods like +{@link android.content.Context#sendBroadcast(Intent) sendBroadcast()}, {@link +android.content.Context#sendOrderedBroadcast(Intent, String) sendOrderedBroadcast()}, or {@link +android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.
    • +
    • You can perform a query to a content provider by calling {@link +android.content.ContentProvider#query query()} on a {@link android.content.ContentResolver}.
    • +
    + +

    For more information about using intents, see the Intents and +Intent Filters document. More information about activating specific components is also provided +in the following documents: Activities, Services, {@link +android.content.BroadcastReceiver} and Content Providers.

    + + +

    The Manifest File

    + +

    Before the Android system can start an application component, the system must know that the +component exists by reading the application's {@code AndroidManifest.xml} file (the "manifest" +file). Your application must declare all its components in this file, which must be at the root of +the application project directory.

    + +

    The manifest does a number of things in addition to declaring the application's components, +such as:

    +
      +
    • Identify any user permissions the application requires, such as Internet access or +read-access to the user's contacts.
    • +
    • Declare the minimum API Level +required by the application, based on which APIs the application uses.
    • +
    • Declare hardware and software features used or required by the application, such as a camera, +bluetooth services, or a multitouch screen.
    • +
    • API libraries the application needs to be linked against (other than the Android framework +APIs), such as the Google Maps +library.
    • +
    • And more
    • +
    + + +

    Declaring components

    + +

    The primary task of the manifest is to inform the system about the application's components. For +example, a manifest file can declare an activity as follows:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<manifest ... >
    +    <application android:icon="@drawable/app_icon.png" ... >
    +        <activity android:name="com.example.project.ExampleActivity"
    +                  android:label="@string/example_label" ... >
    +        </activity>
    +        ...
    +    </application>
    +</manifest>
    + +

    In the <application> +element, the {@code android:icon} attribute points to resources for an icon that identifies the +application.

    + +

    In the <activity> element, +the {@code android:name} attribute specifies the fully qualified class name of the {@link +android.app.Activity} subclass and the {@code android:label} attributes specifies a string +to use as the user-visible label for the activity.

    + +

    You must declare all application components this way:

    + + +

    Activities, services, and content providers that you include in your source but do not declare +in the manifest are not visible to the system and, consequently, can never run. However, +broadcast +receivers can be either declared in the manifest or created dynamically in code (as +{@link android.content.BroadcastReceiver} objects) and registered with the system by calling +{@link android.content.Context#registerReceiver registerReceiver()}.

    + +

    For more about how to structure the manifest file for your application, see the The AndroidManifest.xml File +documentation.

    + + + +

    Declaring component capabilities

    + +

    As discussed above, in Activating Components, you can use an +{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so +by explicitly naming the target component (using the component class name) in the intent. However, +the real power of intents lies in the concept of intent actions. With intent actions, you simply +describe the type of action you want to perform (and optionally, the data upon which you’d like to +perform the action) and allow the system to find a component on the device that can perform the +action and start it. If there are multiple components that can perform the action described by the +intent, then the user selects which one to use.

    + +

    The way the system identifies the components that can respond to an intent is by comparing the +intent received to the intent filters provided in the manifest file of other applications on +the device.

    + +

    When you declare a component in your application's manifest, you can optionally include +intent filters that declare the capabilities of the component so it can respond to intents +from other applications. You can declare an intent filter for your component by +adding an {@code +<intent-filter>} element as a child of the component's declaration element.

    + +

    For example, an email application with an activity for composing a new email might declare an +intent filter in its manifest entry to respond to "send" intents (in order to send email). An +activity in your application can then create an intent with the “send” action ({@link +android.content.Intent#ACTION_SEND}), which the system matches to the email application’s “send” +activity and launches it when you invoke the intent with {@link android.app.Activity#startActivity +startActivity()}.

    + +

    For more about creating intent filters, see the Intents and Intent Filters document. +

    + + + +

    Declaring application requirements

    + +

    There are a variety of devices powered by Android and not all of them provide the +same features and capabilities. In order to prevent your application from being installed on devices +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 Google Play do read them in order to provide filtering +for users when they search for applications from their device.

    + +

    For example, if your application requires a camera and uses APIs introduced in Android 2.1 (API Level 7), you should declare these as +requirements in your manifest file. That way, devices that do not have a camera and have an +Android version lower than 2.1 cannot install your application from Google Play.

    + +

    However, you can also declare that your application uses the camera, but does not +require 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.

    + +

    Here are some of the important device characteristics that you should consider as you design and +develop your application:

    + +
    +
    Screen size and density
    +
    In order to categorize devices by their screen type, Android defines two characteristics for +each device: screen size (the physical dimensions of the screen) and screen density (the physical +density of the pixels on the screen, or dpi—dots per inch). To simplify all the different +types of screen configurations, the Android system generalizes them into select groups that make +them easier to target. +

    The screen sizes are: small, normal, large, and extra large.
    +The screen densities are: low density, medium density, high density, and extra high density.

    + +

    By default, your application is compatible with all screen sizes and densities, +because the Android system makes the appropriate adjustments to your UI layout and image +resources. However, you should create specialized layouts for certain screen sizes and provide +specialized images for certain densities, using alternative layout resources, and by declaring in +your manifest exactly which screen sizes your application supports with the {@code +<supports-screens>} element.

    +

    For more information, see the Supporting Multiple Screens +document.

    + +
    Input configurations
    +
    Many devices provide a different type of user input mechanism, such as a hardware keyboard, a +trackball, or a five-way navigation pad. If your application requires a particular kind of input +hardware, then you should declare it in your manifest with the {@code +<uses-configuration>} element. However, it is rare that an application should require +a certain input configuration.
    + +
    Device features
    +
    There are many hardware and software features that may or may not exist on a given +Android-powered device, such as a camera, a light sensor, bluetooth, a certain +version of OpenGL, or the fidelity of the touchscreen. You should never assume that a certain +feature is available on all Android-powered devices (other than the availability of the standard +Android library), so you should declare any features used by your application with the {@code <uses-feature>} +element.
    + +
    Platform Version
    +
    Different Android-powered devices often run different versions of the Android platform, +such as Android 1.6 or Android 2.3. Each successive version often includes additional APIs not +available in the previous version. In order to indicate which set of APIs are available, each +platform version specifies an API Level (for example, Android 1.0 is API Level +1 and Android 2.3 is API Level 9). If you use any APIs that were added to the platform after +version 1.0, you should declare the minimum API Level in which those APIs were introduced using the +{@code <uses-sdk>} +element.
    +
    + +

    It's important that you declare all such requirements for your application, because, when you +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.

    + +

    For more information about how Google Play filters applications based on these (and other) +requirements, see the Filters on Google Play +document.

    + + + +

    Application Resources

    + +

    An Android application is composed of more than just code—it requires resources that are +separate from the source code, such as images, audio files, and anything relating to the visual +presentation of the application. For example, you should define animations, menus, styles, colors, +and the layout of activity user interfaces with XML files. Using application resources makes it easy +to update various characteristics of your application without modifying code and—by providing +sets of alternative resources—enables you to optimize your application for a variety of +device configurations (such as different languages and screen sizes).

    + +

    For every resource that you include in your Android project, the SDK build tools define a unique +integer ID, which you can use to reference the resource from your application code or from +other resources defined in XML. For example, if your application contains an image file named {@code +logo.png} (saved in the {@code res/drawable/} directory), the SDK tools generate a resource ID +named {@code R.drawable.logo}, which you can use to reference the image and insert it in your +user interface.

    + +

    One of the most important aspects of providing resources separate from your source code +is the ability for you to provide alternative resources for different device +configurations. For example, by defining UI strings in XML, you can translate the strings into other +languages and save those strings in separate files. Then, based on a language qualifier +that you append to the resource directory's name (such as {@code res/values-fr/} for French string +values) and the user's language setting, the Android system applies the appropriate language strings +to your UI.

    + +

    Android supports many different qualifiers for your alternative resources. The +qualifier is a short string that you include in the name of your resource directories in order to +define the device configuration for which those resources should be used. As another +example, you should often create different layouts for your activities, depending on the +device's screen orientation and size. For example, when the device screen is in portrait +orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in +landscape orientation (wide), the buttons should be aligned horizontally. To change the layout +depending on the orientation, you can define two different layouts and apply the appropriate +qualifier to each layout's directory name. Then, the system automatically applies the appropriate +layout depending on the current device orientation.

    + +

    For more about the different kinds of resources you can include in your application and how +to create alternative resources for various device configurations, see the Application Resources developer guide.

    + + + diff --git a/docs/html/guide/components/index.jd b/docs/html/guide/components/index.jd new file mode 100644 index 000000000000..87bae53bf22a --- /dev/null +++ b/docs/html/guide/components/index.jd @@ -0,0 +1,56 @@ +page.title=App Components +page.landing=true +page.landing.intro=Android's application framework lets you create extremely rich and innovative apps using a set of reusable components. This section explains how Android apps work and how you use components to build them. +page.landing.image=images/develop/app_components.png + +@jd:body + +
    + + + + + +
    diff --git a/docs/html/guide/components/intents-filters.jd b/docs/html/guide/components/intents-filters.jd new file mode 100644 index 000000000000..3ad3c9374a81 --- /dev/null +++ b/docs/html/guide/components/intents-filters.jd @@ -0,0 +1,1055 @@ +page.title=Intents and Intent Filters +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. Intent Objects
    2. +
    3. Intent Resolution
    4. +
    5. Intent filters
    6. +
    7. Common cases
    8. +
    9. Using intent matching
    10. +
    11. Note Pad Example
    12. +
    + +

    Key classes

    +
      +
    1. {@link android.content.Intent}
    2. +
    3. {@link android.content.IntentFilter}
    4. +
    5. {@link android.content.BroadcastReceiver}
    6. +
    7. {@link android.content.pm.PackageManager}
    8. +
    + +
    +
    + + +

    +Three of the core components of an application — activities, services, and +broadcast receivers — are activated through messages, called intents. +Intent messaging is a facility for late run-time binding between components in the same +or different applications. The intent itself, an {@link android.content.Intent} +object, is a passive data structure holding an abstract description of an operation +to be performed — or, often in the case of broadcasts, a description of something +that has happened and is being announced. There are separate mechanisms for +delivering intents to each type of component: +

    + +
      +
    • An Intent object is passed to {@link android.content.Context#startActivity +Context.startActivity()} or {@link android.app.Activity#startActivityForResult +Activity.startActivityForResult()} to launch an activity or get an existing +activity to do something new. (It can also be passed to +{@link android.app.Activity#setResult(int, Intent) Activity.setResult()} +to return information to the activity that called {@code startActivityForResult()}.)
    • + +
    • An Intent object is passed to {@link android.content.Context#startService +Context.startService()} to initiate a service or deliver new instructions to an +ongoing service. Similarly, an intent can be passed to {@link +android.content.Context#bindService Context.bindService()} to establish a +connection between the calling component and a target service. It can optionally +initiate the service if it's not already running.

    • + +
    • Intent objects passed to any of the broadcast methods (such as {@link +android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()}, +{@link android.content.Context#sendOrderedBroadcast(Intent, String) +Context.sendOrderedBroadcast()}, or {@link +android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}) +are delivered to all interested broadcast receivers. Many kinds of broadcasts +originate in system code.

    • +
    + +

    +In each case, the Android system finds the appropriate activity, service, or set +of broadcast receivers to respond to the intent, instantiating them if necessary. +There is no overlap within these messaging systems: Broadcast intents are delivered +only to broadcast receivers, never to activities or services. An intent passed to +{@code startActivity()} is delivered only to an activity, never to a service or +broadcast receiver, and so on. +

    + +

    +This document begins with a description of Intent objects. It then describes the +rules Android uses to map intents to components — how it resolves which +component should receive an intent message. For intents that don't explicitly +name a target component, this process involves testing the Intent object against +intent filters associated with potential targets. +

    + + +

    Intent Objects

    + +

    +An {@link android.content.Intent} object is a bundle of information. It +contains information of interest to the component that receives the intent +(such as the action to be taken and the data to act on) plus information +of interest to the Android system (such as the category of component that +should handle the intent and instructions on how to launch a target activity). +Principally, it can contain the following: +

    + +
    + +
    Component name
    +
    The name of the component that should handle the intent. This field is +a {@link android.content.ComponentName} object — a combination of the +fully qualified class name of the target component (for example "{@code +com.example.project.app.FreneticActivity}") and the package name set +in the manifest file of the application where the component resides (for +example, "{@code com.example.project}"). The package part of the component +name and the package name set in the manifest do not necessarily have to match. + +

    +The component name is optional. If it is set, the Intent object is +delivered to an instance of the designated class. If it is not set, +Android uses other information in the Intent object to locate a suitable +target — see Intent Resolution, later in this +document. +

    + +

    +The component name is set by {@link android.content.Intent#setComponent +setComponent()}, {@link android.content.Intent#setClass +setClass()}, or {@link android.content.Intent#setClassName(String, String) +setClassName()} and read by {@link android.content.Intent#getComponent +getComponent()}. +

    +
    + +

    Action
    +
    A string naming the action to be performed — or, in the case of broadcast +intents, the action that took place and is being reported. The Intent class defines +a number of action constants, including these: +

    + + + + + + + + + + + + + + + +
    ConstantTarget componentAction
    {@code ACTION_CALL} + activity + Initiate a phone call. +
    {@code ACTION_EDIT} + activity + Display data for the user to edit. +
    {@code ACTION_MAIN} + activity + Start up as the initial activity of a task, with no data input and no returned output. +
    {@code ACTION_SYNC} + activity + Synchronize data on a server with data on the mobile device. +
    {@code ACTION_BATTERY_LOW} + broadcast receiver + A warning that the battery is low. +
    {@code ACTION_HEADSET_PLUG} + broadcast receiver + A headset has been plugged into the device, or unplugged from it. +
    {@code ACTION_SCREEN_ON} + broadcast receiver + The screen has been turned on. +
    {@code ACTION_TIMEZONE_CHANGED} + broadcast receiver + The setting for the time zone has changed. +
    + +

    +See the {@link android.content.Intent} class description for a list of +pre-defined constants for generic actions. Other actions are defined +elsewhere in the Android API. +You can also define your own action strings for activating the components +in your application. Those you invent should include the application +package as a prefix — for example: +"com.example.project.SHOW_COLOR". +

    + +

    +The action largely determines how the rest of the intent is structured +— particularly the data and +extras fields — +much as a method name determines a set of arguments and a return value. +For this reason, it's a good idea to use action names that are +as specific as possible, and to couple them tightly to the other fields of +the intent. In other words, instead of defining an action in isolation, +define an entire protocol for the Intent objects your components can handle. +

    + +

    +The action in an Intent object is set by the +{@link android.content.Intent#setAction setAction()} +method and read by +{@link android.content.Intent#getAction getAction()}. +

    +
    + +

    Data
    +
    The URI of the data to be acted on and the MIME type of that data. Different +actions are paired with different kinds of data specifications. For example, if +the action field is {@code ACTION_EDIT}, +the data field would contain the URI of the document to be displayed for editing. +If the action is {@code ACTION_CALL}, the data field would be a {@code tel:} URI +with the number to call. Similarly, if the action is {@code ACTION_VIEW} and the +data field is an {@code http:} URI, the receiving activity would be called upon +to download and display whatever data the URI refers to. + +

    +When matching an intent to a component that is capable of handling the data, +it's often important to know the type of data (its MIME type) in addition to its URI. +For example, a component able to display image data should not be called +upon to play an audio file. +

    + +

    +In many cases, the data type can be inferred from the URI — particularly +{@code content:} URIs, which indicate that the data is located on the device and +controlled by a content provider (see the +separate +discussion on content providers). But the type can also be explicitly set +in the Intent object. +The {@link android.content.Intent#setData setData()} method specifies +data only as a URI, {@link android.content.Intent#setType setType()} +specifies it only as a MIME type, and {@link +android.content.Intent#setDataAndType setDataAndType()} specifies it as both +a URI and a MIME type. The URI is read by {@link +android.content.Intent#getData getData()} and the type by {@link +android.content.Intent#getType getType()}. +

    +
    + +

    Category
    +
    A string containing additional information about the kind of component +that should handle the intent. Any number of category descriptions can be +placed in an Intent object. As it does for actions, the Intent class defines +several category constants, including these: + + + + + + + + + + + +
    ConstantMeaning
    {@code CATEGORY_BROWSABLE} + The target activity can be safely invoked by the browser to display data + referenced by a link — for example, an image or an e-mail message. +
    {@code CATEGORY_GADGET} + The activity can be embedded inside of another activity that hosts gadgets. +
    {@code CATEGORY_HOME} + The activity displays the home screen, the first screen the user sees when + the device is turned on or when the Home button is pressed. +
    {@code CATEGORY_LAUNCHER} + The activity can be the initial activity of a task and is listed in + the top-level application launcher. +
    {@code CATEGORY_PREFERENCE} + The target activity is a preference panel. +
    + +

    +See the {@link android.content.Intent} class description for the full list of +categories. +

    + +

    +The {@link android.content.Intent#addCategory addCategory()} method +places a category in an Intent object, {@link android.content.Intent#removeCategory +removeCategory()} deletes a category previously added, and {@link android.content.Intent#getCategories getCategories()} gets the set of all +categories currently in the object. +

    +
    + +

    Extras
    +
    Key-value pairs for additional information that should be delivered to the +component handling the intent. Just as some actions are paired with particular +kinds of data URIs, some are paired with particular extras. For example, an +{@code ACTION_TIMEZONE_CHANGED} intent has a "{@code time-zone}" extra that +identifies the new time zone, and {@code ACTION_HEADSET_PLUG} has a +"{@code state}" extra indicating whether the headset is now plugged in or +unplugged, as well as a "{@code name}" extra for the type of headset. +If you were to invent a {@code SHOW_COLOR} action, the color value would +be set in an extra key-value pair. + +

    +The Intent object has a series of {@code put...()} methods for inserting various +types of extra data and a similar set of {@code get...()} methods for reading +the data. These methods parallel those for {@link android.os.Bundle} objects. +In fact, the extras can be installed and read as a Bundle using the {@link +android.content.Intent#putExtras putExtras()} and {@link +android.content.Intent#getExtras getExtras()} methods. +

    +
    + +

    Flags
    +
    Flags of various sorts. Many instruct the Android system how to launch an +activity (for example, which task the activity should belong to) and how to treat +it after it's launched (for example, whether it belongs in the list of recent +activities). All these flags are defined in the Intent class. +
    + +
    + +

    +The Android system and the applications that come with the platform employ +Intent objects both to send out system-originated broadcasts and to activate +system-defined components. To see how to structure an intent to activate a +system component, consult the +list of intents +in the reference. +

    + + +

    Intent Resolution

    + +

    +Intents can be divided into two groups: +

    + +
      +
    • Explicit intents designate the target component by its +name (the component name field, mentioned earlier, +has a value set). Since component names would generally not be known to +developers of other applications, explicit intents are typically used +for application-internal messages — such as an activity starting +a subordinate service or launching a sister activity.
    • + +
    • Implicit intents do not name a target (the field for +the component name is blank). Implicit intents are often used to +activate components in other applications.

    • +
    + +

    +Android delivers an explicit intent to an instance of the designated +target class. Nothing in the Intent object other than the component +name matters for determining which component should get the intent. +

    + +

    +A different strategy is needed for implicit intents. In the absence of a +designated target, the Android system must find the best component (or +components) to handle the intent — a single activity or service to +perform the requested action or the set of broadcast receivers to respond +to the broadcast announcement. It does so by comparing the contents of +the Intent object to intent filters, structures associated with +components that can potentially receive intents. Filters advertise the +capabilities of a component and delimit the intents it can handle. They +open the component to the possibility of receiving implicit intents of +the advertised type. If a component does not have any intent filters, +it can receive only explicit intents. A component with filters can +receive both explicit and implicit intents. +

    + +

    +Only three aspects of an Intent object are consulted when the object +is tested against an intent filter: +

    + +

    action +
    data (both URI and data type) +
    category

    + +

    +The extras and flags play no part in resolving which component receives +an intent. +

    + + +

    Intent filters

    + +

    +To inform the system which implicit intents they can handle, activities, +services, and broadcast receivers can have one or more intent filters. +Each filter describes a capability of the component, a set of intents that +the component is willing to receive. It, in effect, filters in +intents of a desired type, while filtering out unwanted +intents — but only unwanted implicit intents (those that don't name +a target class). An explicit intent is always delivered to its target, +no matter what it contains; the filter is not consulted. But an implicit +intent is delivered to a component only if it can pass through one of the +component's filters. +

    + +

    +A component has separate filters for each job it can do, each face it can +present to the user. For example, the NoteEditor activity of the sample +Note Pad application has two filters — one for starting up with a +specific note that the user can view or edit, and another for starting +with a new, blank note that the user can fill in and save. (All of Note +Pad's filters are described in the Note Pad Example +section, later.) +

    + + + +

    +An intent filter is an instance of the {@link android.content.IntentFilter} class. +However, since the Android system must know about the capabilities of a component +before it can launch that component, intent filters are generally not set up in +Java code, but in the application's manifest file (AndroidManifest.xml) as +<intent-filter> +elements. (The one exception would be filters for +broadcast receivers that are registered dynamically by calling {@link android.content.Context#registerReceiver(BroadcastReceiver, IntentFilter, String, +Handler) Context.registerReceiver()}; they are directly created as +IntentFilter objects.) +

    + +

    +A filter has fields that parallel the action, data, and category fields of an +Intent object. An implicit intent is tested against the filter in all three areas. +To be delivered to the component that owns the filter, it must pass all three tests. +If it fails even one of them, the Android system won't deliver it to the +component — at least not on the basis of that filter. However, since a +component can have multiple intent filters, an intent that does not pass +through one of a component's filters might make it through on another. +

    + +

    +Each of the three tests is described in detail below: +

    + +
    + +
    Action test
    +
    An +<intent-filter> +element in the manifest file lists actions as +<action> +subelements. For example: + +
    <intent-filter . . . >
    +    <action android:name="com.example.project.SHOW_CURRENT" />
    +    <action android:name="com.example.project.SHOW_RECENT" />
    +    <action android:name="com.example.project.SHOW_PENDING" />
    +    . . .
    +</intent-filter>
    + +

    +As the example shows, while an Intent object names just a single action, +a filter may list more than one. The list cannot be empty; a filter must +contain at least one {@code <action>} element, or it +will block all intents. +

    + +

    +To pass this test, the action specified in the Intent object must match +one of the actions listed in the filter. If the object or the filter +does not specify an action, the results are as follows: +

    + +
      +
    • If the filter fails to list any actions, there is nothing for an +intent to match, so all intents fail the test. No intents can get +through the filter.
    • + +
    • On the other hand, an Intent object that doesn't specify an +action automatically passes the test — as long as the filter +contains at least one action.

    • +
    + +
    Category test
    +
    An +<intent-filter> +element also lists categories as subelements. For example: + +
    <intent-filter . . . >
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <category android:name="android.intent.category.BROWSABLE" />
    +    . . .
    +</intent-filter>
    + +

    +Note that the constants described earlier for actions and categories are not +used in the manifest file. The full string values are used instead. For +instance, the "{@code android.intent.category.BROWSABLE}" string in the example +above corresponds to the {@code CATEGORY_BROWSABLE} constant mentioned earlier +in this document. Similarly, the string "{@code android.intent.action.EDIT}" +corresponds to the {@code ACTION_EDIT} constant. +

    + +

    +For an intent to pass the category test, every category in the Intent object +must match a category in the filter. The filter can list additional categories, +but it cannot omit any that are in the intent. +

    + +

    +In principle, therefore, an Intent object with no categories should always pass +this test, regardless of what's in the filter. That's mostly true. However, +with one exception, Android treats all implicit intents passed to {@link +android.content.Context#startActivity startActivity()} as if they contained +at least one category: "{@code android.intent.category.DEFAULT}" (the +{@code CATEGORY_DEFAULT} constant). +Therefore, activities that are willing to receive implicit intents must +include "{@code android.intent.category.DEFAULT}" in their intent filters. +(Filters with "{@code android.intent.action.MAIN}" and +"{@code android.intent.category.LAUNCHER}" settings are the exception. +They mark activities that begin new tasks and that are represented on the +launcher screen. They can include "{@code android.intent.category.DEFAULT}" +in the list of categories, but don't need to.) See Using +intent matching, later, for more on these filters.) +

    +
    + +
    Data test
    +
    Like the action and categories, the data specification for an intent filter +is contained in a subelement. And, as in those cases, the subelement can appear +multiple times, or not at all. For example: + +
    <intent-filter . . . >
    +    <data android:mimeType="video/mpeg" android:scheme="http" . . . /> 
    +    <data android:mimeType="audio/mpeg" android:scheme="http" . . . />
    +    . . .
    +</intent-filter>
    + +

    +Each +<data> +element can specify a URI and a data type (MIME media type). There are separate +attributes — {@code scheme}, {@code host}, {@code port}, +and {@code path} — for each part of the URI: +

    + +

    {@code scheme://host:port/path}

    + +

    +For example, in the following URI, +

    + +

    {@code content://com.example.project:200/folder/subfolder/etc}

    + +

    the scheme is "{@code content}", the host is "{@code com.example.project}", +the port is "{@code 200}", and the path is "{@code folder/subfolder/etc}". +The host and port together constitute the URI authority; if a host is +not specified, the port is ignored. +

    + +

    +Each of these attributes is optional, but they are not independent of each other: +For an authority to be meaningful, a scheme must also be specified. +For a path to be meaningful, both a scheme and an authority must be specified. +

    + +

    +When the URI in an Intent object is compared to a URI specification in a filter, +it's compared only to the parts of the URI actually mentioned in the filter. +For example, if a filter specifies only a scheme, all URIs with that scheme match +the filter. If a filter specifies a scheme and an authority but no path, all URIs +with the same scheme and authority match, regardless of their paths. If a filter +specifies a scheme, an authority, and a path, only URIs with the same scheme, +authority, and path match. However, a path specification in the filter can +contain wildcards to require only a partial match of the path. +

    + +

    +The {@code type} attribute of a {@code <data>} element specifies the MIME type +of the data. It's more common in filters than a URI. Both the Intent object and +the filter can use a "*" wildcard for the subtype field — for example, +"{@code text/*}" or "{@code audio/*}" — indicating any subtype matches. +

    + +

    +The data test compares both the URI and the data type in the Intent object to a URI +and data type specified in the filter. The rules are as follows: +

    + +
      +
    1. An Intent object that contains neither a URI nor a data type passes the +test only if the filter likewise does not specify any URIs or data types.
    2. + +
    3. An Intent object that contains a URI but no data type (and a type cannot +be inferred from the URI) passes the test only if its URI matches a URI in the +filter and the filter likewise does not specify a type. This will be the case +only for URIs like {@code mailto:} and {@code tel:} that do not refer to actual data.

    4. + +
    5. An Intent object that contains a data type but not a URI passes the test +only if the filter lists the same data type and similarly does not specify a URI.

    6. + +
    7. An Intent object that contains both a URI and a data type (or a data type +can be inferred from the URI) passes the data type part of the test only if its +type matches a type listed in the filter. It passes the URI part of the test +either if its URI matches a URI in the filter or if it has a {@code content:} +or {@code file:} URI and the filter does not specify a URI. In other words, +a component is presumed to support {@code content:} and {@code file:} data if +its filter lists only a data type.

    8. +
    +
    + +

    +If an intent can pass through the filters of more than one activity or service, +the user may be asked which component to activate. An exception is raised if +no target can be found. +

    + + +

    Common cases

    + +

    +The last rule shown above for the data test, rule (d), reflects the expectation +that components are able to get local data from a file or content provider. +Therefore, their filters can list just a data type and do not need to explicitly +name the {@code content:} and {@code file:} schemes. +This is a typical case. A {@code <data>} element like the following, +for example, tells Android that the component can get image data from a content +provider and display it: +

    + +
    <data android:mimeType="image/*" />
    + +

    +Since most available data is dispensed by content providers, filters that +specify a data type but not a URI are perhaps the most common. +

    + +

    +Another common configuration is filters with a scheme and a data type. For +example, a {@code <data>} element like the following tells Android that +the component can get video data from the network and display it: +

    + +
    <data android:scheme="http" android:type="video/*" />
    + +

    +Consider, for example, what the browser application does when +the user follows a link on a web page. It first tries to display the data +(as it could if the link was to an HTML page). If it can't display the data, +it puts together an implicit intent with the scheme and data type and tries +to start an activity that can do the job. If there are no takers, it asks the +download manager to download the data. That puts it under the control +of a content provider, so a potentially larger pool of activities +(those with filters that just name a data type) can respond. +

    + +

    +Most applications also have a way to start fresh, without a reference +to any particular data. Activities that can initiate applications +have filters with "{@code android.intent.action.MAIN}" specified as +the action. If they are to be represented in the application launcher, +they also specify the "{@code android.intent.category.LAUNCHER}" +category: +

    + +
    <intent-filter . . . >
    +    <action android:name="code android.intent.action.MAIN" />
    +    <category android:name="code android.intent.category.LAUNCHER" />
    +</intent-filter>
    + + +

    Using intent matching

    + +

    +Intents are matched against intent filters not only to discover a target +component to activate, but also to discover something about the set of +components on the device. For example, the Android system populates the +application launcher, the top-level screen that shows the applications +that are available for the user to launch, by finding all the activities + with intent filters that specify the "{@code android.intent.action.MAIN}" +action and "{@code android.intent.category.LAUNCHER}" category +(as illustrated in the previous section). It then displays the icons and +labels of those activities in the launcher. Similarly, it discovers the +home screen by looking for the activity with +"{@code android.intent.category.HOME}" in its filter. +

    + +

    +Your application can use intent matching is a similar way. +The {@link android.content.pm.PackageManager} has a set of {@code query...()} +methods that return all components that can accept a particular intent, and +a similar series of {@code resolve...()} methods that determine the best +component to respond to an intent. For example, +{@link android.content.pm.PackageManager#queryIntentActivities +queryIntentActivities()} returns a list of all activities that can perform +the intent passed as an argument, and {@link +android.content.pm.PackageManager#queryIntentServices +queryIntentServices()} returns a similar list of services. +Neither method activates the components; they just list the ones that +can respond. There's a similar method, +{@link android.content.pm.PackageManager#queryBroadcastReceivers +queryBroadcastReceivers()}, for broadcast receivers. +

    + +

    Note Pad Example

    + +

    +The Note Pad sample application enables users to browse through a list +of notes, view details about individual items in the list, edit the items, +and add a new item to the list. This section looks at the intent filters +declared in its manifest file. (If you're working offline in the SDK, you +can find all the source files for this sample application, including its +manifest file, at {@code <sdk>/samples/NotePad/index.html}. +If you're viewing the documentation online, the source files are in the +Tutorials and Sample Code +section here.) +

    + +

    +In its manifest file, the Note Pad application declares three activities, +each with at least one intent filter. It also declares a content provider +that manages the note data. Here is the manifest file in its entirety: +

    + +
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +          package="com.example.android.notepad">
    +    <application android:icon="@drawable/app_notes"
    +                 android:label="@string/app_name" >
    +
    +        <provider android:name="NotePadProvider"
    +                  android:authorities="com.google.provider.NotePad" />
    +
    +        <activity android:name="NotesList" android:label="@string/title_notes_list">
    +            <intent-filter>
    +                <action android:name="android.intent.action.MAIN" />
    +                <category android:name="android.intent.category.LAUNCHER" />
    +            </intent-filter>
    +            <intent-filter>
    +                <action android:name="android.intent.action.VIEW" />
    +                <action android:name="android.intent.action.EDIT" />
    +                <action android:name="android.intent.action.PICK" />
    +                <category android:name="android.intent.category.DEFAULT" />
    +                <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
    +            </intent-filter>
    +            <intent-filter>
    +                <action android:name="android.intent.action.GET_CONTENT" />
    +                <category android:name="android.intent.category.DEFAULT" />
    +                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
    +            </intent-filter>
    +        </activity>
    +        
    +        <activity android:name="NoteEditor"
    +                  android:theme="@android:style/Theme.Light"
    +                  android:label="@string/title_note" >
    +            <intent-filter android:label="@string/resolve_edit">
    +                <action android:name="android.intent.action.VIEW" />
    +                <action android:name="android.intent.action.EDIT" />
    +                <action android:name="com.android.notepad.action.EDIT_NOTE" />
    +                <category android:name="android.intent.category.DEFAULT" />
    +                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
    +            </intent-filter>
    +            <intent-filter>
    +                <action android:name="android.intent.action.INSERT" />
    +                <category android:name="android.intent.category.DEFAULT" />
    +                <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
    +            </intent-filter>
    +        </activity>
    +        
    +        <activity android:name="TitleEditor" 
    +                  android:label="@string/title_edit_title"
    +                  android:theme="@android:style/Theme.Dialog">
    +            <intent-filter android:label="@string/resolve_title">
    +                <action android:name="com.android.notepad.action.EDIT_TITLE" />
    +                <category android:name="android.intent.category.DEFAULT" />
    +                <category android:name="android.intent.category.ALTERNATIVE" />
    +                <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
    +                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
    +            </intent-filter>
    +        </activity>
    +        
    +    </application>
    +</manifest>
    + +

    +The first activity, NotesList, is +distinguished from the other activities by the fact that it operates +on a directory of notes (the note list) rather than on a single note. +It would generally serve as the initial user interface into the +application. It can do three things as described by its three intent +filters: +

    + +
      +
    1. <intent-filter>
      +    <action android:name="android.intent.action.MAIN" />
      +    <category android:name="android.intent.category.LAUNCHER" />
      +</intent-filter>
      + +

      +This filter declares the main entry point into the Note Pad application. +The standard {@code MAIN} action is an entry point that does not require +any other information in the Intent (no data specification, for example), +and the {@code LAUNCHER} category says that this entry point should be +listed in the application launcher. +

    2. + +
    3. <intent-filter>
      +    <action android:name="android.intent.action.VIEW" />
      +    <action android:name="android.intent.action.EDIT" />
      +    <action android:name="android.intent.action.PICK" />
      +    <category android:name="android.intent.category.DEFAULT" />
      +    <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
      +</intent-filter>
      + +

      +This filter declares the things that the activity can do on a directory +of notes. It can allow the user to view or edit the directory (via +the {@code VIEW} and {@code EDIT} actions), or to pick a particular note +from the directory (via the {@code PICK} action). +

      + +

      +The {@code mimeType} attribute of the +<data> +element specifies the kind of data that these actions operate on. It +indicates that the activity can get a Cursor over zero or more items +({@code vnd.android.cursor.dir}) from a content provider that holds +Note Pad data ({@code vnd.google.note}). The Intent object that launches +the activity would include a {@code content:} URI specifying the exact +data of this type that the activity should open. +

      + +

      +Note also the {@code DEFAULT} category supplied in this filter. It's +there because the {@link android.content.Context#startActivity +Context.startActivity()} and +{@link android.app.Activity#startActivityForResult +Activity.startActivityForResult()} methods treat all intents +as if they contained the {@code DEFAULT} category — with just +two exceptions: +

      + +
        +
      • Intents that explicitly name the target activity
      • +
      • Intents consisting of the {@code MAIN} action and {@code LAUNCHER} +category
      • +
      + +

      +Therefore, the {@code DEFAULT} category is required for all +filters — except for those with the {@code MAIN} action and +{@code LAUNCHER} category. (Intent filters are not consulted for +explicit intents.) +

    4. + +
    5. <intent-filter>
      +    <action android:name="android.intent.action.GET_CONTENT" />
      +    <category android:name="android.intent.category.DEFAULT" />
      +    <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
      +</intent-filter>
      + +

      +This filter describes the activity's ability to return a note selected by +the user without requiring any specification of the directory the user should +choose from. The {@code GET_CONTENT} action is similar to the {@code PICK} +action. In both cases, the activity returns the URI for a note selected by +the user. (In each case, it's returned to the activity that called +{@link android.app.Activity#startActivityForResult +startActivityForResult()} to start the NoteList activity.) Here, +however, the caller specifies the type of data desired instead of the +directory of data the user will be picking from. +

      + +

      +The data type, vnd.android.cursor.item/vnd.google.note, +indicates the type of data the activity can return — a URI for +a single note. From the returned URI, the caller can get a Cursor for +exactly one item ({@code vnd.android.cursor.item}) from the content +provider that holds Note Pad data ({@code vnd.google.note}). +

      + +

      +In other words, for the {@code PICK} action in the previous filter, +the data type indicates the type of data the activity could display to the +user. For the {@code GET_CONTENT} filter, it indicates the type of data +the activity can return to the caller. +

    6. +
    + +

    +Given these capabilities, the following intents will resolve to the +NotesList activity: +

    + +
    +
    action: android.intent.action.MAIN
    +
    Launches the activity with no data specified.
    + +
    action: android.intent.action.MAIN +
    category: android.intent.category.LAUNCHER
    +
    Launches the activity with no data selected specified. +This is the actual intent used by the Launcher to populate its top-level +list. All activities with filters that match this action and category +are added to the list.
    + +
    action: android.intent.action.VIEW +
    data: content://com.google.provider.NotePad/notes
    +
    Asks the activity to display a list of all the notes under +content://com.google.provider.NotePad/notes. The user can then +browse through the list and get information about the items in it.
    + +
    action: android.intent.action.PICK +
    data: content://com.google.provider.NotePad/notes
    +
    Asks the activity to display a list of the notes under +content://com.google.provider.NotePad/notes. +The user can then pick a note from the list, and the activity will return +the URI for that item back to the activity that started the NoteList activity.
    + +
    action: android.intent.action.GET_CONTENT +
    data type: vnd.android.cursor.item/vnd.google.note
    +
    Asks the activity to supply a single item of Note Pad data.
    +
    + +

    +The second activity, NoteEditor, shows +users a single note entry and allows them to edit it. It can do two things +as described by its two intent filters: + +

      +
    1. <intent-filter android:label="@string/resolve_edit">
      +    <action android:name="android.intent.action.VIEW" />
      +    <action android:name="android.intent.action.EDIT" />
      +    <action android:name="com.android.notepad.action.EDIT_NOTE" />
      +    <category android:name="android.intent.category.DEFAULT" />
      +    <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
      +</intent-filter>
      + +

      +The first, primary, purpose of this activity is to enable the user to +interact with a single note — to either {@code VIEW} the note or +{@code EDIT} it. (The {@code EDIT_NOTE} category is a synonym for +{@code EDIT}.) The intent would contain the URI for data matching the +MIME type vnd.android.cursor.item/vnd.google.note — +that is, the URI for a single, specific note. It would typically be a +URI that was returned by the {@code PICK} or {@code GET_CONTENT} +actions of the NoteList activity. +

      + +

      +As before, this filter lists the {@code DEFAULT} category so that the +activity can be launched by intents that don't explicitly specify the +NoteEditor class. +

    2. + +
    3. <intent-filter>
      +    <action android:name="android.intent.action.INSERT" />
      +    <category android:name="android.intent.category.DEFAULT" />
      +    <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
      +</intent-filter>
      + +

      +The secondary purpose of this activity is to enable the user to create a new +note, which it will {@code INSERT} into an existing directory of notes. The +intent would contain the URI for data matching the MIME type +vnd.android.cursor.dir/vnd.google.note — that +is, the URI for the directory where the note should be placed. +

    4. +
    + +

    +Given these capabilities, the following intents will resolve to the +NoteEditor activity: +

    + +
    +
    action: android.intent.action.VIEW +
    data: content://com.google.provider.NotePad/notes/ID
    +
    Asks the activity to display the content of the note identified +by {@code ID}. (For details on how {@code content:} URIs +specify individual members of a group, see +Content Providers.) + +
    action: android.intent.action.EDIT +
    data: content://com.google.provider.NotePad/notes/ID
    +
    Asks the activity to display the content of the note identified +by {@code ID}, and to let the user edit it. If the user +saves the changes, the activity updates the data for the note in the +content provider.
    + +
    action: android.intent.action.INSERT +
    data: content://com.google.provider.NotePad/notes
    +
    Asks the activity to create a new, empty note in the notes list at +content://com.google.provider.NotePad/notes +and allow the user to edit it. If the user saves the note, its URI +is returned to the caller. +
    +
    + +

    The last activity, TitleEditor, +enables the user to edit the title of a note. This could be implemented +by directly invoking the activity (by explicitly setting its component +name in the Intent), without using an intent filter. But here we take +the opportunity to show how to publish alternative operations on existing +data: +

    + +
    <intent-filter android:label="@string/resolve_title">
    +    <action android:name="com.android.notepad.action.EDIT_TITLE" />
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <category android:name="android.intent.category.ALTERNATIVE" />
    +    <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
    +    <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
    +</intent-filter>
    + +

    +The single intent filter for this activity uses a custom action called +"com.android.notepad.action.EDIT_TITLE". It must be invoked on +a specific note (data type vnd.android.cursor.item/vnd.google.note), +like the previous {@code VIEW} and {@code EDIT} actions. However, here the +activity displays the title contained in the note data, not the content of +the note itself. +

    + +

    +In addition to supporting the usual {@code DEFAULT} category, the title +editor also supports two other standard categories: +{@link android.content.Intent#CATEGORY_ALTERNATIVE ALTERNATIVE} +and {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE +SELECTED_ALTERNATIVE}. +These categories identify activities that can be presented to users in +a menu of options (much as the {@code LAUNCHER} category identifies +activities that should be presented to user in the application launcher). +Note that the filter also supplies an explicit label (via +android:label="@string/resolve_title") to better control +what users see when presented with this activity as an alternative +action to the data they are currently viewing. (For more information +on these categories and building options menus, see the +{@link android.content.pm.PackageManager#queryIntentActivityOptions +PackageManager.queryIntentActivityOptions()} and +{@link android.view.Menu#addIntentOptions Menu.addIntentOptions()} +methods.) +

    + +

    +Given these capabilities, the following intent will resolve to the +TitleEditor activity: +

    + +
    +
    action: com.android.notepad.action.EDIT_TITLE +
    data: content://com.google.provider.NotePad/notes/ID
    +
    Asks the activity to display the title associated with note ID, and +allow the user to edit the title.
    +
    + + + + + + + + + + + diff --git a/docs/html/guide/components/loaders.jd b/docs/html/guide/components/loaders.jd new file mode 100644 index 000000000000..ddd513b2a2c5 --- /dev/null +++ b/docs/html/guide/components/loaders.jd @@ -0,0 +1,500 @@ +page.title=Loaders +parent.title=Activities +parent.link=activities.html +@jd:body +
    +
    +

    In this document

    +
      +
    1. Loader API Summary
    2. +
    3. Using Loaders in an Application +
        +
      1. +
      2. Starting a Loader
      3. +
      4. Restarting a Loader
      5. +
      6. Using the LoaderManager Callbacks
      7. +
      +
    4. +
    5. Example +
        +
      1. More Examples
      2. +
      +
    6. +
    + +

    Key classes

    +
      +
    1. {@link android.app.LoaderManager}
    2. +
    3. {@link android.content.Loader}
    4. + +
    + +

    Related samples

    +
      +
    1. +LoaderCursor
    2. +
    3. +LoaderThrottle
    4. +
    +
    +
    + +

    Introduced in Android 3.0, loaders make it easy to asynchronously load data +in an activity or fragment. Loaders have these characteristics:

    +
      +
    • They are available to every {@link android.app.Activity} and {@link +android.app.Fragment}.
    • +
    • They provide asynchronous loading of data.
    • +
    • They monitor the source of their data and deliver new results when the +content changes.
    • +
    • They automatically reconnect to the last loader's cursor when being +recreated after a configuration change. Thus, they don't need to re-query their +data.
    • +
    + +

    Loader API Summary

    + +

    There are multiple classes and interfaces that may be involved in using +loaders in an application. They are summarized in this table:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Class/InterfaceDescription
    {@link android.app.LoaderManager}An abstract class associated with an {@link android.app.Activity} or +{@link android.app.Fragment} for managing one or more {@link +android.content.Loader} instances. This helps an application manage +longer-running operations in conjunction with the {@link android.app.Activity} +or {@link android.app.Fragment} lifecycle; the most common use of this is with a +{@link android.content.CursorLoader}, however applications are free to write +their own loaders for loading other types of data. +
    +
    + There is only one {@link android.app.LoaderManager} per activity or fragment. But a {@link android.app.LoaderManager} can have +multiple loaders.
    {@link android.app.LoaderManager.LoaderCallbacks}A callback interface for a client to interact with the {@link +android.app.LoaderManager}. For example, you use the {@link +android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} +callback method to create a new loader.
    {@link android.content.Loader}An abstract class that performs asynchronous loading of data. This is +the base class for a loader. You would typically use {@link +android.content.CursorLoader}, but you can implement your own subclass. While +loaders are active they should monitor the source of their data and deliver new +results when the contents change.
    {@link android.content.AsyncTaskLoader}Abstract loader that provides an {@link android.os.AsyncTask} to do the work.
    {@link android.content.CursorLoader}A subclass of {@link android.content.AsyncTaskLoader} that queries the +{@link android.content.ContentResolver} and returns a {@link +android.database.Cursor}. This class implements the {@link +android.content.Loader} protocol in a standard way for querying cursors, +building on {@link android.content.AsyncTaskLoader} to perform the cursor query +on a background thread so that it does not block the application's UI. Using +this loader is the best way to asynchronously load data from a {@link +android.content.ContentProvider}, instead of performing a managed query through +the fragment or activity's APIs.
    + +

    The classes and interfaces in the above table are the essential components +you'll use to implement a loader in your application. You won't need all of them +for each loader you create, but you'll always need a reference to the {@link +android.app.LoaderManager} in order to initialize a loader and an implementation +of a {@link android.content.Loader} class such as {@link +android.content.CursorLoader}. The following sections show you how to use these +classes and interfaces in an application.

    + +

    Using Loaders in an Application

    +

    This section describes how to use loaders in an Android application. An +application that uses loaders typically includes the following:

    +
      +
    • An {@link android.app.Activity} or {@link android.app.Fragment}.
    • +
    • An instance of the {@link android.app.LoaderManager}.
    • +
    • A {@link android.content.CursorLoader} to load data backed by a {@link +android.content.ContentProvider}. Alternatively, you can implement your own subclass +of {@link android.content.Loader} or {@link android.content.AsyncTaskLoader} to +load data from some other source.
    • +
    • An implementation for {@link android.app.LoaderManager.LoaderCallbacks}. +This is where you create new loaders and manage your references to existing +loaders.
    • +
    • A way of displaying the loader's data, such as a {@link +android.widget.SimpleCursorAdapter}.
    • +
    • A data source, such as a {@link android.content.ContentProvider}, when using a +{@link android.content.CursorLoader}.
    • +
    +

    Starting a Loader

    + +

    The {@link android.app.LoaderManager} manages one or more {@link +android.content.Loader} instances within an {@link android.app.Activity} or +{@link android.app.Fragment}. There is only one {@link +android.app.LoaderManager} per activity or fragment.

    + +

    You typically +initialize a {@link android.content.Loader} within the activity's {@link +android.app.Activity#onCreate onCreate()} method, or within the fragment's +{@link android.app.Fragment#onActivityCreated onActivityCreated()} method. You +do this as follows:

    + +
    // Prepare the loader.  Either re-connect with an existing one,
    +// or start a new one.
    +getLoaderManager().initLoader(0, null, this);
    + +

    The {@link android.app.LoaderManager#initLoader initLoader()} method takes +the following parameters:

    +
      +
    • A unique ID that identifies the loader. In this example, the ID is 0.
    • +
    • Optional arguments to supply to the loader at +construction (null in this example).
    • + +
    • A {@link android.app.LoaderManager.LoaderCallbacks} implementation, which +the {@link android.app.LoaderManager} calls to report loader events. In this +example, the local class implements the {@link +android.app.LoaderManager.LoaderCallbacks} interface, so it passes a reference +to itself, {@code this}.
    • +
    +

    The {@link android.app.LoaderManager#initLoader initLoader()} call ensures that a loader +is initialized and active. It has two possible outcomes:

    +
      +
    • If the loader specified by the ID already exists, the last created loader +is reused.
    • +
    • If the loader specified by the ID does not exist, +{@link android.app.LoaderManager#initLoader initLoader()} triggers the +{@link android.app.LoaderManager.LoaderCallbacks} method {@link android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}. +This is where you implement the code to instantiate and return a new loader. +For more discussion, see the section onCreateLoader.
    • +
    +

    In either case, the given {@link android.app.LoaderManager.LoaderCallbacks} +implementation is associated with the loader, and will be called when the +loader state changes. If at the point of this call the caller is in its +started state, and the requested loader already exists and has generated its +data, then the system calls {@link +android.app.LoaderManager.LoaderCallbacks#onLoadFinished onLoadFinished()} +immediately (during {@link android.app.LoaderManager#initLoader initLoader()}), +so you must be prepared for this to happen. See +onLoadFinished for more discussion of this callback

    + +

    Note that the {@link android.app.LoaderManager#initLoader initLoader()} +method returns the {@link android.content.Loader} that is created, but you don't +need to capture a reference to it. The {@link android.app.LoaderManager} manages +the life of the loader automatically. The {@link android.app.LoaderManager} +starts and stops loading when necessary, and maintains the state of the loader +and its associated content. As this implies, you rarely interact with loaders +directly (though for an example of using loader methods to fine-tune a loader's +behavior, see the LoaderThrottle sample). +You most commonly use the {@link +android.app.LoaderManager.LoaderCallbacks} methods to intervene in the loading +process when particular events occur. For more discussion of this topic, see Using the LoaderManager Callbacks.

    + +

    Restarting a Loader

    + +

    When you use {@link android.app.LoaderManager#initLoader initLoader()}, as +shown above, it uses an existing loader with the specified ID if there is one. +If there isn't, it creates one. But sometimes you want to discard your old data +and start over.

    + +

    To discard your old data, you use {@link +android.app.LoaderManager#restartLoader restartLoader()}. For example, this +implementation of {@link android.widget.SearchView.OnQueryTextListener} restarts +the loader when the user's query changes. The loader needs to be restarted so +that it can use the revised search filter to do a new query:

    + +
    +public boolean onQueryTextChanged(String newText) {
    +    // Called when the action bar search text has changed.  Update
    +    // the search filter, and restart the loader to do a new query
    +    // with this filter.
    +    mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
    +    getLoaderManager().restartLoader(0, null, this);
    +    return true;
    +}
    + +

    Using the LoaderManager Callbacks

    + +

    {@link android.app.LoaderManager.LoaderCallbacks} is a callback interface +that lets a client interact with the {@link android.app.LoaderManager}.

    +

    Loaders, in particular {@link android.content.CursorLoader}, are expected to +retain their data after being stopped. This allows applications to keep their +data across the activity or fragment's {@link android.app.Activity#onStop +onStop()} and {@link android.app.Activity#onStart onStart()} methods, so that +when users return to an application, they don't have to wait for the data to +reload. You use the {@link android.app.LoaderManager.LoaderCallbacks} methods +when to know when to create a new loader, and to tell the application when it is + time to stop using a loader's data.

    + +

    {@link android.app.LoaderManager.LoaderCallbacks} includes these +methods:

    +
      +
    • {@link android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} — +Instantiate and return a new {@link android.content.Loader} for the given ID. +
    +
      +
    • {@link android.app.LoaderManager.LoaderCallbacks#onLoadFinished onLoadFinished()} +— Called when a previously created loader has finished its load. +
    +
      +
    • {@link android.app.LoaderManager.LoaderCallbacks#onLoaderReset onLoaderReset()} + — Called when a previously created loader is being reset, thus making its +data unavailable. +
    • +
    +

    These methods are described in more detail in the following sections.

    + +

    onCreateLoader

    + +

    When you attempt to access a loader (for example, through {@link +android.app.LoaderManager#initLoader initLoader()}), it checks to see whether +the loader specified by the ID exists. If it doesn't, it triggers the {@link +android.app.LoaderManager.LoaderCallbacks} method {@link +android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}. This +is where you create a new loader. Typically this will be a {@link +android.content.CursorLoader}, but you can implement your own {@link +android.content.Loader} subclass.

    + +

    In this example, the {@link +android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} +callback method creates a {@link android.content.CursorLoader}. You must build +the {@link android.content.CursorLoader} using its constructor method, which +requires the complete set of information needed to perform a query to the {@link +android.content.ContentProvider}. Specifically, it needs:

    +
      +
    • uri — The URI for the content to retrieve.
    • +
    • projection — A list of which columns to return. Passing +null will return all columns, which is inefficient.
    • +
    • selection — A filter declaring which rows to return, +formatted as an SQL WHERE clause (excluding the WHERE itself). Passing +null will return all rows for the given URI.
    • +
    • selectionArgs — You may include ?s in the selection, which will +be replaced by the values from selectionArgs, in the order that they appear in +the selection. The values will be bound as Strings.
    • +
    • sortOrder — How to order the rows, formatted as an SQL +ORDER BY clause (excluding the ORDER BY itself). Passing null will +use the default sort order, which may be unordered.
    • +
    +

    For example:

    +
    + // If non-null, this is the current filter the user has provided.
    +String mCurFilter;
    +...
    +public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    +    // This is called when a new Loader needs to be created.  This
    +    // sample only has one Loader, so we don't care about the ID.
    +    // First, pick the base URI to use depending on whether we are
    +    // currently filtering.
    +    Uri baseUri;
    +    if (mCurFilter != null) {
    +        baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
    +                  Uri.encode(mCurFilter));
    +    } else {
    +        baseUri = Contacts.CONTENT_URI;
    +    }
    +
    +    // Now create and return a CursorLoader that will take care of
    +    // creating a Cursor for the data being displayed.
    +    String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
    +            + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
    +            + Contacts.DISPLAY_NAME + " != '' ))";
    +    return new CursorLoader(getActivity(), baseUri,
    +            CONTACTS_SUMMARY_PROJECTION, select, null,
    +            Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    +}
    +

    onLoadFinished

    + +

    This method is called when a previously created loader has finished its load. +This method is guaranteed to be called prior to the release of the last data +that was supplied for this loader. At this point you should remove all use of +the old data (since it will be released soon), but should not do your own +release of the data since its loader owns it and will take care of that.

    + + +

    The loader will release the data once it knows the application is no longer +using it. For example, if the data is a cursor from a {@link +android.content.CursorLoader}, you should not call {@link +android.database.Cursor#close close()} on it yourself. If the cursor is being +placed in a {@link android.widget.CursorAdapter}, you should use the {@link +android.widget.SimpleCursorAdapter#swapCursor swapCursor()} method so that the +old {@link android.database.Cursor} is not closed. For example:

    + +
    +// This is the Adapter being used to display the list's data.
    SimpleCursorAdapter mAdapter; +... + +public void onLoadFinished(Loader<Cursor> loader, Cursor data) { + // Swap the new cursor in.  (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); +}
    + +

    onLoaderReset

    + +

    This method is called when a previously created loader is being reset, thus +making its data unavailable. This callback lets you find out when the data is +about to be released so you can remove your reference to it.  

    +

    This implementation calls +{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} +with a value of null:

    + +
    +// This is the Adapter being used to display the list's data.
    +SimpleCursorAdapter mAdapter;
    +...
    +
    +public void onLoaderReset(Loader<Cursor> loader) {
    +    // This is called when the last Cursor provided to onLoadFinished()
    +    // above is about to be closed.  We need to make sure we are no
    +    // longer using it.
    +    mAdapter.swapCursor(null);
    +}
    + + +

    Example

    + +

    As an example, here is the full implementation of a {@link +android.app.Fragment} that displays a {@link android.widget.ListView} containing +the results of a query against the contacts content provider. It uses a {@link +android.content.CursorLoader} to manage the query on the provider.

    + +

    For an application to access a user's contacts, as shown in this example, its +manifest must include the permission +{@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}.

    + +
    +public static class CursorLoaderListFragment extends ListFragment
    +        implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
    +
    +    // This is the Adapter being used to display the list's data.
    +    SimpleCursorAdapter mAdapter;
    +
    +    // If non-null, this is the current filter the user has provided.
    +    String mCurFilter;
    +
    +    @Override public void onActivityCreated(Bundle savedInstanceState) {
    +        super.onActivityCreated(savedInstanceState);
    +
    +        // Give some text to display if there is no data.  In a real
    +        // application this would come from a resource.
    +        setEmptyText("No phone numbers");
    +
    +        // We have a menu item to show in action bar.
    +        setHasOptionsMenu(true);
    +
    +        // Create an empty adapter we will use to display the loaded data.
    +        mAdapter = new SimpleCursorAdapter(getActivity(),
    +                android.R.layout.simple_list_item_2, null,
    +                new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
    +                new int[] { android.R.id.text1, android.R.id.text2 }, 0);
    +        setListAdapter(mAdapter);
    +
    +        // Prepare the loader.  Either re-connect with an existing one,
    +        // or start a new one.
    +        getLoaderManager().initLoader(0, null, this);
    +    }
    +
    +    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    +        // Place an action bar item for searching.
    +        MenuItem item = menu.add("Search");
    +        item.setIcon(android.R.drawable.ic_menu_search);
    +        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    +        SearchView sv = new SearchView(getActivity());
    +        sv.setOnQueryTextListener(this);
    +        item.setActionView(sv);
    +    }
    +
    +    public boolean onQueryTextChange(String newText) {
    +        // Called when the action bar search text has changed.  Update
    +        // the search filter, and restart the loader to do a new query
    +        // with this filter.
    +        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
    +        getLoaderManager().restartLoader(0, null, this);
    +        return true;
    +    }
    +
    +    @Override public boolean onQueryTextSubmit(String query) {
    +        // Don't care about this.
    +        return true;
    +    }
    +
    +    @Override public void onListItemClick(ListView l, View v, int position, long id) {
    +        // Insert desired behavior here.
    +        Log.i("FragmentComplexList", "Item clicked: " + id);
    +    }
    +
    +    // These are the Contacts rows that we will retrieve.
    +    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
    +        Contacts._ID,
    +        Contacts.DISPLAY_NAME,
    +        Contacts.CONTACT_STATUS,
    +        Contacts.CONTACT_PRESENCE,
    +        Contacts.PHOTO_ID,
    +        Contacts.LOOKUP_KEY,
    +    };
    +    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    +        // This is called when a new Loader needs to be created.  This
    +        // sample only has one Loader, so we don't care about the ID.
    +        // First, pick the base URI to use depending on whether we are
    +        // currently filtering.
    +        Uri baseUri;
    +        if (mCurFilter != null) {
    +            baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
    +                    Uri.encode(mCurFilter));
    +        } else {
    +            baseUri = Contacts.CONTENT_URI;
    +        }
    +
    +        // Now create and return a CursorLoader that will take care of
    +        // creating a Cursor for the data being displayed.
    +        String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
    +                + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
    +                + Contacts.DISPLAY_NAME + " != '' ))";
    +        return new CursorLoader(getActivity(), baseUri,
    +                CONTACTS_SUMMARY_PROJECTION, select, null,
    +                Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    +    }
    +
    +    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    +        // Swap the new cursor in.  (The framework will take care of closing the
    +        // old cursor once we return.)
    +        mAdapter.swapCursor(data);
    +    }
    +
    +    public void onLoaderReset(Loader<Cursor> loader) {
    +        // This is called when the last Cursor provided to onLoadFinished()
    +        // above is about to be closed.  We need to make sure we are no
    +        // longer using it.
    +        mAdapter.swapCursor(null);
    +    }
    +}
    +

    More Examples

    + +

    There are a few different samples in ApiDemos that +illustrate how to use loaders:

    +
      +
    • +LoaderCursor — A complete version of the +snippet shown above.
    • +
    • LoaderThrottle — An example of how to use throttling to +reduce the number of queries a content provider does when its data changes.
    • +
    + +

    For information on downloading and installing the SDK samples, see Getting the +Samples.

    + diff --git a/docs/html/guide/components/processes-and-threads.jd b/docs/html/guide/components/processes-and-threads.jd new file mode 100644 index 000000000000..07a2667dc73f --- /dev/null +++ b/docs/html/guide/components/processes-and-threads.jd @@ -0,0 +1,424 @@ +page.title=Processes and Threads +@jd:body + +
    +
    +

    Quickview

    +
      +
    • Every application runs in its own process and all components of the application run in that +process, by default
    • +
    • Any slow, blocking operations in an activity should be done in a new thread, to avoid slowing +down the user interface
    • +
    + +

    In this document

    +
      +
    1. Processes +
        +
      1. Process lifecycle
      2. +
      +
    2. +
    3. Threads +
        +
      1. Worker threads
      2. +
      3. Thread-safe methods
      4. +
      +
    4. +
    5. Interprocess Communication
    6. +
    + +
    +
    + +

    When an application component starts and the application does not have any other components +running, the Android system starts a new Linux process for the application with a single thread of +execution. By default, all components of the same application run in the same process and thread +(called the "main" thread). If an application component starts and there already exists a process +for that application (because another component from the application exists), then the component is +started within that process and uses the same thread of execution. However, you can arrange for +different components in your application to run in separate processes, and you can create additional +threads for any process.

    + +

    This document discusses how processes and threads work in an Android application.

    + + +

    Processes

    + +

    By default, all components of the same application run in the same process and most applications +should not change this. However, if you find that you need to control which process a certain +component belongs to, you can do so in the manifest file.

    + +

    The manifest entry for each type of component element—{@code +<activity>}, {@code +<service>}, {@code +<receiver>}, and {@code +<provider>}—supports an {@code android:process} attribute that can specify a +process in which that component should run. You can set this attribute so that each component runs +in its own process or so that some components share a process while others do not. You can also set +{@code android:process} so that components of different applications run in the same +process—provided that the applications share the same Linux user ID and are signed with the +same certificates.

    + +

    The {@code +<application>} element also supports an {@code android:process} attribute, to set a +default value that applies to all components.

    + +

    Android might decide to shut down a process at some point, when memory is low and required by +other processes that are more immediately serving the user. Application +components running in the process that's killed are consequently destroyed. A process is started +again for those components when there's again work for them to do.

    + +

    When deciding which processes to kill, the Android system weighs their relative importance to +the user. For example, it more readily shuts down a process hosting activities that are no longer +visible on screen, compared to a process hosting visible activities. The decision whether to +terminate a process, therefore, depends on the state of the components running in that process. The +rules used to decide which processes to terminate is discussed below.

    + + +

    Process lifecycle

    + +

    The Android system tries to maintain an application process for as long as possible, but +eventually needs to remove old processes to reclaim memory for new or more important processes. To +determine which processes to keep +and which to kill, the system places each process into an "importance hierarchy" based on the +components running in the process and the state of those components. Processes with the lowest +importance are eliminated first, then those with the next lowest importance, and so on, as necessary +to recover system resources.

    + +

    There are five levels in the importance hierarchy. The following list presents the different +types of processes in order of importance (the first process is most important and is +killed last):

    + +
      +
    1. Foreground process +

      A process that is required for what the user is currently doing. A + process is considered to be in the foreground if any of the following conditions are true:

      + +
        +
      • It hosts an {@link android.app.Activity} that the user is interacting with (the {@link +android.app.Activity}'s {@link android.app.Activity#onResume onResume()} method has been +called).
      • + +
      • It hosts a {@link android.app.Service} that's bound to the activity that the user is +interacting with.
      • + +
      • It hosts a {@link android.app.Service} that's running "in the foreground"—the +service has called {@link android.app.Service#startForeground startForeground()}. + +
      • It hosts a {@link android.app.Service} that's executing one of its lifecycle +callbacks ({@link android.app.Service#onCreate onCreate()}, {@link android.app.Service#onStart +onStart()}, or {@link android.app.Service#onDestroy onDestroy()}).
      • + +
      • It hosts a {@link android.content.BroadcastReceiver} that's executing its {@link + android.content.BroadcastReceiver#onReceive onReceive()} method.
      • +
      + +

      Generally, only a few foreground processes exist at any given time. They are killed only as +a last resort—if memory is so low that they cannot all continue to run. Generally, at that +point, the device has reached a memory paging state, so killing some foreground processes is +required to keep the user interface responsive.

    2. + +
    3. Visible process +

      A process that doesn't have any foreground components, but still can + affect what the user sees on screen. A process is considered to be visible if either of the + following conditions are true:

      + +
        +
      • It hosts an {@link android.app.Activity} that is not in the foreground, but is still +visible to the user (its {@link android.app.Activity#onPause onPause()} method has been called). +This might occur, for example, if the foreground activity started a dialog, which allows the +previous activity to be seen behind it.
      • + +
      • It hosts a {@link android.app.Service} that's bound to a visible (or foreground) +activity.
      • +
      + +

      A visible process is considered extremely important and will not be killed unless doing so +is required to keep all foreground processes running.

      +
    4. + +
    5. Service process +

      A process that is running a service that has been started with the {@link +android.content.Context#startService startService()} method and does not fall into either of the two +higher categories. Although service processes are not directly tied to anything the user sees, they +are generally doing things that the user cares about (such as playing music in the background or +downloading data on the network), so the system keeps them running unless there's not enough memory +to retain them along with all foreground and visible processes.

      +
    6. + +
    7. Background process +

      A process holding an activity that's not currently visible to the user (the activity's +{@link android.app.Activity#onStop onStop()} method has been called). These processes have no direct +impact on the user experience, and the system can kill them at any time to reclaim memory for a +foreground, +visible, or service process. Usually there are many background processes running, so they are kept +in an LRU (least recently used) list to ensure that the process with the activity that was most +recently seen by the user is the last to be killed. If an activity implements its lifecycle methods +correctly, and saves its current state, killing its process will not have a visible effect on +the user experience, because when the user navigates back to the activity, the activity restores +all of its visible state. See the Activities +document for information about saving and restoring state.

      +
    8. + +
    9. Empty process +

      A process that doesn't hold any active application components. The only reason to keep this +kind of process alive is for caching purposes, to improve startup time the next time a component +needs to run in it. The system often kills these processes in order to balance overall system +resources between process caches and the underlying kernel caches.

      +
    10. +
    + + +

    Android ranks a process at the highest level it can, based upon the importance of the +components currently active in the process. For example, if a process hosts a service and a visible +activity, the process is ranked as a visible process, not a service process.

    + +

    In addition, a process's ranking might be increased because other processes are dependent on +it—a process that is serving another process can never be ranked lower than the process it is +serving. For example, if a content provider in process A is serving a client in process B, or if a +service in process A is bound to a component in process B, process A is always considered at least +as important as process B.

    + +

    Because a process running a service is ranked higher than a process with background activities, +an activity that initiates a long-running operation might do well to start a service for that operation, rather than +simply create a worker thread—particularly if the operation will likely outlast the activity. +For example, an activity that's uploading a picture to a web site should start a service to perform +the upload so that the upload can continue in the background even if the user leaves the activity. +Using a service guarantees that the operation will have at least "service process" priority, +regardless of what happens to the activity. This is the same reason that broadcast receivers should +employ services rather than simply put time-consuming operations in a thread.

    + + + + +

    Threads

    + +

    When an application is launched, the system creates a thread of execution for the application, +called "main." This thread is very important because it is in charge of dispatching events to +the appropriate user interface widgets, including drawing events. It is also the thread in which +your application interacts with components from the Android UI toolkit (components from the {@link +android.widget} and {@link android.view} packages). As such, the main thread is also sometimes +called the UI thread.

    + +

    The system does not create a separate thread for each instance of a component. All +components that run in the same process are instantiated in the UI thread, and system calls to +each component are dispatched from that thread. Consequently, methods that respond to system +callbacks (such as {@link android.view.View#onKeyDown onKeyDown()} to report user actions +or a lifecycle callback method) always run in the UI thread of the process.

    + +

    For instance, when the user touches a button on the screen, your app's UI thread dispatches the +touch event to the widget, which in turn sets its pressed state and posts an invalidate request to +the event queue. The UI thread dequeues the request and notifies the widget that it should redraw +itself.

    + +

    When your app performs intensive work in response to user interaction, this single thread model +can yield poor performance unless you implement your application properly. Specifically, if +everything is happening in the UI thread, performing long operations such as network access or +database queries will block the whole UI. When the thread is blocked, no events can be dispatched, +including drawing events. From the user's perspective, the +application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds +(about 5 seconds currently) the user is presented with the infamous "application not +responding" (ANR) dialog. The user might then decide to quit your application and uninstall it +if they are unhappy.

    + +

    Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate +your UI from a worker thread—you must do all manipulation to your user interface from the UI +thread. Thus, there are simply two rules to Android's single thread model:

    + +
      +
    1. Do not block the UI thread +
    2. Do not access the Android UI toolkit from outside the UI thread +
    + +

    Worker threads

    + +

    Because of the single thread model described above, it's vital to the responsiveness of your +application's UI that you do not block the UI thread. If you have operations to perform +that are not instantaneous, you should make sure to do them in separate threads ("background" or +"worker" threads).

    + +

    For example, below is some code for a click listener that downloads an image from a separate +thread and displays it in an {@link android.widget.ImageView}:

    + +
    +public void onClick(View v) {
    +    new Thread(new Runnable() {
    +        public void run() {
    +            Bitmap b = loadImageFromNetwork("http://example.com/image.png");
    +            mImageView.setImageBitmap(b);
    +        }
    +    }).start();
    +}
    +
    + +

    At first, this seems to work fine, because it creates a new thread to handle the network +operation. However, it violates the second rule of the single-threaded model: do not access the +Android UI toolkit from outside the UI thread—this sample modifies the {@link +android.widget.ImageView} from the worker thread instead of the UI thread. This can result in +undefined and unexpected behavior, which can be difficult and time-consuming to track down.

    + +

    To fix this problem, Android offers several ways to access the UI thread from other +threads. Here is a list of methods that can help:

    + +
      +
    • {@link android.app.Activity#runOnUiThread(java.lang.Runnable) +Activity.runOnUiThread(Runnable)}
    • +
    • {@link android.view.View#post(java.lang.Runnable) View.post(Runnable)}
    • +
    • {@link android.view.View#postDelayed(java.lang.Runnable, long) View.postDelayed(Runnable, +long)}
    • +
    + +

    For example, you can fix the above code by using the {@link +android.view.View#post(java.lang.Runnable) View.post(Runnable)} method:

    + +
    +public void onClick(View v) {
    +    new Thread(new Runnable() {
    +        public void run() {
    +            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
    +            mImageView.post(new Runnable() {
    +                public void run() {
    +                    mImageView.setImageBitmap(bitmap);
    +                }
    +            });
    +        }
    +    }).start();
    +}
    +
    + +

    Now this implementation is thread-safe: the network operation is done from a separate thread +while the {@link android.widget.ImageView} is manipulated from the UI thread.

    + +

    However, as the complexity of the operation grows, this kind of code can get complicated and +difficult to maintain. To handle more complex interactions with a worker thread, you might consider +using a {@link android.os.Handler} in your worker thread, to process messages delivered from the UI +thread. Perhaps the best solution, though, is to extend the {@link android.os.AsyncTask} class, +which simplifies the execution of worker thread tasks that need to interact with the UI.

    + + +

    Using AsyncTask

    + +

    {@link android.os.AsyncTask} allows you to perform asynchronous work on your user +interface. It performs the blocking operations in a worker thread and then publishes the results on +the UI thread, without requiring you to handle threads and/or handlers yourself.

    + +

    To use it, you must subclass {@link android.os.AsyncTask} and implement the {@link +android.os.AsyncTask#doInBackground doInBackground()} callback method, which runs in a pool of +background threads. To update your UI, you should implement {@link +android.os.AsyncTask#onPostExecute onPostExecute()}, which delivers the result from {@link +android.os.AsyncTask#doInBackground doInBackground()} and runs in the UI thread, so you can safely +update your UI. You can then run the task by calling {@link android.os.AsyncTask#execute execute()} +from the UI thread.

    + +

    For example, you can implement the previous example using {@link android.os.AsyncTask} this +way:

    + +
    +public void onClick(View v) {
    +    new DownloadImageTask().execute("http://example.com/image.png");
    +}
    +
    +private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    +    /** The system calls this to perform work in a worker thread and
    +      * delivers it the parameters given to AsyncTask.execute() */
    +    protected Bitmap doInBackground(String... urls) {
    +        return loadImageFromNetwork(urls[0]);
    +    }
    +    
    +    /** The system calls this to perform work in the UI thread and delivers
    +      * the result from doInBackground() */
    +    protected void onPostExecute(Bitmap result) {
    +        mImageView.setImageBitmap(result);
    +    }
    +}
    +
    + +

    Now the UI is safe and the code is simpler, because it separates the work into the +part that should be done on a worker thread and the part that should be done on the UI thread.

    + +

    You should read the {@link android.os.AsyncTask} reference for a full understanding on +how to use this class, but here is a quick overview of how it works:

    + +
      +
    • You can specify the type of the parameters, the progress values, and the final +value of the task, using generics
    • +
    • The method {@link android.os.AsyncTask#doInBackground doInBackground()} executes automatically +on a worker thread
    • +
    • {@link android.os.AsyncTask#onPreExecute onPreExecute()}, {@link +android.os.AsyncTask#onPostExecute onPostExecute()}, and {@link +android.os.AsyncTask#onProgressUpdate onProgressUpdate()} are all invoked on the UI thread
    • +
    • The value returned by {@link android.os.AsyncTask#doInBackground doInBackground()} is sent to +{@link android.os.AsyncTask#onPostExecute onPostExecute()}
    • +
    • You can call {@link android.os.AsyncTask#publishProgress publishProgress()} at anytime in {@link +android.os.AsyncTask#doInBackground doInBackground()} to execute {@link +android.os.AsyncTask#onProgressUpdate onProgressUpdate()} on the UI thread
    • +
    • You can cancel the task at any time, from any thread
    • +
    + +

    Caution: Another problem you might encounter when using a worker +thread is unexpected restarts in your activity due to a runtime configuration change +(such as when the user changes the screen orientation), which may destroy your worker thread. To +see how you can persist your task during one of these restarts and how to properly cancel the task +when the activity is destroyed, see the source code for the Shelves sample application.

    + + +

    Thread-safe methods

    + +

    In some situations, the methods you implement might be called from more than one thread, and +therefore must be written to be thread-safe.

    + +

    This is primarily true for methods that can be called remotely—such as methods in a bound service. When a call on a +method implemented in an {@link android.os.IBinder} originates in the same process in which the +{@link android.os.IBinder IBinder} is running, the method is executed in the caller's thread. +However, when the call originates in another process, the method is executed in a thread chosen from +a pool of threads that the system maintains in the same process as the {@link android.os.IBinder +IBinder} (it's not executed in the UI thread of the process). For example, whereas a service's +{@link android.app.Service#onBind onBind()} method would be called from the UI thread of the +service's process, methods implemented in the object that {@link android.app.Service#onBind +onBind()} returns (for example, a subclass that implements RPC methods) would be called from threads +in the pool. Because a service can have more than one client, more than one pool thread can engage +the same {@link android.os.IBinder IBinder} method at the same time. {@link android.os.IBinder +IBinder} methods must, therefore, be implemented to be thread-safe.

    + +

    Similarly, a content provider can receive data requests that originate in other processes. +Although the {@link android.content.ContentResolver} and {@link android.content.ContentProvider} +classes hide the details of how the interprocess communication is managed, {@link +android.content.ContentProvider} methods that respond to those requests—the methods {@link +android.content.ContentProvider#query query()}, {@link android.content.ContentProvider#insert +insert()}, {@link android.content.ContentProvider#delete delete()}, {@link +android.content.ContentProvider#update update()}, and {@link android.content.ContentProvider#getType +getType()}—are called from a pool of threads in the content provider's process, not the UI +thread for the process. Because these methods might be called from any number of threads at the +same time, they too must be implemented to be thread-safe.

    + + +

    Interprocess Communication

    + +

    Android offers a mechanism for interprocess communication (IPC) using remote procedure calls +(RPCs), in which a method is called by an activity or other application component, but executed +remotely (in another process), with any result returned back to the +caller. This entails decomposing a method call and its data to a level the operating system can +understand, transmitting it from the local process and address space to the remote process and +address space, then reassembling and reenacting the call there. Return values are then +transmitted in the opposite direction. Android provides all the code to perform these IPC +transactions, so you can focus on defining and implementing the RPC programming interface.

    + +

    To perform IPC, your application must bind to a service, using {@link +android.content.Context#bindService bindService()}. For more information, see the Services developer guide.

    + + + diff --git a/docs/html/guide/components/services.jd b/docs/html/guide/components/services.jd new file mode 100644 index 000000000000..ba5e1f03b277 --- /dev/null +++ b/docs/html/guide/components/services.jd @@ -0,0 +1,874 @@ +page.title=Services +@jd:body + +
    +
      +

      Quickview

      +
        +
      • A service can run in the background to perform work even while the user is in a different +application
      • +
      • A service can allow other components to bind to it, in order to interact with it and +perform interprocess communication
      • +
      • A service runs in the main thread of the application that hosts it, by default
      • +
      +

      In this document

      +
        +
      1. The Basics
      2. +
          +
        1. Declaring a service in the manifest
        2. +
        +
      3. Creating a Started Service +
          +
        1. Extending the IntentService class
        2. +
        3. Extending the Service class
        4. +
        5. Starting a service
        6. +
        7. Stopping a service
        8. +
        +
      4. +
      5. Creating a Bound Service
      6. +
      7. Sending Notifications to the User
      8. +
      9. Running a Service in the Foreground
      10. +
      11. Managing the Lifecycle of a Service +
          +
        1. Implementing the lifecycle callbacks
        2. +
        +
      12. +
      + +

      Key classes

      +
        +
      1. {@link android.app.Service}
      2. +
      3. {@link android.app.IntentService}
      4. +
      + +

      Samples

      +
        +
      1. {@code + ServiceStartArguments}
      2. +
      3. {@code + LocalService}
      4. +
      + +

      Articles

      +
        +
      1. Multitasking the Android Way
      2. +
      3. Service API changes starting + with Android 2.0
      4. +
      + +

      See also

      +
        +
      1. Bound Services
      2. +
      + +
    + + +

    A {@link android.app.Service} is an application component that can perform +long-running operations in the background and does not provide a user interface. Another +application component can start a service and it will continue to run in the background even if the +user switches to another application. Additionally, a component can bind to a service to +interact with it and even perform interprocess communication (IPC). For example, a service might +handle network transactions, play music, perform file I/O, or interact with a content provider, all +from the background.

    + +

    A service can essentially take two forms:

    + +
    +
    Started
    +
    A service is "started" when an application component (such as an activity) starts it by +calling {@link android.content.Context#startService startService()}. Once started, a service +can run in the background indefinitely, even if the component that started it is destroyed. Usually, +a started service performs a single operation and does not return a result to the caller. +For example, it might download or upload a file over the network. When the operation is done, the +service should stop itself.
    +
    Bound
    +
    A service is "bound" when an application component binds to it by calling {@link +android.content.Context#bindService bindService()}. A bound service offers a client-server +interface that allows components to interact with the service, send requests, get results, and even +do so across processes with interprocess communication (IPC). A bound service runs only as long as +another application component is bound to it. Multiple components can bind to the service at once, +but when all of them unbind, the service is destroyed.
    +
    + +

    Although this documentation generally discusses these two types of services separately, your +service can work both ways—it can be started (to run indefinitely) and also allow binding. +It's simply a matter of whether you implement a couple callback methods: {@link +android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link +android.app.Service#onBind onBind()} to allow binding.

    + +

    Regardless of whether your application is started, bound, or both, any application component +can use the service (even from a separate application), in the same way that any component can use +an activity—by starting it with an {@link android.content.Intent}. However, you can declare +the service as private, in the manifest file, and block access from other applications. This is +discussed more in the section about Declaring the service in the +manifest.

    + +

    Caution: A service runs in the +main thread of its hosting process—the service does not create its own thread +and does not run in a separate process (unless you specify otherwise). This means +that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 +playback or networking), you should create a new thread within the service to do that work. By using +a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the +application's main thread can remain dedicated to user interaction with your activities.

    + + +

    The Basics

    + + + +

    To create a service, you must create a subclass of {@link android.app.Service} (or one +of its existing subclasses). In your implementation, you need to override some callback methods that +handle key aspects of the service lifecycle and provide a mechanism for components to bind to +the service, if appropriate. The most important callback methods you should override are:

    + +
    +
    {@link android.app.Service#onStartCommand onStartCommand()}
    +
    The system calls this method when another component, such as an activity, +requests that the service be started, by calling {@link android.content.Context#startService +startService()}. Once this method executes, the service is started and can run in the +background indefinitely. If you implement this, it is your responsibility to stop the service when +its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}. (If you only want to provide binding, you don't +need to implement this method.)
    +
    {@link android.app.Service#onBind onBind()}
    +
    The system calls this method when another component wants to bind with the +service (such as to perform RPC), by calling {@link android.content.Context#bindService +bindService()}. In your implementation of this method, you must provide an interface that clients +use to communicate with the service, by returning an {@link android.os.IBinder}. You must always +implement this method, but if you don't want to allow binding, then you should return null.
    +
    {@link android.app.Service#onCreate()}
    +
    The system calls this method when the service is first created, to perform one-time setup +procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or +{@link android.app.Service#onBind onBind()}). If the service is already running, this method is not +called.
    +
    {@link android.app.Service#onDestroy()}
    +
    The system calls this method when the service is no longer used and is being destroyed. +Your service should implement this to clean up any resources such as threads, registered +listeners, receivers, etc. This is the last call the service receives.
    +
    + +

    If a component starts the service by calling {@link +android.content.Context#startService startService()} (which results in a call to {@link +android.app.Service#onStartCommand onStartCommand()}), then the service +remains running until it stops itself with {@link android.app.Service#stopSelf()} or another +component stops it by calling {@link android.content.Context#stopService stopService()}.

    + +

    If a component calls +{@link android.content.Context#bindService bindService()} to create the service (and {@link +android.app.Service#onStartCommand onStartCommand()} is not called), then the service runs +only as long as the component is bound to it. Once the service is unbound from all clients, the +system destroys it.

    + +

    The Android system will force-stop a service only when memory is low and it must recover system +resources for the activity that has user focus. If the service is bound to an activity that has user +focus, then it's less likely to be killed, and if the service is declared to run in the foreground (discussed later), then it will almost never be killed. +Otherwise, if the service was started and is long-running, then the system will lower its position +in the list of background tasks over time and the service will become highly susceptible to +killing—if your service is started, then you must design it to gracefully handle restarts +by the system. If the system kills your service, it restarts it as soon as resources become +available again (though this also depends on the value you return from {@link +android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information +about when the system might destroy a service, see the Processes and Threading +document.

    + +

    In the following sections, you'll see how you can create each type of service and how to use +it from other application components.

    + + + +

    Declaring a service in the manifest

    + +

    Like activities (and other components), you must declare all services in your application's +manifest file.

    + +

    To declare your service, add a {@code <service>} element +as a child of the {@code <application>} +element. For example:

    + +
    +<manifest ... >
    +  ...
    +  <application ... >
    +      <service android:name=".ExampleService" />
    +      ...
    +  </application>
    +</manifest>
    +
    + +

    There are other attributes you can include in the {@code <service>} element to +define properties such as permissions required to start the service and the process in +which the service should run. The {@code android:name} +attribute is the only required attribute—it specifies the class name of the service. Once +you publish your application, you should not change this name, because if you do, you might break +some functionality where explicit intents are used to reference your service (read the blog post, Things +That Cannot Change). + +

    See the {@code <service>} element +reference for more information about declaring your service in the manifest.

    + +

    Just like an activity, a service can define intent filters that allow other components to +invoke the service using implicit intents. By declaring intent filters, components +from any application installed on the user's device can potentially start your service if your +service declares an intent filter that matches the intent another application passes to {@link +android.content.Context#startService startService()}.

    + +

    If you plan on using your service only locally (other applications do not use it), then you +don't need to (and should not) supply any intent filters. Without any intent filters, you must +start the service using an intent that explicitly names the service class. More information +about starting a service is discussed below.

    + +

    Additionally, you can ensure that your service is private to your application only if +you include the {@code android:exported} +attribute and set it to {@code "false"}. This is effective even if your service supplies intent +filters.

    + +

    For more information about creating intent filters for your service, see the Intents and Intent Filters +document.

    + + + +

    Creating a Started Service

    + + + +

    A started service is one that another component starts by calling {@link +android.content.Context#startService startService()}, resulting in a call to the service's +{@link android.app.Service#onStartCommand onStartCommand()} method.

    + +

    When a service is started, it has a lifecycle that's independent of the +component that started it and the service can run in the background indefinitely, even if +the component that started it is destroyed. As such, the service should stop itself when its job +is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it +by calling {@link android.content.Context#stopService stopService()}.

    + +

    An application component such as an activity can start the service by calling {@link +android.content.Context#startService startService()} and passing an {@link android.content.Intent} +that specifies the service and includes any data for the service to use. The service receives +this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand +onStartCommand()} method.

    + +

    For instance, suppose an activity needs to save some data to an online database. The activity can +start a companion service and deliver it the data to save by passing an intent to {@link +android.content.Context#startService startService()}. The service receives the intent in {@link +android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the +database transaction. When the transaction is done, the service stops itself and it is +destroyed.

    + +

    Caution: A services runs in the same process as the application +in which it is declared and in the main thread of that application, by default. So, if your service +performs intensive or blocking operations while the user interacts with an activity from the same +application, the service will slow down activity performance. To avoid impacting application +performance, you should start a new thread inside the service.

    + +

    Traditionally, there are two classes you can extend to create a started service:

    +
    +
    {@link android.app.Service}
    +
    This is the base class for all services. When you extend this class, it's important that +you create a new thread in which to do all the service's work, because the service uses your +application's main thread, by default, which could slow the performance of any activity your +application is running.
    +
    {@link android.app.IntentService}
    +
    This is a subclass of {@link android.app.Service} that uses a worker thread to handle all +start requests, one at a time. This is the best option if you don't require that your service +handle multiple requests simultaneously. All you need to do is implement {@link +android.app.IntentService#onHandleIntent onHandleIntent()}, which receives the intent for each +start request so you can do the background work.
    +
    + +

    The following sections describe how you can implement your service using either one for these +classes.

    + + +

    Extending the IntentService class

    + +

    Because most started services don't need to handle multiple requests simultaneously +(which can actually be a dangerous multi-threading scenario), it's probably best if you +implement your service using the {@link android.app.IntentService} class.

    + +

    The {@link android.app.IntentService} does the following:

    + +
      +
    • Creates a default worker thread that executes all intents delivered to {@link +android.app.Service#onStartCommand onStartCommand()} separate from your application's main +thread.
    • +
    • Creates a work queue that passes one intent at a time to your {@link +android.app.IntentService#onHandleIntent onHandleIntent()} implementation, so you never have to +worry about multi-threading.
    • +
    • Stops the service after all start requests have been handled, so you never have to call +{@link android.app.Service#stopSelf}.
    • +
    • Provides default implementation of {@link android.app.IntentService#onBind onBind()} that +returns null.
    • +
    • Provides a default implementation of {@link android.app.IntentService#onStartCommand +onStartCommand()} that sends the intent to the work queue and then to your {@link +android.app.IntentService#onHandleIntent onHandleIntent()} implementation.
    • +
    + +

    All this adds up to the fact that all you need to do is implement {@link +android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the +client. (Though, you also need to provide a small constructor for the service.)

    + +

    Here's an example implementation of {@link android.app.IntentService}:

    + +
    +public class HelloIntentService extends IntentService {
    +
    +  /** 
    +   * A constructor is required, and must call the super {@link android.app.IntentService#IntentService}
    +   * constructor with a name for the worker thread.
    +   */
    +  public HelloIntentService() {
    +      super("HelloIntentService");
    +  }
    +
    +  /**
    +   * The IntentService calls this method from the default worker thread with
    +   * the intent that started the service. When this method returns, IntentService
    +   * stops the service, as appropriate.
    +   */
    +  @Override
    +  protected void onHandleIntent(Intent intent) {
    +      // Normally we would do some work here, like download a file.
    +      // For our sample, we just sleep for 5 seconds.
    +      long endTime = System.currentTimeMillis() + 5*1000;
    +      while (System.currentTimeMillis() < endTime) {
    +          synchronized (this) {
    +              try {
    +                  wait(endTime - System.currentTimeMillis());
    +              } catch (Exception e) {
    +              }
    +          }
    +      }
    +  }
    +}
    +
    + +

    That's all you need: a constructor and an implementation of {@link +android.app.IntentService#onHandleIntent onHandleIntent()}.

    + +

    If you decide to also override other callback methods, such as {@link +android.app.IntentService#onCreate onCreate()}, {@link +android.app.IntentService#onStartCommand onStartCommand()}, or {@link +android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so +that the {@link android.app.IntentService} can properly handle the life of the worker thread.

    + +

    For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return +the default implementation (which is how the intent gets delivered to {@link +android.app.IntentService#onHandleIntent onHandleIntent()}):

    + +
    +@Override
    +public int onStartCommand(Intent intent, int flags, int startId) {
    +    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    +    return super.onStartCommand(intent,flags,startId);
    +}
    +
    + +

    Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method +from which you don't need to call the super class is {@link android.app.IntentService#onBind +onBind()} (but you only need to implement that if your service allows binding).

    + +

    In the next section, you'll see how the same kind of service is implemented when extending +the base {@link android.app.Service} class, which is a lot more code, but which might be +appropriate if you need to handle simultaneous start requests.

    + + +

    Extending the Service class

    + +

    As you saw in the previous section, using {@link android.app.IntentService} makes your +implementation of a started service very simple. If, however, you require your service to +perform multi-threading (instead of processing start requests through a work queue), then you +can extend the {@link android.app.Service} class to handle each intent.

    + +

    For comparison, the following example code is an implementation of the {@link +android.app.Service} class that performs the exact same work as the example above using {@link +android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the +job and processes only one request at a time.

    + +
    +public class HelloService extends Service {
    +  private Looper mServiceLooper;
    +  private ServiceHandler mServiceHandler;
    +
    +  // Handler that receives messages from the thread
    +  private final class ServiceHandler extends Handler {
    +      public ServiceHandler(Looper looper) {
    +          super(looper);
    +      }
    +      @Override
    +      public void handleMessage(Message msg) {
    +          // Normally we would do some work here, like download a file.
    +          // For our sample, we just sleep for 5 seconds.
    +          long endTime = System.currentTimeMillis() + 5*1000;
    +          while (System.currentTimeMillis() < endTime) {
    +              synchronized (this) {
    +                  try {
    +                      wait(endTime - System.currentTimeMillis());
    +                  } catch (Exception e) {
    +                  }
    +              }
    +          }
    +          // Stop the service using the startId, so that we don't stop
    +          // the service in the middle of handling another job
    +          stopSelf(msg.arg1);
    +      }
    +  }
    +
    +  @Override
    +  public void onCreate() {
    +    // Start up the thread running the service.  Note that we create a
    +    // separate thread because the service normally runs in the process's
    +    // main thread, which we don't want to block.  We also make it
    +    // background priority so CPU-intensive work will not disrupt our UI.
    +    HandlerThread thread = new HandlerThread("ServiceStartArguments",
    +            Process.THREAD_PRIORITY_BACKGROUND);
    +    thread.start();
    +    
    +    // Get the HandlerThread's Looper and use it for our Handler 
    +    mServiceLooper = thread.getLooper();
    +    mServiceHandler = new ServiceHandler(mServiceLooper);
    +  }
    +
    +  @Override
    +  public int onStartCommand(Intent intent, int flags, int startId) {
    +      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    +
    +      // For each start request, send a message to start a job and deliver the
    +      // start ID so we know which request we're stopping when we finish the job
    +      Message msg = mServiceHandler.obtainMessage();
    +      msg.arg1 = startId;
    +      mServiceHandler.sendMessage(msg);
    +      
    +      // If we get killed, after returning from here, restart
    +      return START_STICKY;
    +  }
    +
    +  @Override
    +  public IBinder onBind(Intent intent) {
    +      // We don't provide binding, so return null
    +      return null;
    +  }
    +  
    +  @Override
    +  public void onDestroy() {
    +    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
    +  }
    +}
    +
    + +

    As you can see, it's a lot more work than using {@link android.app.IntentService}.

    + +

    However, because you handle each call to {@link android.app.Service#onStartCommand +onStartCommand()} yourself, you can perform multiple requests simultaneously. That's not what +this example does, but if that's what you want, then you can create a new thread for each +request and run them right away (instead of waiting for the previous request to finish).

    + +

    Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an +integer. The integer is a value that describes how the system should continue the service in the +event that the system kills it (as discussed above, the default implementation for {@link +android.app.IntentService} handles this for you, though you are able to modify it). The return value +from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following +constants:

    + +
    +
    {@link android.app.Service#START_NOT_STICKY}
    +
    If the system kills the service after {@link android.app.Service#onStartCommand +onStartCommand()} returns, do not recreate the service, unless there are pending +intents to deliver. This is the safest option to avoid running your service when not necessary +and when your application can simply restart any unfinished jobs.
    +
    {@link android.app.Service#START_STICKY}
    +
    If the system kills the service after {@link android.app.Service#onStartCommand +onStartCommand()} returns, recreate the service and call {@link +android.app.Service#onStartCommand onStartCommand()}, but do not redeliver the last intent. +Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a +null intent, unless there were pending intents to start the service, in which case, +those intents are delivered. This is suitable for media players (or similar services) that are not +executing commands, but running indefinitely and waiting for a job.
    +
    {@link android.app.Service#START_REDELIVER_INTENT}
    +
    If the system kills the service after {@link android.app.Service#onStartCommand +onStartCommand()} returns, recreate the service and call {@link +android.app.Service#onStartCommand onStartCommand()} with the last intent that was delivered to the +service. Any pending intents are delivered in turn. This is suitable for services that are +actively performing a job that should be immediately resumed, such as downloading a file.
    +
    +

    For more details about these return values, see the linked reference documentation for each +constant.

    + + + +

    Starting a Service

    + +

    You can start a service from an activity or other application component by passing an +{@link android.content.Intent} (specifying the service to start) to {@link +android.content.Context#startService startService()}. The Android system calls the service's {@link +android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link +android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand +onStartCommand()} directly.)

    + +

    For example, an activity can start the example service in the previous section ({@code +HelloSevice}) using an explicit intent with {@link android.content.Context#startService +startService()}:

    + +
    +Intent intent = new Intent(this, HelloService.class);
    +startService(intent);
    +
    + +

    The {@link android.content.Context#startService startService()} method returns immediately and +the Android system calls the service's {@link android.app.Service#onStartCommand +onStartCommand()} method. If the service is not already running, the system first calls {@link +android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand +onStartCommand()}.

    + +

    If the service does not also provide binding, the intent delivered with {@link +android.content.Context#startService startService()} is the only mode of communication between the +application component and the service. However, if you want the service to send a result back, then +the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast +(with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service +in the {@link android.content.Intent} that starts the service. The service can then use the +broadcast to deliver a result.

    + +

    Multiple requests to start the service result in multiple corresponding calls to the service's +{@link android.app.Service#onStartCommand onStartCommand()}. However, only one request to stop +the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}) is required to stop it.

    + + +

    Stopping a service

    + +

    A started service must manage its own lifecycle. That is, the system does not stop or +destroy the service unless it must recover system memory and the service +continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So, +the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another +component can stop it by calling {@link android.content.Context#stopService stopService()}.

    + +

    Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}, the system destroys the service as soon as +possible.

    + +

    However, if your service handles multiple requests to {@link +android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the +service when you're done processing a start request, because you might have since received a new +start request (stopping at the end of the first request would terminate the second one). To avoid +this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to +stop the service is always based on the most recent start request. That is, when you call {@link +android.app.Service#stopSelf(int)}, you pass the ID of the start request (the startId +delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request +corresponds. Then if the service received a new start request before you were able to call {@link +android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.

    + +

    Caution: It's important that your application stops its services +when it's done working, to avoid wasting system resources and consuming battery power. If necessary, +other components can stop the service by calling {@link +android.content.Context#stopService stopService()}. Even if you enable binding for the service, +you must always stop the service yourself if it ever received a call to {@link +android.app.Service#onStartCommand onStartCommand()}.

    + +

    For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.

    + + + +

    Creating a Bound Service

    + +

    A bound service is one that allows application components to bind to it by calling {@link +android.content.Context#bindService bindService()} in order to create a long-standing connection +(and generally does not allow components to start it by calling {@link +android.content.Context#startService startService()}).

    + +

    You should create a bound service when you want to interact with the service from activities +and other components in your application or to expose some of your application's functionality to +other applications, through interprocess communication (IPC).

    + +

    To create a bound service, you must implement the {@link +android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that +defines the interface for communication with the service. Other application components can then call +{@link android.content.Context#bindService bindService()} to retrieve the interface and +begin calling methods on the service. The service lives only to serve the application component that +is bound to it, so when there are no components bound to the service, the system destroys it +(you do not need to stop a bound service in the way you must when the service is started +through {@link android.app.Service#onStartCommand onStartCommand()}).

    + +

    To create a bound service, the first thing you must do is define the interface that specifies +how a client can communicate with the service. This interface between the service +and a client must be an implementation of {@link android.os.IBinder} and is what your service must +return from the {@link android.app.Service#onBind +onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin +interacting with the service through that interface.

    + +

    Multiple clients can bind to the service at once. When a client is done interacting with the +service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once +there are no clients bound to the service, the system destroys the service.

    + +

    There are multiple ways to implement a bound service and the implementation is more +complicated than a started service, so the bound service discussion appears in a separate +document about Bound Services.

    + + + +

    Sending Notifications to the User

    + +

    Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.

    + +

    A toast notification is a message that appears on the surface of the current window for a +moment then disappears, while a status bar notification provides an icon in the status bar with a +message, which the user can select in order to take an action (such as start an activity).

    + +

    Usually, a status bar notification is the best technique when some background work has completed +(such as a file completed +downloading) and the user can now act on it. When the user selects the notification from the +expanded view, the notification can start an activity (such as to view the downloaded file).

    + +

    See the Toast Notifications or Status Bar Notifications +developer guides for more information.

    + + + +

    Running a Service in the Foreground

    + +

    A foreground service is a service that's considered to be something the +user is actively aware of and thus not a candidate for the system to kill when low on memory. A +foreground service must provide a notification for the status bar, which is placed under the +"Ongoing" heading, which means that the notification cannot be dismissed unless the service is +either stopped or removed from the foreground.

    + +

    For example, a music player that plays music from a service should be set to run in the +foreground, because the user is explicitly aware +of its operation. The notification in the status bar might indicate the current song and allow +the user to launch an activity to interact with the music player.

    + +

    To request that your service run in the foreground, call {@link +android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer +that uniquely identifies the notification and the {@link +android.app.Notification} for the status bar. For example:

    + +
    +Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
    +        System.currentTimeMillis());
    +Intent notificationIntent = new Intent(this, ExampleActivity.class);
    +PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    +notification.setLatestEventInfo(this, getText(R.string.notification_title),
    +        getText(R.string.notification_message), pendingIntent);
    +startForeground(ONGOING_NOTIFICATION, notification);
    +
    + + +

    To remove the service from the foreground, call {@link +android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating +whether to remove the status bar notification as well. This method does not stop the +service. However, if you stop the service while it's still running in the foreground, then the +notification is also removed.

    + +

    Note: The methods {@link +android.app.Service#startForeground startForeground()} and {@link +android.app.Service#stopForeground stopForeground()} were introduced in Android 2.0 (API Level +5). In order to run your service in the foreground on older versions of the platform, you must +use the previous {@code setForeground()} method—see the {@link +android.app.Service#startForeground startForeground()} documentation for information about how +to provide backward compatibility.

    + +

    For more information about notifications, see Creating Status Bar +Notifications.

    + + + +

    Managing the Lifecycle of a Service

    + +

    The lifecycle of a service is much simpler than that of an activity. However, it's even more important +that you pay close attention to how your service is created and destroyed, because a service +can run in the background without the user being aware.

    + +

    The service lifecycle—from when it's created to when it's destroyed—can follow two +different paths:

    + +
      +
    • A started service +

      The service is created when another component calls {@link +android.content.Context#startService startService()}. The service then runs indefinitely and must +stop itself by calling {@link +android.app.Service#stopSelf() stopSelf()}. Another component can also stop the +service by calling {@link android.content.Context#stopService +stopService()}. When the service is stopped, the system destroys it..

    • + +
    • A bound service +

      The service is created when another component (a client) calls {@link +android.content.Context#bindService bindService()}. The client then communicates with the service +through an {@link android.os.IBinder} interface. The client can close the connection by calling +{@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to +the same service and when all of them unbind, the system destroys the service. (The service +does not need to stop itself.)

    • +
    + +

    These two paths are not entirely separate. That is, you can bind to a service that was already +started with {@link android.content.Context#startService startService()}. For example, a background +music service could be started by calling {@link android.content.Context#startService +startService()} with an {@link android.content.Intent} that identifies the music to play. Later, +possibly when the user wants to exercise some control over the player or get information about the +current song, an activity can bind to the service by calling {@link +android.content.Context#bindService bindService()}. In cases like this, {@link +android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf +stopSelf()} does not actually stop the service until all clients unbind.

    + + +

    Implementing the lifecycle callbacks

    + +

    Like an activity, a service has lifecycle callback methods that you can implement to monitor +changes in the service's state and perform work at the appropriate times. The following skeleton +service demonstrates each of the lifecycle methods:

    + + +
    + +

    Figure 2. The service lifecycle. The diagram on the left +shows the lifecycle when the service is created with {@link android.content.Context#startService +startService()} and the diagram on the right shows the lifecycle when the service is created +with {@link android.content.Context#bindService bindService()}.

    +
    + +
    +public class ExampleService extends Service {
    +    int mStartMode;       // indicates how to behave if the service is killed
    +    IBinder mBinder;      // interface for clients that bind
    +    boolean mAllowRebind; // indicates whether onRebind should be used
    +
    +    @Override
    +    public void {@link android.app.Service#onCreate onCreate}() {
    +        // The service is being created
    +    }
    +    @Override
    +    public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) {
    +        // The service is starting, due to a call to {@link android.content.Context#startService startService()}
    +        return mStartMode;
    +    }
    +    @Override
    +    public IBinder {@link android.app.Service#onBind onBind}(Intent intent) {
    +        // A client is binding to the service with {@link android.content.Context#bindService bindService()}
    +        return mBinder;
    +    }
    +    @Override
    +    public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) {
    +        // All clients have unbound with {@link android.content.Context#unbindService unbindService()}
    +        return mAllowRebind;
    +    }
    +    @Override
    +    public void {@link android.app.Service#onRebind onRebind}(Intent intent) {
    +        // A client is binding to the service with {@link android.content.Context#bindService bindService()},
    +        // after onUnbind() has already been called
    +    }
    +    @Override
    +    public void {@link android.app.Service#onDestroy onDestroy}() {
    +        // The service is no longer used and is being destroyed
    +    }
    +}
    +
    + +

    Note: Unlike the activity lifecycle callback methods, you are +not required to call the superclass implementation of these callback methods.

    + +

    By implementing these methods, you can monitor two nested loops of the service's lifecycle:

    + +
      +
    • The entire lifetime of a service happens between the time {@link +android.app.Service#onCreate onCreate()} is called and the time {@link +android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in +{@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link +android.app.Service#onDestroy onDestroy()}. For example, a +music playback service could create the thread where the music will be played in {@link +android.app.Service#onCreate onCreate()}, then stop the thread in {@link +android.app.Service#onDestroy onDestroy()}. + +

      The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy +onDestroy()} methods are called for all services, whether +they're created by {@link android.content.Context#startService startService()} or {@link +android.content.Context#bindService bindService()}.

    • + +
    • The active lifetime of a service begins with a call to either {@link +android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}. +Each method is handed the {@link +android.content.Intent} that was passed to either {@link android.content.Context#startService +startService()} or {@link android.content.Context#bindService bindService()}, respectively. +

      If the service is started, the active lifetime ends the same time that the entire lifetime +ends (the service is still active even after {@link android.app.Service#onStartCommand +onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link +android.app.Service#onUnbind onUnbind()} returns.

      +
    • +
    + +

    Note: Although a started service is stopped by a call to +either {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}, there is not a respective callback for the +service (there's no {@code onStop()} callback). So, unless the service is bound to a client, +the system destroys it when the service is stopped—{@link +android.app.Service#onDestroy onDestroy()} is the only callback received.

    + +

    Figure 2 illustrates the typical callback methods for a service. Although the figure separates +services that are created by {@link android.content.Context#startService startService()} from those +created by {@link android.content.Context#bindService bindService()}, keep +in mind that any service, no matter how it's started, can potentially allow clients to bind to it. +So, a service that was initially started with {@link android.app.Service#onStartCommand +onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) +can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls +{@link android.content.Context#bindService bindService()}).

    + +

    For more information about creating a service that provides binding, see the Bound Services document, +which includes more information about the {@link android.app.Service#onRebind onRebind()} +callback method in the section about Managing the Lifecycle of +a Bound Service.

    + + + diff --git a/docs/html/guide/components/tasks-and-back-stack.jd b/docs/html/guide/components/tasks-and-back-stack.jd new file mode 100644 index 000000000000..8b7041cef826 --- /dev/null +++ b/docs/html/guide/components/tasks-and-back-stack.jd @@ -0,0 +1,595 @@ +page.title=Tasks and Back Stack +parent.title=Activities +parent.link=activities.html +@jd:body + +
    +
    +

    Quickview

    +
      +
    • All activities belong to a task
    • +
    • A task contains a collection of activities in the order in which the user interacts with +them
    • +
    • Tasks can move to the background and retain the state of each activity in order for users +to perform other tasks without losing their work
    • +
    + +

    In this document

    +
      +
    1. Saving Activity State
    2. +
    3. Managing Tasks +
        +
      1. Defining launch modes
      2. +
      3. Handling affinities
      4. +
      5. Clearing the back stack
      6. +
      7. Starting a task
      8. +
      +
    4. +
    + +

    Articles

    +
      +
    1. Multitasking the Android Way
    2. +
    + +

    See also

    +
      +
    1. Android Design: +Navigation
    2. +
    3. {@code <activity>} manifest +element
    4. +
    +
    +
    + + +

    An application usually contains multiple activities. Each activity +should be designed around a specific kind of action the user can perform and can start other +activities. For example, an email application might have one activity to show a list of new email. +When the user selects an email, a new activity opens to view that email.

    + +

    An activity can even start activities that exist in other applications on the device. For +example, if your application wants to send an email, you can define an intent to perform a "send" +action and include some data, such as an email address and a message. An activity from another +application that declares itself to handle this kind of intent then opens. In this case, the intent +is to send an email, so an email application's "compose" activity starts (if multiple activities +support the same intent, then the system lets the user select which one to use). When the email is +sent, your activity resumes and it seems as if the email activity was part of your application. Even +though the activities may be from different applications, Android maintains this seamless user +experience by keeping both activities in the same task.

    + +

    A task is a collection of activities that users interact with +when performing a certain job. The activities are arranged in a stack (the "back stack"), in the +order in which each activity is opened.

    + + + +

    The device Home screen is the starting place for most tasks. When the user touches an icon in the +application +launcher (or a shortcut on the Home screen), that application's task comes to the foreground. If no +task exists for the application (the application has not been used recently), then a new task +is created and the "main" activity for that application opens as the root activity in the stack.

    + +

    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 +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 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.

    + + +

    Figure 1. A representation of how each new activity in a +task adds an item to the back stack. When the user presses the Back button, the current +activity is +destroyed and the previous activity resumes.

    + + +

    If the user continues to press Back, 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.

    + +
    +

    Figure 2. Two tasks: Task B receives user interaction +in the foreground, while Task A is in the background, waiting to be resumed.

    +
    +
    +

    Figure 3. A single activity is instantiated multiple times.

    +
    + +

    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 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 +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 +that application, the user returns Home again and selects the application that originally +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 button to reveal recent tasks +and selecting +one). This is an example of multitasking on Android.

    + +

    Note: Multiple tasks can be held in the background at once. +However, if the user is running many background tasks at the same time, the system might begin +destroying background activities in order to recover memory, causing the activity states to be lost. +See the following section about Activity state.

    + +

    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 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 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 Managing Tasks.

    + + +

    To summarize the default behavior for activities and tasks:

    + +
      +
    • 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 button while in Activity B, Activity A resumes with its state +restored.
    • +
    • When the user leaves a task by pressing the Home 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.
    • +
    • If the user presses the Back 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 +does not retain the activity's state.
    • +
    • Activities can be instantiated multiple times, even from other tasks.
    • +
    + + +
    +

    Navigation Design

    +

    For more about how app navigation works on Android, read Android Design's Navigation guide.

    +
    + + +

    Saving Activity State

    + +

    As discussed above, the system's default behavior preserves the state of an activity when it is +stopped. This way, when users navigate back to a previous activity, its user interface appears +the way they left it. However, you can—and should—proactively retain +the state of your activities using callback methods, in case the activity is destroyed and must +be recreated.

    + +

    When the system stops one of your activities (such as when a new activity starts or the task +moves to the background), the system might destroy that activity completely if it needs to recover +system memory. When this happens, information about the activity state is lost. If this happens, the +system still +knows that the activity has a place in the back stack, but when the activity is brought to the +top of the stack the system must recreate it (rather than resume it). In order to +avoid losing the user's work, you should proactively retain it by implementing the {@link +android.app.Activity#onSaveInstanceState onSaveInstanceState()} callback +methods in your activity.

    + +

    For more information about how to save your activity state, see the Activities +document.

    + + + +

    Managing Tasks

    + +

    The way Android manages tasks and the back stack, as described above—by placing all +activities started in succession in the same task and in a "last in, first out" stack—works +great for most applications and you shouldn't have to worry about how your activities are associated +with tasks or how they exist in the back stack. However, you might decide that you want to interrupt +the normal behavior. Perhaps you want an activity in your application to begin a new task when it is +started (instead of being placed within the current task); or, when you start an activity, you want +to bring forward an existing instance of it (instead of creating a new +instance on top of the back stack); or, you want your back stack to be cleared of all +activities except for the root activity when the user leaves the task.

    + +

    You can do these things and more, with attributes in the +{@code +<activity>} manifest element and with flags in the intent that you pass to {@link +android.app.Activity#startActivity startActivity()}.

    + +

    In this regard, the the principal {@code <activity>} +attributes you can use are:

    + + + +

    And the principal intent flags you can use are:

    + +
      +
    • {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}
    • +
    • {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}
    • +
    • {@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}
    • +
    + +

    In the following sections, you'll see how you can use these manifest attributes and intent +flags to define how activities are associated with tasks and how the behave in the back stack.

    + + +

    Caution: 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 button. +Be sure +to test for navigation behaviors that might conflict with the user's expected behavior.

    + + +

    Defining launch modes

    + +

    Launch modes allow you to define how a new instance of an activity is associated with the +current task. You can define different launch modes in two ways:

    +
      +
    • Using the manifest file +

      When you declare an activity in your manifest file, you can specify how the activity +should associate with tasks when it starts.

    • +
    • Using Intent flags +

      When you call {@link android.app.Activity#startActivity startActivity()}, +you can include a flag in the {@link android.content.Intent} that declares how (or +whether) the new activity should associate with the current task.

    • +
    + +

    As such, if Activity A starts Activity B, Activity B can define in its manifest how it +should associate with the current task (if at all) and Activity A can also request how Activity +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).

    + +

    Note: 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.

    + + +

    Using the manifest file

    + +

    When declaring an activity in your manifest file, you can specify how the activity should +associate with a task using the {@code <activity>} +element's {@code +launchMode} attribute.

    + +

    The {@code +launchMode} attribute specifies an instruction on how the activity should be launched into a +task. There are four different launch modes you can assign to the +launchMode +attribute:

    + +
    +
    {@code "standard"} (the default mode)
    +
    Default. The system creates a new instance of the activity in the task from +which it was started and routes the intent to it. The activity can be instantiated multiple times, +each instance can belong to different tasks, and one task can have multiple instances.
    +
    {@code "singleTop"}
    +
    If an instance of the activity already exists at the top of the current task, the system +routes the intent to that instance through a call to its {@link +android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a new instance of the +activity. The activity can be instantiated multiple times, each instance can +belong to different tasks, and one task can have multiple instances (but only if the the +activity at the top of the back stack is not an existing instance of the activity). +

    For example, suppose a task's back stack consists of root activity A with activities B, C, +and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of type D. +If D has the default {@code "standard"} launch mode, a new instance of the class is launched and the +stack becomes A-B-C-D-D. However, if D's launch mode is {@code "singleTop"}, the existing instance +of D receives the intent through {@link +android.app.Activity#onNewIntent onNewIntent()}, because it's at the top of the stack—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"}.

    +

    Note: When a new instance of an activity is created, +the user can press the Back button to return to the previous activity. But when an existing +instance of +an activity handles a new intent, the user cannot press the Back button to return to the +state of +the activity before the new intent arrived in {@link android.app.Activity#onNewIntent +onNewIntent()}.

    +
    + +
    {@code "singleTask"}
    +
    The system creates a new task and instantiates the activity at the root of the new task. +However, if an instance of the activity already exists in a separate task, the system routes the +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. +

    Note: Although the activity starts in a new task, the +Back button still returns the user to the previous activity.

    +
    {@code "singleInstance"}.
    +
    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; +any activities started by this one open in a separate task.
    +
    + + +

    As another example, the Android Browser application declares that the web browser activity should +always open in its own task—by specifying the {@code singleTask} launch mode in the {@code <activity>} element. +This means that if your application issues an +intent to open the Android Browser, its activity is not placed in the same +task as your application. Instead, either a new task starts for the Browser or, if the Browser +already has a task running in the background, that task is brought forward to handle the new +intent.

    + +

    Regardless of whether an activity starts in a new task or in the same task as the activity that +started it, the Back 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.

    + + +

    Figure 4. 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, then the entire back stack also comes +forward, on top of the current task.

    + +

    For more information about using launch modes in the manifest file, see the +<activity> +element documentation, where the {@code launchMode} attribute and the accepted values are +discussed more.

    + +

    Note: The behaviors that you specify for your activity with the {@code launchMode} attribute +can be overridden by flags included with the intent that start your activity, as discussed in the +next section.

    + + + +

    Using Intent flags

    + +

    When starting an activity, you can modify the default association of an activity to its task +by including flags in the intent that you deliver to {@link +android.app.Activity#startActivity startActivity()}. The flags you can use to modify the +default behavior are:

    + +

    +

    {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}
    +
    Start the activity in a new task. If a task is already running for the activity you are now +starting, that task is brought to the foreground with its last state restored and the activity +receives the new intent in {@link android.app.Activity#onNewIntent onNewIntent()}. +

    This produces the same behavior as the {@code "singleTask"} {@code launchMode} value, +discussed in the previous section.

    +
    {@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}
    +
    If the activity being started is the current activity (at the top of the back stack), then +the existing instance receives a call to {@link android.app.Activity#onNewIntent onNewIntent()}, +instead of creating a new instance of the activity. +

    This produces the same behavior as the {@code "singleTop"} {@code launchMode} value, +discussed in the previous section.

    +
    {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}
    +
    If the activity being started is already running in the current task, then instead +of launching a new instance of that activity, all of the other activities on top of it are +destroyed and this intent is delivered to the resumed instance of the activity (now on top), +through {@link android.app.Activity#onNewIntent onNewIntent()}). +

    There is no value for the {@code launchMode} +attribute that produces this behavior.

    +

    {@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction with {@code +FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are a way of locating an existing activity +in another task and putting it in a position where it can respond to the intent.

    +

    Note: If the launch mode of the designated activity is {@code +"standard"}, it too is removed from the stack and a new instance is launched in its place to handle +the incoming intent. That's because a new instance is always created for a new intent when the +launch mode is {@code "standard"}.

    +
    + + + + + + +

    Handling affinities

    + +

    The affinity indicates which task an activity prefers to belong to. By default, all the +activities from the same application have an affinity for each other. So, by default, all +activities in the same application prefer to be in the same task. However, you can modify +the default affinity for an activity. Activities defined in +different applications can share an affinity, or activities defined in the same application can be +assigned different task affinities.

    + +

    You can modify the affinity for any given activity with the {@code taskAffinity} attribute +of the {@code <activity>} +element.

    + +

    The {@code taskAffinity} +attribute takes a string value, which must be unique from the default package name +declared in the {@code +<manifest>} element, because the system uses that name to identify the default task +affinity for the application.

    + +

    The affinity comes into play in two circumstances:

    +
      +
    • When the intent that launches an activity contains the {@link +android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag. + +

      A new activity is, by default, launched into the task of the activity +that called {@link android.app.Activity#startActivity startActivity()}. It's pushed onto the same +back stack as the caller. However, if the intent passed to {@link +android.app.Activity#startActivity startActivity()} contains the {@link +android.content.Intent#FLAG_ACTIVITY_NEW_TASK} +flag, the system looks for a different task to house the new activity. Often, it's a new task. +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.

      + +

      If this flag causes an activity to begin a new task and the user presses the Home 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 +android.app.Activity#startActivity startActivity()}. If you have an activity that can be invoked by +an external entity that might use this flag, take care that the user has a independent way to get +back to the task that's started, such as with a launcher icon (the root activity of the task +has a {@link android.content.Intent#CATEGORY_LAUNCHER} intent filter; see the Starting a task section below).

      +
    • + +
    • When an activity has its {@code +allowTaskReparenting} attribute set to {@code "true"}. +

      In this case, the activity can move from the task it starts to the task it has an affinity +for, when that task comes to the foreground.

      +

      For example, suppose that an activity that reports weather conditions in selected cities is +defined as part of a travel application. It has the same affinity as other activities in the same +application (the default application affinity) and it allows re-parenting with this attribute. +When one of your activities starts the weather reporter activity, it initially belongs to the same +task as your activity. However, when the travel application's task comes to the foreground, the +weather reporter activity is reassigned to that task and displayed within it.

      +
    • +
    + +

    Tip: If an {@code .apk} file contains more than one "application" +from the user's point of view, you probably want to use the {@code taskAffinity} +attribute to assign different affinities to the activities associated with each "application".

    + + + +

    Clearing the back stack

    + +

    If the user leaves a task for a long time, the system clears the task of all activities except +the root activity. When the user returns to the task again, only the root activity is restored. +The system behaves this way, because, after an extended amount of time, users likely have abandoned +what they were doing before and are returning to the task to begin something new.

    + +

    There are some activity attributes that you can use to modify this behavior:

    + +
    +
    alwaysRetainTaskState +
    +
    If this attribute is set to {@code "true"} in the root activity of a task, +the default behavior just described does not happen. +The task retains all activities in its stack even after a long period.
    + +
    clearTaskOnLaunch
    +
    If this attribute is set to {@code "true"} in the root activity of a task, +the stack is cleared down to the root activity whenever the user leaves the task +and returns to it. In other words, it's the opposite of {@code +alwaysRetainTaskState}. The user always returns to the task in its +initial state, even after a leaving the task for only a moment.
    + +
    finishOnTaskLaunch +
    +
    This attribute is like {@code clearTaskOnLaunch}, +but it operates on a +single activity, not an entire task. It can also cause any activity to go +away, including the root activity. When it's set to {@code "true"}, the +activity remains part of the task only for the current session. If the user +leaves and then returns to the task, it is no longer present.
    +
    + + + + +

    Starting a task

    + +

    You can set up an activity as the entry point for a task by giving it an intent filter with +{@code "android.intent.action.MAIN"} as the specified action and {@code +"android.intent.category.LAUNCHER"} as the specified category. For example:

    + +
    +<activity ... >
    +    <intent-filter ... >
    +        <action android:name="android.intent.action.MAIN" />
    +        <category android:name="android.intent.category.LAUNCHER" />
    +    </intent-filter>
    +    ...
    +</activity>
    +
    + +

    An intent filter of this kind causes an icon and label for the +activity to be displayed in the application launcher, giving users a way to launch the activity and +to return to the task that it creates any time after it has been launched. +

    + +

    This second ability is important: Users must be able to leave a task and then come back to it +later using this activity launcher. For this reason, the two launch +modes that mark activities as always initiating a task, {@code "singleTask"} and "{@code +"singleInstance"}, should be used only when the activity has an {@link +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 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. +

    + +

    For those cases where you don't want the user to be able to return to an activity, set the + <activity> element's +{@code +finishOnTaskLaunch} to {@code "true"} (see Clearing the stack).

    + + + + diff --git a/docs/html/guide/developing/building/building-cmdline.jd b/docs/html/guide/developing/building/building-cmdline.jd deleted file mode 100644 index fd90b1a5a7f1..000000000000 --- a/docs/html/guide/developing/building/building-cmdline.jd +++ /dev/null @@ -1,371 +0,0 @@ -page.title=Building and Running from the Command Line -parent.title=Building and Running -parent.link=index.html -@jd:body - - - -

    There are two ways to build your application using the Ant build script: one for - testing/debugging your application — debug mode — and one for building your - final package for release — release mode. Regardless of which way you build your application, - it must be signed before it can install on an emulator or device—with a debug key when building - in debug mode and with your own private key when building in release mode.

    - -

    Whether you're building in debug mode or release mode, you need to use the Ant tool to compile - and build your project. This will create the .apk file that you can install on an emulator or device. - When you build in debug mode, the .apk file is automatically signed by the SDK tools with - a debug key, so it's instantly ready for installation onto an emulator or attached - development device. You cannot distribute an application that is signed with a debug key. - When you build in release mode, the .apk file is unsigned, so you - must manually sign it with your own private key, using Keytool and Jarsigner.

    - -

    It's important that you read and understand Signing Your Applications, particularly once - you're ready to release your application and share it with end-users. That document describes the - procedure for generating a private key and then using it to sign your .apk file. If you're just - getting started, however, you can quickly run your applications on an emulator or your own - development device by building in debug mode.

    - -

    If you don't have Ant, you can obtain it from the Apache Ant - home page. Install it and make sure it is in your executable PATH. Before calling Ant, you - need to declare the JAVA_HOME environment variable to specify the path to where the JDK is - installed.

    - -

    Note: When installing JDK on Windows, the default is to install - in the "Program Files" directory. This location will cause ant to fail, because of - the space. To fix the problem, you can specify the JAVA_HOME variable like this: -

    set JAVA_HOME=c:\Progra~1\Java\<jdkdir>
    - -

    The easiest solution, however, is to install JDK in a non-space directory, for example:

    - -
    c:\java\jdk1.6.0_02
    - -

    Building in Debug Mode

    - -

    For immediate application testing and debugging, you can build your application in debug mode - and immediately install it on an emulator. In debug mode, the build tools automatically sign your - application with a debug key and optimize the package with {@code zipalign}.

    - -

    To build in debug mode:

    - -
      -
    1. Open a command-line and navigate to the root of your project directory.
    2. -
    3. Use Ant to compile your project in debug mode: -
      -ant debug
      -
      - -

      This creates your debug .apk file inside the project bin/ directory, named - <your_project_name>-debug.apk. The file is already signed with - the debug key and has been aligned with - zipalign. -

      -
    4. -
    - -

    Each time you change a source file or resource, you must run Ant again in order to package up - the latest version of the application.

    - -

    To install and run your application on an emulator, see the following section about Running on the Emulator.

    - -

    Building in Release Mode

    - -

    When you're ready to release and distribute your application to end-users, you must build your - application in release mode. Once you have built in release mode, it's a good idea to perform - additional testing and debugging with the final .apk.

    - -

    Before you start building your application in release mode, be aware that you must sign the - resulting application package with your private key, and should then align it using the {@code - zipalign} tool. There are two approaches to building in release mode: build an unsigned package - in release mode and then manually sign and align the package, or allow the build script to sign - and align the package for you.

    - -

    Build unsigned

    - -

    If you build your application unsigned, then you will need to manually sign and align - the package.

    - -

    To build an unsigned .apk in release mode:

    - -
      -
    1. Open a command-line and navigate to the root of your project directory.
    2. - -
    3. Use Ant to compile your project in release mode: -
      -ant release
      -
      -
    4. -
    - -

    This creates your Android application .apk file inside the project bin/ - directory, named <your_project_name>-unsigned.apk.

    - -

    Note: The .apk file is unsigned at this point and can't - be installed until signed with your private key.

    - -

    Once you have created the unsigned .apk, your next step is to sign the .apk with your private - key and then align it with {@code zipalign}. To complete this procedure, read Signing Your Applications.

    - -

    When your .apk has been signed and aligned, it's ready to be distributed to end-users. - You should test the final build on different devices or AVDs to ensure that it - runs properly on different platforms.

    - -

    Build signed and aligned

    - -

    If you would like, you can configure the Android build script to automatically sign and align - your application package. To do so, you must provide the path to your keystore and the name of - your key alias in your project's {@code ant.properties} file. With this information provided, - the build script will prompt you for your keystore and alias password when you build in release - mode and produce your final application package, which will be ready for distribution.

    - -

    Caution: Due to the way Ant handles input, the password that - you enter during the build process will be visible. If you are concerned about - your keystore and alias password being visible on screen, then you may prefer to perform the - application signing manually, via Jarsigner (or a similar tool). To instead perform the signing - procedure manually, build unsigned and then continue with - Signing Your Applications.

    - -

    To specify your keystore and alias, open the project {@code ant.properties} file (found in - the root of the project directory) and add entries for {@code key.store} and {@code key.alias}. - For example:

    -
    -key.store=path/to/my.keystore
    -key.alias=mykeystore
    -
    - -

    Save your changes. Now you can build a signed .apk in release mode:

    - -
      -
    1. Open a command-line and navigate to the root of your project directory.
    2. - -
    3. Use Ant to compile your project in release mode: -
      -ant release
      -
      -
    4. - -
    5. When prompted, enter you keystore and alias passwords. - -

      Caution: As described above, your password will be - visible on the screen.

      -
    6. -
    - -

    This creates your Android application .apk file inside the project bin/ - directory, named <your_project_name>-release.apk. This .apk file has - been signed with the private key specified in {@code ant.properties} and aligned with {@code - zipalign}. It's ready for installation and distribution.

    - -

    Once built and signed in release mode

    - -

    Once you have signed your application with a private key, you can install and run it on an - emulator or device. You can - also try installing it onto a device from a web server. Simply upload the signed .apk to a web - site, then load the .apk URL in your Android web browser to download the application and begin - installation. (On your device, be sure you have enabled - Settings > Applications > Unknown sources.)

    - -

    Running on the Emulator

    - -

    Before you can run your application on the Android Emulator, you must create an AVD.

    - -

    To run your application:

    - -
      -
    1. - Open the AVD Manager and launch a virtual device - -

      From your SDK's platform-tools/ directory, execute the {@code android} tool -with the avd options:

      -
      -android avd
      -
      - -

      In the Virtual Devices view, select an AVD and click Start.

      -
    2. - -
    3. - Install your application - -

      From your SDK's tools/ directory, install the {@code .apk} on the - emulator:

      -
      -adb install <path_to_your_bin>.apk
      -
      - -

      Your .apk file (signed with either a release or debug key) is in your project {@code bin/} - directory after you build your application.

      - -

      If there is more than one emulator running, you must specify the emulator upon which to - install the application, by its serial number, with the -s option. For - example:

      -
      -adb -s emulator-5554 install path/to/your/app.apk
      -
      - -

      To see a list of available device serial numbers, execute {@code adb devices}.

      -
    4. -
    - -

    If you don't see your application on the emulator, try closing the emulator and launching the - virtual device again from the AVD Manager. Sometimes when you install an application for the - first time, it won't show up in the application launcher or be accessible by other applications. - This is because the package manager usually examines manifests completely only on emulator - startup.

    - -

    Be certain to create multiple AVDs upon which to test your application. You should have one - AVD for each platform and screen type with which your application is compatible. For instance, if - your application compiles against the Android 1.5 (API Level 3) platform, you should create an - AVD for each platform equal to and greater than 1.5 and an AVD for each screen type you support, then test your - application on each one.

    - -

    Tip: If you have only one emulator running, you can - build your application and install it on the emulator in one simple step. Navigate to the root of - your project directory and use Ant to compile the project with install mode: ant - install. This will build your application, sign it with the debug key, and install it on - the currently running emulator.

    - -

    Running on a Device

    - -

    Before you can run your application on a device, you must perform some basic setup for your - device:

    - -
      -
    • Enable USB Debugging on your device. You can find the setting on most Android devices by - going to Settings > Applications > Development > USB debugging.
    • - -
    • Ensure that your development computer can detect your device when connected via USB
    • -
    - -

    Read Setting up a Device for - Development for more information.

    - -

    Once your device is set up and connected via USB, navigate to your SDK's platform-tools/ - directory and install the .apk on the device:

    -
    -adb -d install path/to/your/app.apk
    -
    - -

    The {@code -d} flag specifies that you want to use the attached device (in case you also have - an emulator running).

    - -

    For more information on the tools used above, please see the following documents:

    - - - -

    Application Signing

    - -

    As you begin developing Android applications, understand that all Android applications must be - digitally signed before the system will install them on an emulator or device. There are two ways - to do this: with a debug key (for immediate testing on an emulator or development - device) or with a private key (for application distribution).

    - -

    The Android build tools help you get started by automatically signing your .apk files with a - debug key at build time. This means that you can compile your application and install it on the - emulator without having to generate your own private key. However, please note that if you intend - to publish your application, you must sign the application with your own private - key, rather than the debug key generated by the SDK tools.

    - -

    The ADT plugin helps you get started quickly by signing your .apk files with a debug key, - prior to installing them on an emulator or development device. This means that you can quickly - run your application from Eclipse without having to generate your own private key. No specific - action on your part is needed, provided ADT has access to Keytool. However, please note that if - you intend to publish your application, you must sign the application with your - own private key, rather than the debug key generated by the SDK tools.

    - -

    Please read Signing Your - Applications, which provides a thorough guide to application signing on Android and what it - means to you as an Android application developer. The document also includes a guide to exporting - and signing your application with the ADT's Export Wizard.

    - -

    Ant Command Reference

    -
    ant clean
    -
    Cleans the project. If you include the all target before clean -(ant all clean), other projects are also cleaned. For instance if you clean a -test project, the tested project is also cleaned.
    - -
    ant debug
    -
    Builds a debug package. Works on application, library, and test projects and compiles - dependencies as needed.
    - -
    ant emma debug
    -
    Builds a test project while building the tested project with instrumentation turned on. - This is used to run tests with code coverage enabled.
    - -
    ant release
    -
    Builds a release package.
    - -
    ant instrument -
    -
    Builds an instrumented debug package. This is generally called automatically when building a - test project with code coverage enabled (with the emma - target)
    - -
    ant <build_target> install
    -
    Builds and installs a package. Using install by itself fails.
    - -
    ant installd
    -
    Installs an already compiled debug package. This fails if the .apk is not - already built.
    - -
    ant installr
    -
    Installs an already compiled release package. This fails if the .apk is not - already built.
    - -
    ant installt
    -
    Installs an already compiled test package. Also installs the .apk of the - tested application. This fails if the .apk is not already built.
    - -
    ant installi
    -
    Installs an already compiled instrumented package. This is generally not used manually as - it's called when installing a test package. This fails if the .apk is not already - built.
    - -
    ant test
    -
    Runs the tests (for test projects). The tested and test .apk files must be - previously installed.
    - -
    ant debug installt test
    -
    Builds a test project and the tested project, installs both .apk files, and - runs the tests.
    - -
    ant emma debug install test
    -
    Builds a test project and the tested project, installs both .apk files, and - runs the tests with code coverage enabled.
    - diff --git a/docs/html/guide/developing/building/building-eclipse.jd b/docs/html/guide/developing/building/building-eclipse.jd deleted file mode 100644 index 6ebc49ef57e3..000000000000 --- a/docs/html/guide/developing/building/building-eclipse.jd +++ /dev/null @@ -1,165 +0,0 @@ -page.title=Building and Running from Eclipse with ADT -parent.title=Building and Running -parent.link=index.html -@jd:body - - - -

    Eclipse and ADT provide an environment where most of the details of the build process are - hidden from you. By default, the build process constantly runs in the background as you make - changes to your project.

    - -

    When Eclipse automatically builds your application, it enables debugging and signs the - .apk with a debug key, by default. When you run the application, - Eclipse invokes ADB and installs your application to a device or emulator, so you do not have to - manually perform these tasks. Since most of the build process is taken care of by Eclipse, the - following topics show you how to run an application, which will automatically build your - application as well.

    - -

    To distribute your application, however, you must build your application in release mode and sign the - .apk file with your own private key.

    - -

    This document shows you how to run your application on an emulator or a real device - from Eclipse—all of which is done using the debug version of your application. - For more information about how to sign your application with a private key for release, see Signing Your Applications

    - -

    Running on the emulator

    - -

    Before you can run your application on the Android Emulator, you must create an AVD.

    - -

    To run (or debug) your application, select Run > Run (or - Run > Debug) from the Eclipse menu bar. The ADT plugin will - automatically create a default run configuration for the project. Eclipse will then perform the - following:

    - -
      -
    1. Compile the project (if there have been changes since the last build).
    2. - -
    3. Create a default run configuration (if one does not already exist for the project).
    4. - -
    5. Install and start the application on an emulator (or device), based on the Deployment - Target defined by the run configuration. - -

      By default, Android run configurations use an "automatic target" mode for selecting a - device target. For information on how automatic target mode selects a deployment target, see - Automatic and manual target modes below.

      -
    6. -
    - -

    If you run the application with the Debug option, the application will start in the "Waiting For Debugger" mode. Once the debugger - is attached, Eclipse opens the Debug perspective and starts the application's main activity. Otherwise, if you run the - application with the normal Run option, Eclipse installs the application on the device and launches the main activity.

    - -

    To set or change the run configuration used for your project, use the run configuration - manager. See the section below about Creating a Run Configuration for more information.

    - -

    Be certain to create multiple AVDs upon which to test your application. You should have one - AVD for each platform and screen type with which your application is compatible. For instance, if - your application compiles against the Android 1.5 (API Level 3) platform, you should create an - AVD for each platform equal to and greater than 1.5 and an AVD for each screen type you support, then test your - application on each one.

    - -

    Running on a device

    - -

    Before you can run your application on a device, you must perform some basic setup for your - device:

    - -
      -
    • Ensure that your application is debuggable by setting the - android:debuggable attribute of the <application> - element to true. As of ADT 8.0, this is done by default when you build in debug mode.
    • - -
    • Enable USB Debugging on your device. You can find the setting on most Android devices by - going to Settings > Applications > Development > USB debugging.
    • - -
    • Ensure that your development computer can detect your device when connected via USB
    • -
    - -

    Read Using Hardware Devices - for more information.

    - -

    Once set up and your device is connected via USB, install your application on the device by - selecting Run > Run (or Run > - Debug) from the Eclipse menu bar.

    - -

    Creating a Run Configuration

    - -

    The run configuration specifies the project to run, the Activity to start, the emulator or - connected device to use, and so on. When you first run a project as an Android - Application, ADT will automatically create a run configuration. The default run - configuration will launch the default project Activity and use automatic target mode for device - selection (with no preferred AVD). If the default settings don't suit your project, you can - customize the run configuration or even create a new one.

    - -

    To create or modify a run configuration, refer to the Eclipse documentation on how to create Run configurations. - The following steps highlight the important things you need to do for an Android project:

    - -
      -
    1. Open the run configuration manager from the Run Menu.
    2. - -
    3. Expand the Android Application item and create a new configuration or open - an existing one. -
    4. - -
    5. With the Run Configuration selected, adjust your desired run configuration settings: -
        -
      • In the Android tab, specify the Project and Activity to launch. -
      • -
      • In the Target tab, consider whether you'd like to use Manual or Automatic mode when - selecting an AVD to run your application. See the following section on Automatic and manual target modes).

        - -

        You can specify any emulator options to the Additional Emulator Command Line Options - field. For example, you could add -scale 96dpi to scale the AVD's screen to an - accurate size, based on the dpi of your computer monitor. For a full list of emulator - options, see the Android - Emulator document.

        -
      • -
      -
    6. -
    - -

    Automatic and manual target modes

    - -

    By default, a run configuration uses the automatic target mode in order to - select an AVD. In this mode, ADT will select an AVD for the application in the following - manner:

    - -
      -
    1. If there's a device or emulator already running and its AVD configuration meets the - requirements of the application's build target, the application is installed and run upon - it.
    2. - -
    3. If there's more than one device or emulator running, each of which meets the requirements - of the build target, a "device chooser" is shown to let you select which device to use.
    4. - -
    5. If there are no devices or emulators running that meet the requirements of the build - target, ADT looks at the available AVDs. If there is an AVD that matches the build target of the project, - ADT chooses that AVD. If the AVD versions are newer than the build target of the project, ADT chooses - the oldest possible version of an AVD that meets the project's build target requirement.
    6. - -
    7. If there are no suitable AVDs, the application is not installed a console error warning tells - you that there is no existing AVD that meets the build target requirements.
    8. -
    - -

    However, if a "preferred AVD" is selected in the run configuration, then the application will - always be deployed to that AVD. If it's not already running, then a new emulator will be - launched.

    - -

    If your run configuration uses manual mode, then the "device chooser" is - presented every time that your application is run, so that you can select which AVD to use.

    \ No newline at end of file diff --git a/docs/html/guide/developing/building/index.jd b/docs/html/guide/developing/building/index.jd deleted file mode 100644 index 569cd28387b8..000000000000 --- a/docs/html/guide/developing/building/index.jd +++ /dev/null @@ -1,81 +0,0 @@ -page.title=Building and Running -@jd:body - -
    -
    -

    In this document

    -
      -
    1. A Detailed Look at the Build Process
    2. -
    -
    -
    - -

    During the build process, your Android projects are compiled and packaged into an .apk file, - the container for your application binary. It contains all of the information necessary to run - your application on a device or emulator, such as compiled .dex files (.class files - converted to Dalvik byte code), a binary version of the AndroidManifest.xml file, compiled - resources (resources.arsc) and uncompiled resource files for your application.

    - -

    If you are developing in Eclipse, the ADT plugin incrementally builds your project as you - make changes to the source code. Eclipse outputs an .apk file automatically to the bin folder of - the project, so you do not have to do anything extra to generate the .apk.

    - -

    If you are developing in a non-Eclipse environment, you can build your project with the - generated build.xml Ant file that is in the project directory. The Ant file calls targets that - automatically call the build tools for you.

    - -

    To run an application on an emulator or device, the application must be signed using debug or - release mode. You typically want to sign your application in debug mode when you develop and test - your application, because the build tools use a debug key with a known password so you do not have - to enter it every time you build. When you are ready to release the application to Google - Play, you must sign the application in release mode, using your own private key.

    - -

    Fortunately, Eclipse or your Ant build script signs the application for you in debug mode - when you build your application. You can also easily setup Eclipse or your Ant build to sign your - application in release mode as well. For more information on signing applications, see Signing Your Applications.

    - -

    The following diagram depicts the components involved in building and running an application:

    - - - -

    A Detailed Look at the Build Process

    - -

    The build process involves many tools and processes that generate intermediate files on the - way to producing an .apk. If you are developing in Eclipse, the complete build process is - automatically done periodically as you develop and save your code changes. If you are using other - IDEs, this build process is done every time you run the generated Ant build script for your - project. It is useful, however, to understand what is happening under the hood since much of the - tools and processes are masked from you. The following diagram depicts the different tools and - processes that are involved in a build:

    - - - -

    The general process for a typical build is outlined below:

    - -
      - -
    • The Android Asset Packaging Tool (aapt) takes your application resource files, such as the - AndroidManifest.xml file and the XML files for your Activities, and compiles them. An R.java is - also produced so you can reference your resources from your Java code.
    • - -
    • The aidl tool converts any .aidl interfaces that you have into Java interfaces.
    • - -
    • All of your Java code, including the R.java and .aidl files, are compiled by the Java - compiler and .class files are output.
    • - -
    • The dex tool converts the .class files to Dalvik byte code. Any 3rd party libraries and - .class files that you have included in your project are also converted into .dex files so that - they can be packaged into the final .apk file.
    • - -
    • All non-compiled resources (such as images), compiled resources, and the .dex files are - sent to the apkbuilder tool to be packaged into an .apk file.
    • - -
    • Once the .apk is built, it must be signed with either a debug or release key before it can - be installed to a device.
    • - -
    • Finally, if the application is being signed in release mode, you must align the .apk with - the zipalign tool. Aligning the final .apk decreases memory usage when the application is - running on a device.
    • -
    - diff --git a/docs/html/guide/developing/debug-tasks.html b/docs/html/guide/developing/debug-tasks.html deleted file mode 100644 index 4e738041a315..000000000000 --- a/docs/html/guide/developing/debug-tasks.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/developing/debugging/ddms.jd b/docs/html/guide/developing/debugging/ddms.jd deleted file mode 100644 index 9892e49f1eec..000000000000 --- a/docs/html/guide/developing/debugging/ddms.jd +++ /dev/null @@ -1,357 +0,0 @@ -page.title=Using DDMS -parent.title=Debugging -parent.link=index.html -@jd:body - - - -

    Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which - provides port-forwarding services, screen capture on the device, thread and heap information on - the device, logcat, process, and radio state information, incoming call and SMS spoofing, - location data spoofing, and more. This page provides a modest discussion of DDMS features; it is - not an exhaustive exploration of all the features and capabilities.

    - -

    Running DDMS

    -

    DDMS is integrated into Eclipse and is also shipped in the tools/ directory of the - SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, - DDMS defaults to the emulator.

    - -
      -
    • From Eclipse: Click Window > Open Perspective > Other... > DDMS.
    • -
    • From the command line: Type ddms (or ./ddms on Mac/Linux) from the tools/ - directory.
    • -
    - - -

    How DDMS Interacts with a Debugger

    - -

    On Android, every application runs in its own process, each of which runs in its own virtual machine - (VM). Each VM exposes a unique port that a debugger can attach to.

    - -

    When DDMS starts, it connects to adb. - When a device is connected, a VM monitoring service is created between - adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM - is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a connection to the - VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a - custom wire protocol.

    - -

    DDMS assigns a debugging port to each VM on the device. Typically, - DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger - connects to one of these ports, all traffic is forwarded to the debugger from the associated - VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached - debuggers.

    - -

    By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by default). - The base port is a port forwarder, which can accept VM traffic from any debugging port and forward - it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug - all the VMs on a device. The traffic that is forwarded is determined by the currently selected process - in the DDMS Devices view.

    - -

    The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS from - the command line, the screen is slightly different, but much of the functionality is identical. - Notice that the highlighted process, com.android.email, that is running in the emulator - has the debugging port 8700 assigned to it as well as 8606. This signifies that DDMS is currently - forwarding port 8606 to the static debugging port of 8700.

    - - -

    Figure 1. - Screenshot of DDMS

    - -

    If you are not using Eclipse and ADT, read Configuring - your IDE to attach to the debugging port, for more information on attaching your - debugger.

    - -

    Tip: You can set a number of DDMS preferences in - File > Preferences. Preferences are saved to - $HOME/.android/ddms.cfg.

    - -

    Known debugging issues with Dalvik
    - Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, - when single-stepping out of synchronized code, the "current line" cursor may jump to the last - line in the method for one step.

    - -

    Using DDMS

    - The following sections describe how to use DDMS and the various tabs and panes that are part of the - DDMS GUI. The Eclipse version and the command line version have minor UI differences, but the - same functionality. For information on running DDMS, see the previous section in this document, - Running DDMS. - - -

    Viewing heap usage for a process

    - -

    DDMS allows you to view how much heap memory a process is using. This information is useful in - tracking heap usage at a certain point of time during the execution of your application.

    -

    To view heap usage for a process:

    -
      -
    1. In the Devices tab, select the process that you want to see the heap information for.
    2. - -
    3. Click the Update Heap button to enable heap information for the - process.
    4. - -
    5. In the Heap tab, click Cause GC to invoke garbage collection, which - enables the collection of heap data. When the operation completes, you will see a group of - object types and the memory that has been allocated for each type. You can click Cause - GC again to refresh the data.
    6. - -
    7. Click on an object type in the list to see a bar graph that shows the number of objects - allocated for a particular memory size in bytes.
    8. -
    - -

    Tracking memory allocation of objects

    - -

    DDMS provides a feature to track objects that are being allocated to memory and to see which - classes and threads are allocating the objects. This allows you to track, in real time, where - objects are being allocated when you perform certain actions in your application. This - information is valuable for assessing memory usage that can affect application performance. -

    - -

    To track memory allocation of objects:

    -
      -
    1. In the Devices tab, select the process that you want to enable allocation tracking - for.
    2. - -
    3. In the Allocation Tracker tab, click the Start Tracking button to begin - allocation tracking. At this point, anything you do in your application will be tracked.
    4. - -
    5. Click Get Allocations to see a list of objects that have been allocated - since you clicked on the Start Tracking button. You can click on Get - Allocations again to append to the list new objects that that have been - allocated.
    6. - -
    7. To stop tracking or to clear the data and start over, click the Stop Tracking - button.
    8. - -
    9. Click on a specific row in the list to see more detailed information such as the method and - line number of the code that allocated the object.
    10. -
    - -

    Working with an emulator or device's file system

    - -

    DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the - device. This feature is useful in examining files that are created by your application or if you - want to transfer files to and from the device.

    - -

    To work with an emulator or device's file system:

    -
      -
    1. In the Devices tab, select the emulator that you want to view the file system for.
    2. - -
    3. To copy a file from the device, locate the file in the File Explorer and click the - Pull file button.
    4. - -
    5. To copy a file to the device, click the Push file button on the File - Explorer tab.
    6. -
    - - - -

    Examining thread information

    - -

    The Threads tab in DDMS shows you the currently running threads for a selected process.

    - -
      -
    1. In the Devices tab, select the process that you want to examine the threads for.
    2. - -
    3. Click the Update Threads button.
    4. - -
    5. In the Threads tab, you can view the thread information for the selected process.
    6. -
    - -

    Starting method profiling

    - -

    Method profiling is a means to track certain metrics about a method, such as number of calls, - execution time, and time spent executing the method. If you want more granular control over - where profiling data is collected, use the {@link android.os.Debug#startMethodTracing()} and - {@link android.os.Debug#stopMethodTracing()} methods. For more information about generating trace logs, see - Profiling and Debugging UIs.

    - -

    Before you start method profiling in DDMS, be aware of the following restrictions:

    -
      -
    • Android 1.5 devices are not supported.
    • -
    • Android 2.1 and earlier devices must - have an SD card present and your application must have permission to write to the SD card. -
    • Android 2.2 and later devices do not need an SD card. The trace log files are - streamed directly to your development machine.
    • -
    - -

    To start method profiling:

    -
      -
    1. On the Devices tab, select the process that you want to enable method profiling for.
    2. - -
    3. Click the Start Method Profiling button.
    4. - -
    5. Interact with your application to start the methods that you want to profile.
    6. - -
    7. Click the Stop Method Profiling button. DDMS stops profiling your - application and opens Traceview - with the method profiling information that was collected - between the time you clicked on Start Method Profiling and Stop Method - Profiling.
    8. -
    - -

    Using the Network Traffic tool

    - -

    In Android 4.0, the DDMS (Dalvik Debug Monitor Server) includes a Detailed -Network Usage tab that makes it possible to track when your application is -making network requests. Using this tool, you can monitor how and when your app -transfers data and optimize the underlying code appropriately. You can also -distinguish between different traffic types by applying a “tag” to network -sockets before use.

    - -

    These tags are shown in a stack area chart in DDMS, as shown in figure 2:

    - - -

    Figure 2. Network Usage tab.

    - -

    By monitoring the frequency of your data transfers, and the amount of data -transferred during each connection, you can identify areas of your application -that can be made more battery-efficient. Generally, you should look for -short spikes that can be delayed, or that should cause a later transfer to be -pre-empted.

    - -

    To better identify the cause of transfer spikes, the -{@link android.net.TrafficStats} API allows you -to tag the data transfers occurring within a thread using {@link -android.net.TrafficStats#setThreadStatsTag setThreadStatsTag()}, followed -by manually tagging (and untagging) individual sockets using {@link -android.net.TrafficStats#tagSocket tagSocket()} and {@link -android.net.TrafficStats#untagSocket untagSocket()}. For example:

    - -
    TrafficStats.setThreadStatsTag(0xF00D);
    -TrafficStats.tagSocket(outputSocket);
    -// Transfer data using socket
    -TrafficStats.untagSocket(outputSocket);
    - -

    Alternatively, the Apache {@link org.apache.http.client.HttpClient} and -{@link java.net.URLConnection} APIs included in the platform -automatically tag sockets internally based on the active tag (as -identified by -{@link android.net.TrafficStats#getThreadStatsTag getThreadStatsTag()}). -These APIs correctly tag/untag sockets when recycled through -keep-alive pools. In the following example, -{@link android.net.TrafficStats#setThreadStatsTag setThreadStatsTag()} -sets the active tag to be {@code 0xF00D}. -There can only be one active tag per thread. -That is the value that will -be returned by {@link android.net.TrafficStats#getThreadStatsTag getThreadStatsTag()} -and thus used by {@link org.apache.http.client.HttpClient} - to tag sockets. The {@code finally} statement -invokes -{@link android.net.TrafficStats#clearThreadStatsTag clearThreadStatsTag()} -to clear the tag.

    - -
    TrafficStats.setThreadStatsTag(0xF00D);
    -    try {
    -        // Make network request using HttpClient.execute()
    -    } finally {
    -        TrafficStats.clearThreadStatsTag();
    -}
    - -

    Socket tagging is supported in Android 4.0, but real-time stats will only be -displayed on devices running Android 4.0.3 or higher.

    - -

    Using LogCat

    - -

    LogCat is integrated into DDMS, and outputs the messages that you print out using the {@link android.util.Log} - class along with other system messages such as stack traces when exceptions are thrown. View the - Reading and - Writing Log Messages. topic for more information on how to log messages to the LogCat.

    - -

    When you have set up your logging, you can use the LogCat feature of DDMS to filter certain - messages with the following buttons:

    - -
      -
    • Verbose
    • - -
    • Debug
    • - -
    • Info
    • - -
    • Warn
    • - -
    • Error
    • -
    - -

    You can also setup your own custom filter to specify more details such as filtering messages - with the log tags or with the process id that generated the log message. The add filter, - edit filter, and delete filter buttons let you manage your custom filters.

    - -

    Emulating phone operations and location

    -

    The Emulator control tab lets you simulate a - phone's voice and data network status. This is useful when you want to test your application's - robustness in differing network environments.

    - -

    Changing network state, speed, and latency

    -

    The Telephony Status section of the Emulator - controls tab lets you change different aspects of the phone's networks status, speed and latency. - The following options are available to you and are effective immediately after you set them:

    - -
      -
    • Voice - unregistered, home, roaming, searching, denied
    • - -
    • Data - unregistered, home, roaming, searching, denied
    • - -
    • Speed - Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPA
    • - -
    • Latency - GPRS, EDGE, UMTS
    • -
    - -

    Spoofing calls or SMS text messages

    -

    The Telephony Actions section of the Emulator - controls tab lets you spoof calls and messages. This is useful when you want to to test your - application's robustness in responding to incoming calls and messages that are sent to the phone. - The following actions are available to you:

    - -
      -
    • Voice - Enter a number in the Incoming number field and click - Call to send a simulated call to the emulator or phone. Click the - Hang up button to terminate the call.
    • - -
    • SMS - Enter a number in the Incoming number field and a message in the - Message: field and click the Send button to send the - message.
    • -
    - -

    Setting the location of the phone

    -

    If your application depends on the location of the phone, you can have DDMS send your - device or AVD a mock location. This is useful if you - want to test different aspects of your application's location specific features without - physically moving. The following geolocation data types are available to you:

    - -
      -
    • Manual - set the location by manually specifying decimal or sexagesimal longitude and - latitude values.
    • - -
    • GPX - GPS eXchange file
    • - -
    • KML - Keyhole Markup Language file
    • -
    - - For more information about providing mock location data, see - Obtaining User Location. - diff --git a/docs/html/guide/developing/debugging/debugging-devtools.jd b/docs/html/guide/developing/debugging/debugging-devtools.jd deleted file mode 100644 index 157d62e6c2d9..000000000000 --- a/docs/html/guide/developing/debugging/debugging-devtools.jd +++ /dev/null @@ -1,85 +0,0 @@ -page.title=Using the Dev Tools App -parent.title=Debugging -parent.link=index.html -@jd:body - -

    The Dev Tools application is installed by default on all system images included with the SDK, - so you can use it with the Android Emulator. With the Dev Tools application, you can enable a - number of settings on your device that will make it easier to test and debug your applications.

    - -

    If you'd like to install the Dev Tools application - on a real development device, you can copy the application from your emulator and then install it - on your device using ADB. To copy the application from a running emulator, execute:

    -
    -adb -e pull /system/app/Development.apk ./Development.apk
    -
    - -

    This copies the .apk file into the current directory. Then install it on your connected device - with:

    -
    -adb -d install Development.apk
    -
    - -

    To get started, launch the Dev Tools application and select Development Settings. This will - open the Development Settings page with the following options (among others):

    - -
    -
    Debug app
    - -
    - Lets you select the application to debug. You do not need to set this to attach a debugger, - but setting this value has two effects: - -
      -
    • It will prevent Android from throwing an error if you pause on a breakpoint for a long - time while debugging.
    • - -
    • It will enable you to select the Wait for Debugger option to pause application - startup until your debugger attaches (described next).
    • -
    -
    - -
    Wait for debugger
    - -
    Blocks the selected application from loading until a debugger attaches. This way you can - set a breakpoint in {@link android.app.Activity#onCreate onCreate()}, - which is important to debug the startup process of an Activity. - When you change this option, any currently running instances of the selected application will - be killed. In order to check this box, you must have selected a debug application as described - in the previous option. You can do the same thing by adding {@link - android.os.Debug#waitForDebugger()} to your code.
    - -
    Show screen updates
    - -
    Flashes a momentary pink rectangle on any screen sections that are being redrawn. This is - very useful for discovering unnecessary screen drawing.
    - -
    Immediately destroy activities
    - -
    Tells the system to destroy an activity as soon as it is stopped (as if Android had to - reclaim memory).  This is very useful for testing the {@link - android.app.Activity#onSaveInstanceState} / {@link - android.app.Activity#onCreate(android.os.Bundle)} code path, which would otherwise be difficult - to force. Choosing this option will probably reveal a number of problems in your application - due to not saving state. For more information about saving an activity's state, see the - Activities -document.
    - -
    Show CPU usage
    - -
    Displays CPU meters at the top of the screen, showing how much the CPU is being used. The - top red bar shows overall CPU usage, and the green bar underneath it shows the CPU time spent - in compositing the screen. -

    Note: You cannot turn this feature off once it is on, without - restarting the emulator.

    - -
    Show background
    - -
    Displays a background pattern when no activity screens are visible. This typically does not - happen, but can happen during debugging.
    -
    - -

    These settings will be remembered across emulator restarts.

    - - - diff --git a/docs/html/guide/developing/debugging/debugging-log.jd b/docs/html/guide/developing/debugging/debugging-log.jd deleted file mode 100644 index b5b626e9bf3a..000000000000 --- a/docs/html/guide/developing/debugging/debugging-log.jd +++ /dev/null @@ -1,308 +0,0 @@ -page.title=Reading and Writing Logs -parent.title=Debugging -parent.link=index.html -@jd:body - - - -

    The Android logging system provides a mechanism for collecting and viewing system debug - output. Logcat dumps a log of system messages, which include things such as stack traces when the - emulator throws an error and messages that you have written from your application by using the - {@link android.util.Log} class. You can run LogCat through ADB or from DDMS, which allows you to - read the messages in real time.

    - -

    The Log class

    - -

    {@link android.util.Log} is a logging class that you can utilize in your code to print out - messages to the LogCat. Common logging methods include:

    - -
      -
    • {@link android.util.Log#v(String,String)} (verbose)
    • - -
    • {@link android.util.Log#d(String,String)} (debug)
    • - -
    • {@link android.util.Log#i(String,String)} (information)
    • - -
    • {@link android.util.Log#w(String,String)} (warning)
    • - -
    • {@link android.util.Log#e(String,String)} (error)
    • -
    For example: -
    -Log.i("MyActivity", "MyClass.getView() — get item number " + position);
    -
    - -

    The LogCat will then output something like:

    -
    -I/MyActivity( 1557): MyClass.getView() — get item number 1
    -
    - -

    Using LogCat

    - -

    You can use LogCat from within DDMS or call it on an ADB shell. For more information on how to - use LogCat within DDMS, see Using - DDMS. To run LogCat, through the ADB shell, the general usage is:

    -
    -[adb] logcat [<option>] ... [<filter-spec>] ...
    -
    - -

    You can use the logcat command from your development computer or from a remote - adb shell in an emulator/device instance. To view log output in your development computer, you - use

    -
    -$ adb logcat
    -
    - -

    and from a remote adb shell you use

    -
    -# logcat
    -
    - -

    The following table describes the logcat command line options:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -cClears (flushes) the entire log and exits.
    -dDumps the log to the screen and exits.
    -f <filename>Writes log message output to <filename>. The default is - stdout.
    -gPrints the size of the specified log buffer and exits.
    -n <count>Sets the maximum number of rotated logs to <count>. The default value - is 4. Requires the -r option.
    -r <kbytes>Rotates the log file every <kbytes> of output. The default value is - 16. Requires the -f option.
    -sSets the default filter spec to silent.
    -v <format>Sets the output format for log messages. The default is brief format. For a - list of supported formats, see Controlling Log Output - Format.
    - -

    Filtering Log Output

    - -

    Every Android log message has a tag and a priority associated with it.

    - -
      -
    • The tag of a log message is a short string indicating the system component from which the - message originates (for example, "View" for the view system).
    • - -
    • The priority is one of the following character values, ordered from lowest to highest - priority:
    • - -
    • -
        -
      • V — Verbose (lowest priority)
      • - -
      • D — Debug
      • - -
      • I — Info
      • - -
      • W — Warning
      • - -
      • E — Error
      • - -
      • F — Fatal
      • - -
      • S — Silent (highest priority, on which nothing is ever printed)
      • -
      -
    • -
    - -

    You can obtain a list of tags used in the system, together with priorities, by running - LogCat and observing the first two columns of each message, given as - <priority>/<tag>.

    - -

    Here's an example of logcat output that shows that the message relates to priority level "I" - and tag "ActivityManager":

    -
    -I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}
    -
    - -

    To reduce the log output to a manageable level, you can restrict log output using filter - expressions. Filter expressions let you indicate to the system the tags-priority - combinations that you are interested in — the system suppresses other messages for the - specified tags.

    - -

    A filter expression follows this format tag:priority ..., where tag - indicates the tag of interest and priority indicates the minimum level of - priority to report for that tag. Messages for that tag at or above the specified priority are - written to the log. You can supply any number of tag:priority specifications in a - single filter expression. The series of specifications is whitespace-delimited.

    - -

    Here's an example of a filter expression that suppresses all log messages except those with - the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", - with priority "Debug" or above:

    -
    -adb logcat ActivityManager:I MyApp:D *:S
    -
    - -

    The final element in the above expression, *:S, sets the priority level for all - tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using - *:S is an excellent way to ensure that log output is restricted to the filters that - you have explicitly specified — it lets your filters serve as a "whitelist" for log - output.

    - -

    The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

    -
    -adb logcat *:W
    -
    - -

    If you're running LogCat from your development computer (versus running it on a - remote adb shell), you can also set a default filter expression by exporting a value for the - environment variable ANDROID_LOG_TAGS:

    -
    -export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"
    -
    - -

    Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device - instance, if you are running LogCat from a remote shell or using adb shell - logcat.

    - -

    Controlling Log Output Format

    - -

    Log messages contain a number of metadata fields, in addition to the tag and priority. You can - modify the output format for messages so that they display a specific metadata field. To do so, - you use the -v option and specify one of the supported output formats listed - below.

    - -
      -
    • brief — Display priority/tag and PID of the process issuing the - message (the default format).
    • - -
    • process — Display PID only.
    • - -
    • tag — Display the priority/tag only.
    • - -
    • raw — Display the raw log message, with no other metadata fields.
    • - -
    • time — Display the date, invocation time, priority/tag, and PID of the - process issuing the message.
    • - -
    • threadtime — Display the date, invocation time, priority, tag, and - the PID and TID of the thread issuing the message.
    • - -
    • long — Display all metadata fields and separate messages with blank - lines.
    • -
    - -

    When starting LogCat, you can specify the output format you want by using the - -v option:

    -
    -[adb] logcat [-v <format>]
    -
    - -

    Here's an example that shows how to generate messages in thread output - format:

    -
    -adb logcat -v thread
    -
    - -

    Note that you can only specify one output format with the -v option.

    - -

    Viewing Alternative Log Buffers

    - -

    The Android logging system keeps multiple circular buffers for log messages, and not all of - the log messages are sent to the default circular buffer. To see additional log messages, you can - run the logcat command with the -b option, to request viewing of an alternate - circular buffer. You can view any of these alternate buffers:

    - -
      -
    • radio — View the buffer that contains radio/telephony related - messages.
    • - -
    • events — View the buffer containing events-related messages.
    • - -
    • main — View the main log buffer (default)
    • -
    - -

    The usage of the -b option is:

    -
    -[adb] logcat [-b <buffer>]
    -
    - -

    Here's an example of how to view a log buffer containing radio and telephony messages:

    -
    -adb logcat -b radio
    -
    - -

    Viewing stdout and stderr

    - -

    By default, the Android system sends stdout and stderr - (System.out and System.err) output to /dev/null. In - processes that run the Dalvik VM, you can have the system write a copy of the output to the log - file. In this case, the system writes the messages to the log using the log tags - stdout and stderr, both with priority I.

    - -

    To route the output in this way, you stop a running emulator/device instance and then use the - shell command setprop to enable the redirection of output. Here's how you do it:

    -
    -$ adb shell stop
    -$ adb shell setprop log.redirect-stdio true
    -$ adb shell start
    -
    - -

    The system retains this setting until you terminate the emulator/device instance. To use the - setting as a default on the emulator/device instance, you can add an entry to - /data/local.prop on the device.

    - -

    Debugging Web Apps

    -

    - If you're developing a web application for Android, you can debug your JavaScript using the console JavaScript APIs, - which output messages to LogCat. For more information, see - Debugging Web Apps.

    diff --git a/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd b/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd deleted file mode 100644 index 3b5ceabaf3ba..000000000000 --- a/docs/html/guide/developing/debugging/debugging-projects-cmdline.jd +++ /dev/null @@ -1,78 +0,0 @@ -page.title=Debugging from Other IDEs -parent.title=Debugging -parent.link=index.html -@jd:body - - - - -

    If you are not using Eclipse to develop, you can still take advantage of all the tools that - the Android SDK provides for debugging. A basic debugging environment consists of:

    - -
      -
    • ADB
    • - -
    • DDMS
    • - -
    • Java Debugger
    • -
    - -

    You need to obtain a JDWP-compliant Java debugger to properly debug your application. - Most Java IDEs will already have one included, or you can use a command line debugger, - such as JDB, if you are using a simple text editor to develop applications.

    - -

    Starting a debugging environment

    -

    A Java Debugger assists you in finding problems with - your code by letting you set breakpoints, step through execution of your application, and examine - variable values. Since you are not using Eclipse, you have to manually start up the debugging - environment yourself by running a few tools that are provided in the Android SDK. To begin - debugging your application, follow these general steps:

    - -
      -
    1. Load an AVD with the Android emulator or connect a device to your computer.
    2. - -
    3. Start DDMS from the sdk /tools directory. This also starts ADB if it is - not already started. You should see your device appear in DDMS.
    4. - -
    5. Install and run your .apk file on the device or emulator. In DDMS, you should see your - application running under the device that you installed it to.
    6. - -
    7. Attach your debugger to the debugging port 8700, or to the specific port shown for the - application in DDMS.
    8. -
    - -

    Configuring Your IDE to Attach to the Debugging Port

    - -

    DDMS assigns a specific debugging port to every virtual machine that it finds on the - emulator. You must either attach your IDE to that port (listed on the Info tab for that VM), or - you can use a default port 8700 to connect to whatever application is currently selected on the - list of discovered virtual machines.

    - -

    Your IDE should attach to your application running on the emulator, showing you its threads - and allowing you to suspend them, inspect their state, and set breakpoints. If you selected "Wait - for debugger" in the Development settings panel the application will run when Eclipse connects, - so you will need to set any breakpoints you want before connecting.

    - -

    Changing either the application being debugged or the "Wait for debugger" option causes the - system to kill the selected application if it is currently running. You can use this to kill your - application if it is in a bad state by simply going to the settings and toggling the - checkbox.

    - - - - - - - diff --git a/docs/html/guide/developing/debugging/debugging-projects.jd b/docs/html/guide/developing/debugging/debugging-projects.jd deleted file mode 100644 index 2283f8be9f6d..000000000000 --- a/docs/html/guide/developing/debugging/debugging-projects.jd +++ /dev/null @@ -1,67 +0,0 @@ -page.title=Debugging from Eclipse with ADT -parent.title=Debugging -parent.link=index.html -@jd:body - -
    -
    -

    In this document

    - -
      -
    1. The Debug Perspective
    2. - -
    3. The DDMS Perspective
    4. -
    -
    -
    - -

    If you are developing in Eclipse with the ADT plugin, you can use the built-in Java Debugger, - along with DDMS, to debug your applications. To access the debugger and - DDMS, Eclipse displays the debugger and DDMS features as perspectives, which are customized - Eclipse views that display certain tabs and windows depending on the perspective that you are in. - Eclipse also takes care of starting the ADB host daemon for you, so you do not have to run this - manually.

    - -

    The Debug Perspective in Eclipse

    - -

    The Debug Perspective in Eclipse gives you access to the following tabs:

    - -
      -
    • Debug - Displays previously and currently debugged Android applications and its currently - running threads
    • - -
    • Variables - When breakpoints are set, displays variable values during code execution
    • - -
    • Breakpoints - Displays a list of the set breakpoints in your application code
    • - -
    • LogCat - Allows you to view system log messages in real time. The LogCat tab is also - available in the DDMS perspective.
    • -
    -

    You can access the Debug Perspective by clicking Window > Open Perspective > - Debug. Refer to the appropriate documentation for the Eclipse debugger for more - information.

    - -

    The DDMS Perspective

    -

    The DDMS Perspective in Eclipse lets you access all of the features - of DDMS from within the Eclipse IDE. The following sections of DDMS are available to you:

    - -
      -
    • Devices - Shows the list of devices and AVDs that are connected to ADB.
    • - -
    • Emulator Control - Lets you carry out device functions.
    • - -
    • LogCat - Lets you view system log messages in real time.
    • - -
    • Threads - Shows currently running threads within a VM.
    • - -
    • Heap - Shows heap usage for a VM.
    • - -
    • Allocation Tracker - Shows the memory allocation of objects.
    • - -
    • File Explorer - Lets you explore the device's file system.
    • -
    -

    To access the DDMS perspective, go to Window > Open Perspective > - DDMS. If DDMS does not appear, go to Window > Open Perspective > Other - ... and select DDMS from the Open Perspective window that appears. For - more information on using DDMS, see Using the Dalvik Debug Monitor Server. -

    \ No newline at end of file diff --git a/docs/html/guide/developing/debugging/debugging-tracing.jd b/docs/html/guide/developing/debugging/debugging-tracing.jd deleted file mode 100644 index 72f64982d9a8..000000000000 --- a/docs/html/guide/developing/debugging/debugging-tracing.jd +++ /dev/null @@ -1,402 +0,0 @@ -page.title=Profiling with Traceview and dmtracedump -parent.title=Debugging -parent.link=index.html -@jd:body - - - -

    Traceview is a graphical viewer for execution logs that you create by using the {@link - android.os.Debug} class to log tracing information in your code. Traceview can help you debug - your application and profile its performance.

    - -

    Traceview Layout

    - -

    When you have a trace log file (generated by adding tracing code to your application or by DDMS), - you can have Traceview load the log files and display their data in a window visualizes your application - in two panels:

    - -
      -
    • A timeline panel -- describes when each thread and method - started and stopped
    • - -
    • A profile panel -- provides a summary of what happened inside - a method
    • -
    - -

    The sections below provide addition information about the traceview output panes.

    - -

    Timeline Panel

    - -

    The image below shows a close up of the timeline panel. Each thread’s execution is shown - in its own row, with time increasing to the right. Each method is shown in another color (colors - are reused in a round-robin fashion starting with the methods that have the most inclusive time). - The thin lines underneath the first row show the extent (entry to exit) of all the calls to the - selected method. The method in this case is LoadListener.nativeFinished() and it was selected in - the profile view.

    - - Traceview timeline panel -

    Figure 1. The Traceview Timeline Panel

    - -

    Profile Panel

    - -

    Figure 2 shows the profile pane, a summary of all the time spent - in a method. The table shows both the inclusive and exclusive times (as well as the percentage of - the total time). Exclusive time is the time spent in the method. Inclusive time is the time spent - in the method plus the time spent in any called functions. We refer to calling methods as - "parents" and called methods as "children." When a method is selected (by clicking on it), it - expands to show the parents and children. Parents are shown with a purple background and children - with a yellow background. The last column in the table shows the number of calls to this method - plus the number of recursive calls. The last column shows the number of calls out of the total - number of calls made to that method. In this view, we can see that there were 14 calls to - LoadListener.nativeFinished(); looking at the timeline panel shows that one of those calls took - an unusually long time.

    - - Traceview profile panel. -

    Figure 2. The Traceview Profile Panel

    - -

    Traceview File Format

    - -

    Tracing creates two distinct pieces of output: a data file, which holds the trace - data, and a key file, which provides a mapping from binary identifiers to thread and - method names. The files are concatenated when tracing completes, into a single .trace - file.

    - -

    Note: The previous version of Traceview did not concatenate - these files for you. If you have old key and data files that you'd still like to trace, you can - concatenate them yourself with cat mytrace.key mytrace.data > - mytrace.trace.

    - -

    Data File Format

    - -

    The data file is binary, structured as follows (all values are stored in little-endian - order):

    -
    -* File format:
    -* header
    -* record 0
    -* record 1
    -* ...
    -*
    -* Header format:
    -* u4 magic 0x574f4c53 ('SLOW')
    -* u2 version
    -* u2 offset to data
    -* u8 start date/time in usec
    -*
    -* Record format:
    -* u1 thread ID
    -* u4 method ID | method action
    -* u4 time delta since start, in usec
    -
    - -

    The application is expected to parse all of the header fields, then seek to "offset to data" - from the start of the file. From there it just reads 9-byte records until EOF is reached.

    - -

    u8 start date/time in usec is the output from gettimeofday(). It's mainly there so - that you can tell if the output was generated yesterday or three months ago.

    - -

    method action sits in the two least-significant bits of the method word. The - currently defined meanings are:

    - -
      -
    • 0 - method entry
    • - -
    • 1 - method exit
    • - -
    • 2 - method "exited" when unrolled by exception handling
    • - -
    • 3 - (reserved)
    • -
    - -

    An unsigned 32-bit integer can hold about 70 minutes of time in microseconds.

    - -

    Key File Format

    - -

    The key file is a plain text file divided into three sections. Each section starts with a - keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start - of a new section.

    - -

    An example file might look like this:

    -
    -*version
    -1
    -clock=global
    -*threads
    -1 main
    -6 JDWP Handler
    -5 Async GC
    -4 Reference Handler
    -3 Finalizer
    -2 Signal Handler
    -*methods
    -0x080f23f8 java/io/PrintStream write ([BII)V
    -0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V
    -0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V
    -0x080da620 java/lang/RuntimeException   <init>    ()V
    -[...]
    -0x080f630c android/os/Debug startMethodTracing ()V
    -0x080f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String;I)V
    -*end
    -
    -

    The following list describes the major sections of a key file:

    -
    -
    version section
    - -
    The first line is the file version number, currently 1. The second line, - clock=global, indicates that we use a common clock across all threads. A future - version may use per-thread CPU time counters that are independent for every thread.
    - -
    threads section
    - -
    One line per thread. Each line consists of two parts: the thread ID, followed by a tab, - followed by the thread name. There are few restrictions on what a valid thread name is, so - include everything to the end of the line.
    - -
    methods section
    - -
    One line per method entry or exit. A line consists of four pieces, separated by tab marks: - method-ID [TAB] class-name [TAB] method-name [TAB] - signature . Only the methods that were actually entered or exited are included in the - list. Note that all three identifiers are required to uniquely identify a method.
    -
    - -

    Neither the threads nor methods sections are sorted.

    - -

    Creating Trace Files

    - -

    To use Traceview, you need to generate log files containing the trace information you want to - analyze.

    - -

    There are two ways to generate trace logs:

    -
      -
    • Include the {@link android.os.Debug} class in your code and call its - methods to start and stop logging of trace information to disk. This method is very precise because - you can specify in your code exactly where to start and stop logging trace data.
    • -
    • Use the method profiling feature of DDMS to generate trace logs. This method is less - precise since you do not modify code, but rather specify when to start and stop logging with - a DDMS. Although you have less control on exactly where the data is logged, this method is useful - if you don't have access to the application's code, or if you do not need the precision of the first method. -
    • -
    - -

    Before you start generating trace logs, be aware of the following restrictions:

    -
      -
    • If you are using the {@link android.os.Debug} class, your device or emulator must have an SD card - and your application must have permission to write to the SD card.
    • -
    • If you are using DDMS, Android 1.5 devices are not supported.
    • -
    • If you are using DDMS, Android 2.1 and earlier devices must - have an SD card present and your application must have permission to write to the SD card. -
    • If you are using DDMS, Android 2.2 and later devices do not need an SD card. The trace log files are - streamed directly to your development machine.
    • -
    - -

    This document focuses on using the {@link android.os.Debug} class to generate trace data. For more information on using DDMS - to generate trace data, see Using the Dalvik Debug Monitor Server. -

    - -

    To create the trace files, include the {@link android.os.Debug} class and call one of the - {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods. In the call, you - specify a base name for the trace files that the system generates. To stop tracing, call {@link - android.os.Debug#stopMethodTracing() stopMethodTracing()}. These methods start and stop method - tracing across the entire virtual machine. For example, you could call - {@link android.os.Debug#startMethodTracing() startMethodTracing()} in - your activity's {@link android.app.Activity#onCreate onCreate()} method, and call - {@link android.os.Debug#stopMethodTracing() stopMethodTracing()} in that activity's - {@link android.app.Activity#onDestroy()} method.

    -
    -    // start tracing to "/sdcard/calc.trace"
    -    Debug.startMethodTracing("calc");
    -    // ...
    -    // stop tracing
    -    Debug.stopMethodTracing();
    -
    - -

    When your application calls startMethodTracing(), the system creates a file called - <trace-base-name>.trace. This contains the binary method trace data and a - mapping table with thread and method names.

    - -

    The system then begins buffering the generated trace data, until your application calls - stopMethodTracing(), at which time it writes the buffered data to the output file. If the system - reaches the maximum buffer size before stopMethodTracing() is called, the system stops tracing - and sends a notification to the console.

    - -

    Interpreted code will run more slowly when profiling is enabled. Don't try to generate - absolute timings from the profiler results (i.e. "function X takes 2.5 seconds to run"). The - times are only useful in relation to other profile output, so you can see if changes have made - the code faster or slower.

    - -

    When using the Android emulator, you must specify an SD card when you create your AVD because the trace files - are written to the SD card. Your application must have permission to write to the SD card as well. - -

    The format of the trace files is previously described in this - document.

    - -

    Copying Trace Files to a Host Machine

    - -

    After your application has run and the system has created your trace files - <trace-base-name>.trace on a device or emulator, you must copy those files to - your development computer. You can use adb pull to copy the files. Here's an example - that shows how to copy an example file, calc.trace, from the default location on the emulator to - the /tmp directory on the emulator host machine:

    -
    -adb pull /sdcard/calc.trace /tmp
    -
    - -

    Viewing Trace Files in Traceview

    - -

    To run Traceview and view the trace files, enter traceview - <trace-base-name>. For example, to run Traceview on the example files copied in the - previous section, use:

    -
    -traceview /tmp/calc
    -
    - -

    Note: If you are trying to view the trace logs of an application - that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. - You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information - on this file, see the Proguard documentation.

    - -

    Using dmtracdedump

    - -

    dmtracedump is a tool that gives you an alternate way of generating - graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to - create the graphical output, so you need to install Graphviz before running dmtracedump.

    - -

    The dmtracedump tool generates the call stack data as a tree diagram, with each call - represented as a node. It shows call flow (from parent node to child nodes) using arrows. The - diagram below shows an example of dmtracedump output.

    - -

    Figure 3. Screenshot of dmtracedump

    - -

    For each node, dmtracedump shows <ref> - callname (<inc-ms>, <exc-ms>,<numcalls>), where

    - -
      -
    • <ref> -- Call reference number, as used in trace logs
    • - -
    • <inc-ms> -- Inclusive elapsed time (milliseconds spent in method, - including all child methods)
    • - -
    • <exc-ms> -- Exclusive elapsed time (milliseconds spent in method, - not including any child methods)
    • - -
    • <numcalls> -- Number of calls
    • -
    - -

    The usage for dmtracedump is:

    -
    -dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
    -
    - -

    The tool then loads trace log data from <trace-base-name>.data and - <trace-base-name>.key. The table below lists the options for dmtracedump.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    OptionDescription
    -d <trace-base-name>Diff with this trace name
    -g <outfile>Generate output to <outfile>
    -hTurn on HTML output
    -oDump the trace file instead of profiling
    -d <trace-base-name>URL base to the location of the sortable javascript file
    -t <percent>Minimum threshold for including child nodes in the graph (child's inclusive time as a - percentage of parent inclusive time). If this option is not used, the default threshold - is 20%.
    - - - -

    Traceview Known Issues

    - -
    -
    Threads
    - -
    - Traceview logging does not handle threads well, resulting in these two problems: - -
      -
    1. If a thread exits during profiling, the thread name is not emitted;
    2. - -
    3. The VM reuses thread IDs. If a thread stops and another starts, they may get the same - ID.
    4. -
    -
    - -
    \ No newline at end of file diff --git a/docs/html/guide/developing/debugging/debugging-ui.jd b/docs/html/guide/developing/debugging/debugging-ui.jd deleted file mode 100644 index 22748be93cdd..000000000000 --- a/docs/html/guide/developing/debugging/debugging-ui.jd +++ /dev/null @@ -1,547 +0,0 @@ -page.title=Debugging and Profiling User Interfaces -parent.title=Debugging -parent.link=index.html -@jd:body - - - -

    -Sometimes your application's layout can slow down your application. - To help debug issues in your layout, the Android SDK provides the Hierarchy Viewer and - layoutopt tools. -

    - -

    The Hierarchy Viewer application allows you to debug and optimize your user interface. It - provides a visual representation of the layout's View hierarchy (the View Hierarchy window) - and a magnified view of the display (the Pixel Perfect window).

    - -

    layoutopt is a command-line tool that helps you optimize the layouts and layout - hierarchies of your applications. You can run it against your layout files or resource - directories to quickly check for inefficiencies or other types of problems that could be - affecting the performance of your application.

    - -

    Debugging and Optimizing User Interfaces with Hierarchy Viewer

    - -

    Running Hierarchy Viewer and choosing a window

    -

    - To run Hierarchy Viewer, follow these steps:

    -
      -
    1. - Connect your device or launch an emulator. -

      - To preserve security, Hierarchy Viewer can only connect to devices running a - developer version of the Android system. -

      -
    2. -
    3. - If you have not done so already, install the application you want to work with. -
    4. -
    5. - Run the application, and ensure that its UI is visible. -
    6. -
    7. - From a terminal, launch hierarchyviewer from the - <sdk>/tools/ - directory. -
    8. -
    9. - The first window you see displays a list of devices and emulators. To expand the list - of Activity objects for a device or emulator, click the arrow on the left. This displays a - list of the Activity objects whose UI is currently visible on the device or emulator. The - objects are listed by their Android component name. The list includes both your application - Activity and system Activity objects. A screenshot of this window appears in - figure 1. -
    10. -
    11. - Select the name of your Activity from the list. You can now look at its view - hierarchy using the View Hierarchy window, or look at a magnified image of the UI using - the Pixel Perfect window. -
    12. -
    -

    - To learn how to use the View Hierarchy window, go to - About the View Hierarchy window. To learn how to use the - Pixel Perfect window, go to About the Pixel Perfect window. -

    - -

    Figure 1. Hierarchy Viewer device window

    -

    About the View Hierarchy window

    -

    - The View Hierarchy window displays the View objects that form the UI of the - Activity that is running on your device or emulator. You use it to look at individual - View objects within the context of the entire View tree. For each View object, the View - Hierarchy window also displays rendering performance data. -

    -

    - To see the View Hierarchy window, run Hierarchy Viewer as described in - the section Running Hierarchy Viewer and choosing a window. Next, click - View Hierarchy at the top of the device window. -

    -

    - You should see four panes: -

    -
      -
    • - Tree View: The left-hand pane displays the Tree View, - a diagram of the Activity object's hierarchy of views. Use Tree View to examine individual - View objects and see the relationships between View objects in your UI. -

      - To zoom in on the pane, use the slider at the bottom of the pane, or use your mouse - scroll wheel. To move around in the pane or reveal View objects that are not currently - visible, click and drag the pane. -

      -

      - To highlight the nodes in the tree whose class or ID match a search string, enter the - string in the Filter by class or id: edit box at the bottom of the - window. The background of nodes that match the search string will change from gray to - bright blue. -

      -

      - To save a screenshot of Tree View to a PNG file, click Save As PNG at - the top of the View Hierarchy window. This displays a dialog in which you can choose - a directory and file name. -

      -

      - To save a layered screenshot of your device or emulator to an Adobe Photoshop (PSD) - file, click Capture Layers at the top of the View Hierarchy window. - This displays a dialog in which you can choose a directory or file name. - Each View in the UI is saved as a separate Photoshop layer. -

      -

      - In Photoshop (or similar program that accepts .psd files), you can hide, show or edit a - layer independently of others. When you save a layered screenshot, you can examine and - modify the image of an individual View object. This helps you experiment with design - changes. -

      -
    • -
    • - The upper right-hand pane displays the Tree Overview, a smaller map - representation of the entire Tree View window. Use Tree Overview to identify the part of the - view tree that is being displayed in Tree View. -

      - You can also use Tree Overview to move around in the Tree View pane. Click and drag - the shaded rectangle over an area to reveal it in Tree View. -

      -
    • -
    • - The middle right-hand pane displays the Properties View, - a list of the properties for a selected View object. With Properties View, you can - examine all the properties without having to look at your application source. -

      - The properties are organized by category. To find an individual property, expand - a category name by clicking the arrow on its left. This reveals all the properties - in that category. -

      -
    • -
    • - The lower right-hand pane displays the Layout View, - a block representation of the UI. Layout View is another way to navigate through your UI. - When you click on a View object in Tree View, its position in the UI is highlighted. - Conversely, when you click in an area of Layout View, the View object for that area is - highlighted in Tree View. -

      - The outline colors of blocks in Layout View provide additional information: -

      -
        -
      • - Bold red: The block represents the the View that is currently selected in - Tree View. -
      • -
      • - Light red: The block represents the parent of the block outlined in bold red. -
      • -
      • - White: The block represents a visible View that is not a parent or child of the - View that is currently selected in Tree View. -
      • -
      -
    • -
    -

    - When the UI of the current Activity changes, the View Hierarchy window is not automatically - updated. To update it, click Load View Hierarchy at the top of the window. -

    -

    - Also, the window is not updated if you switch to a new Activity. To update it, start by - clicking the window selection icon in the bottom left-hand corner of the window. This - navigates back to the Window Selection window. From this window, click the Android - component name of the new Activity and then click Load View Hierarchy - at the top of the window. -

    -

    - A screenshot of the View Hierarchy window appears in figure 2. -

    - -

    Figure 2. The View Hierarchy window

    -

    Working with an individual View in Tree View

    -

    - Each node in Tree View represents a single View. Some information is always visible. Starting - at the top of the node, you see the following: -

    -
      -
    1. - View class: The View object's class. -
    2. -
    3. - View object address: A pointer to View object. -
    4. -
    5. - View object ID: The value of the - android:id - attribute. -
    6. -
    7. - Performance indicators: A set of three colored dots that indicate the rendering - speed of this View relative to other View objects in the tree. The three dots - represent (from left to right) the measure, layout, and draw times of the rendering. -

      - The colors indicate the following relative performance: -

      -
        -
      • - Green: For this part of the render time, this View is in the faster 50% of all - the View objects in the tree. For example, a green dot for the measure time means - that this View has a faster measure time than 50% of the View objects in the tree. -
      • -
      • - Yellow: For this part of the render time, this View is in the slower 50% of all - the View objects in the tree. For example, a yellow dot for the layout time means - that this View has a slower layout time than 50% of the View objects in the tree. -
      • -
      • - Red: For this part of the render time, this View is the slowest one in the tree. - For example, a red dot for the draw time means that this View takes the most - time to draw of all the View objects in the tree. -
      • -
      -
    8. -
    9. - View index: The zero-based index of the View in its parent View. If it is the only child, - this is 0. -
    10. -
    -

    - When you select a node, additional information for the View appears in a small window above - the node. When you click one of the nodes, you see the following: -

    -
      -
    • - Image: The actual image of the View, as it would appear in the emulator. If the View has - children, these are also displayed. -
    • -
    • - View count: The number of View objects represented by this node. This includes the View - itself and a count of its children. For example, this value is 4 for a View that has 3 - children. -
    • -
    • - Render times: The actual measure, layout, and draw times for the View rendering, in - milliseconds. These represent the same values as the performance indicators mentioned in - the preceding section. -
    • -
    -

    - An annotated screenshot of an individual node in the Tree View window appears in figure 3. -

    - -

    Figure 3. An annotated node in Tree View

    -

    Debugging with View Hierarchy

    -

    - The View Hierarchy window helps you debug an application by providing a static display - of the UI. The display starts with your application's opening screen. As you step through - your application, the display remains unchanged until you redraw it by invalidating and - then requesting layout for a View. -

    -

    - To redraw a View in the display: -

    -
      -
    • - Select a View in Tree View. As you move up towards the root of the tree (to the - left in the Tree View), you see the highest-level View objects. Redrawing a high-level - object usually forces the lower-level objects to redraw as well. -
    • -
    • - Click Invalidate at the top of the window. This marks the View as - invalid, and schedules it for a redraw at the next point that a layout is requested. -
    • -
    • - Click Request Layout to request a layout. The View and its children - are redrawn, as well as any other View objects that need to be redrawn. -
    • -
    -

    - Manually redrawing a View allows you to watch the View object tree and examine the properties of - individual View objects one step at a time as you go through breakpoints in your code. -

    -

    Optimizing with View Hierarchy

    -

    - View Hierarchy also helps you identify slow render performance. You start by looking at the - View nodes with red or yellow performance indicators to identify the slower View objects. As you - step through your application, you can judge if a View is consistently slow or slow only in - certain circumstances. -

    -

    - Remember that slow performance is not necessarily evidence of a problem, especially for - ViewGroup objects. View objects that have more children and more complex View objects render - more slowly. -

    -

    - The View Hierarchy window also helps you find performance issues. Just by looking at the - performance indicators (the dots) for each View node, you can see which View objects are the - slowest to measure, layout, and draw. From that, you can quickly identify the problems you - should look at first. -

    -

    Examining and Designing User Interfaces with Pixel Perfect

    -

    - Pixel Perfect is a tool for examining pixel properties and laying out UIs from a design drawing. -

    -

    About the Pixel Perfect window

    -

    - The Pixel Perfect window displays a magnified image of the screen that is currently - visible on the emulator or device. In it, you can examine the properties - of individual pixels in the screen image. You can also use the Pixel Perfect window - to help you lay out your application UI based on a bitmap design. -

    -

    - To see the Pixel Perfect window, run Hierarchy Viewer, as described in - the section Running Hierarchy Viewer and choosing a window. Next, click - Inspect Screenshot at the top of the device window. The Pixel Perfect window - appears. -

    -

    - In it, you see three panes: -

    -
      -
    • - View Object pane: This is a hierarchical list of the View objects that are currently - visible on the device or emulator screen, including both the ones in your application and - the ones generated by the system. The objects are listed by their View class. - To see the class names of a View object's children, expand the View by clicking the - arrow to its left. When you click a View, its position is highlighted in the Pixel Perfect - pane on the right. -
    • -
    • - Pixel Perfect Loupe pane: This is the magnified screen image. It is overlaid by a grid in - which each square represents one pixel. To look at the information for a pixel, click in its - square. Its color and X,Y coordinates appear at the bottom of the pane. -

      - The magenta crosshair in the pane corresponds to the positioning - crosshair in the next pane. It only moves when you move the crosshair in the next pane. -

      -

      - To zoom in or out on the image, use the Zoom slider at the bottom of - the pane, or use your mouse's scroll wheel. -

      -

      - When you select a pixel in the Loupe pane, you see the following information at the - bottom of the pane: -

      -
        -
      • - Pixel swatch: A rectangle filled with the same color as the pixel. -
      • -
      • - HTML color code: The hexadecimal RGB code corresponding to the pixel color -
      • -
      • - RGB color values: A list of the (R), green (G), and blue (B) color values of the - pixel color. Each value is in the range 0-255. -
      • -
      • - X and Y coordinates: The pixel's coordinates, in device-specific pixel units. - The values are 0-based, with X=0 at the left of the screen and Y=0 at the top. -
      • -
      -
    • -
    • - Pixel Perfect pane: This displays the currently visible screen as it would appear in the - emulator. -

      - You use the cyan crosshair to do coarse positioning. Drag the crosshair in the image, - and the Loupe crosshair will move accordingly. You can also click on a point in the - Pixel Perfect pane, and the crosshair will move to that point. -

      -

      - The image corresponding to the View object selected in the View Object pane is - outlined in a box that indicates the View object's position on the screen. For the - selected object, the box is bold red. Sibling and parent View objects have a light - red box. View objects that are neither parents nor siblings are in white. -

      -

      - The layout box may have other rectangles either inside or outside it, each of which - indicates part of the View. A purple or green rectangle indicates the View bounding box. - A white or black box inside the layout box represents the padding, the - defined distance between the View object's content and its bounding box. An outer white - or black rectangle represents the margins, the distance between the - View bounding box and adjacent View objects. The padding and margin boxes are white if - the layout background is black, and vice versa. -

      -

      - You can save the screen image being displayed in the Pixel Perfect pane as a PNG file. - This produces a screenshot of the current screen. To do this, click - Save as PNG at the top of the window. This displays a dialog, - in which you can choose a directory and filename for the file. -

      -
    • -
    -

    - The panes are not automatically refreshed when you change one of the View objects or go to - another Activity. To refresh the Pixel Perfect pane and the Loupe pane, click - Refresh Screenshot at the top of the window. This will change the panes - to reflect the current screen image. You still may need to refresh the View Object pane; - to do this, click Refresh Tree at the top of the window. -

    -

    - To automatically refresh the panes while you are debugging, set - Auto Refresh at the top of the window, and then set a refresh rate - with the Refresh Rate slider at the bottom of the Loupe pane. -

    -

    Working with Pixel Perfect overlays

    -

    - You often construct a UI based on a design done as a bitmap image. The Pixel Perfect window - helps you match up your View layout to a bitmap image by allowing you to load the bitmap as an - overlay on the screen image. -

    -

    - To use a bitmap image as an overlay: -

    -
      -
    • - Start your application in a device or emulator and navigate to the Activity whose UI you - want to work with. -
    • -
    • - Start Hierarchy Viewer and navigate to the Pixel Perfect window. -
    • -
    • - At the top of the window, click Load Overlay. A dialog opens, prompting - for the image file to load. Load the image file. -
    • -
    • - Pixel Perfect displays the overlay over the screen image in the Pixel Perfect pane. The - lower left corner of the bitmap image (X=0, Y=max value) is anchored on the lower - leftmost pixel (X=0, Y=max screen) of the screen. -

      - By default, the overlay has a 50% transparency, which allows you to see the screen - image underneath. You can adjust this with the Overlay: slider at the - bottom of the Loupe pane. -

      -

      - Also by default, the overlay is not displayed in the Loupe pane. To display it, - set Show in Loupe at the top of the window. -

      -
    • -
    -

    - The overlay is not saved as part of the screenshot when you save the screen image as a PNG - file. -

    -

    - A screenshot of the Pixel Perfect window appears in figure 4. -

    - -

    Figure 4. The Pixel Perfect window

    -

    Optimizing layouts with layoutopt

    -

    - The layoutopt tool lets you analyze the XML files that define your - application's UI to find inefficiencies in the view hierarchy.

    - -

    - To run the tool, open a terminal and launch layoutopt <xmlfiles> - from your SDK tools/ directory. The <xmlfiles> argument is a space- - delimited list of resources you want to analyze, either uncompiled resource xml files or - directories of such files. -

    -

    - The tool loads the specified XML files and analyzes their definitions and - hierarchies according to a set of predefined rules. For every issue it detects, it - displays the following information: -

    -
      -
    • - The filename in which the issue was detected. -
    • -
    • - The line number for the issue. -
    • -
    • - A description of the issue, and for some types of issues it also suggests a resolution. -
    • -
    -

    The following is a sample of the output from the tool:

    -
    -$ layoutopt samples/
    -samples/compound.xml
    -   7:23 The root-level <FrameLayout/> can be replaced with <merge/>
    -   11:21 This LinearLayout layout or its FrameLayout parent is useless
    -samples/simple.xml
    -   7:7 The root-level <FrameLayout/> can be replaced with <merge/>
    -samples/too_deep.xml
    -   -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10!
    -   20:81 This LinearLayout layout or its LinearLayout parent is useless
    -   24:79 This LinearLayout layout or its LinearLayout parent is useless
    -   28:77 This LinearLayout layout or its LinearLayout parent is useless
    -   32:75 This LinearLayout layout or its LinearLayout parent is useless
    -   36:73 This LinearLayout layout or its LinearLayout parent is useless
    -   40:71 This LinearLayout layout or its LinearLayout parent is useless
    -   44:69 This LinearLayout layout or its LinearLayout parent is useless
    -   48:67 This LinearLayout layout or its LinearLayout parent is useless
    -   52:65 This LinearLayout layout or its LinearLayout parent is useless
    -   56:63 This LinearLayout layout or its LinearLayout parent is useless
    -samples/too_many.xml
    -   7:413 The root-level <FrameLayout/> can be replaced with <merge/>
    -   -1:-1 This layout has too many views: 81 views, it should have <= 80!
    -samples/useless.xml
    -   7:19 The root-level <FrameLayout/> can be replaced with <merge/>
    -   11:17 This LinearLayout layout or its FrameLayout parent is useless
    -
    diff --git a/docs/html/guide/developing/debugging/index.jd b/docs/html/guide/developing/debugging/index.jd deleted file mode 100644 index 0ad1a088a6cb..000000000000 --- a/docs/html/guide/developing/debugging/index.jd +++ /dev/null @@ -1,188 +0,0 @@ -page.title=Debugging -@jd:body - - -
    -
    -

    In this document

    - -
      -
    1. Debugging Environment
    2. - -
    3. Additional Debugging Tools
    4. - -
    5. Debugging Tips
    6. -
    -
    -
    - -

    The Android SDK provides most of the tools that you need to debug your applications. You need - a JDWP-compliant debugger if you want to be able to do things such as step through code, - view variable values, and pause execution of an application. If you are using Eclipse, a - JDWP-compliant debugger is already included and there is no setup required. If you are using - another IDE, you can use the debugger that comes with it and attach the debugger to a special - port so it can communicate with the application VMs on your devices. The main components that - comprise a typical Android debugging environment are:

    - -
    -
    adb
    - -
    adb acts as a middleman between a device and your development system. It provides various - device management capabilities, including moving and syncing files to the emulator, running a - UNIX shell on the device or emulator, and providing a general means to communicate with - connected emulators and devices.
    - -
    Dalvik Debug Monitor - Server
    - -
    DDMS is a graphical program that communicates with your devices through adb. DDMS can - capture screenshots, gather thread and stack information, spoof incoming calls and SMS - messages, and has many other features.
    - -
    Device or - Android Virtual Device
    - -
    Your application must run in a device or in an AVD so that it can be debugged. An adb device - daemon runs on the device or emulator and provides a means for the adb host daemon to - communicate with the device or emulator.
    - -
    JDWP debugger
    - -
    The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to attach to - a VM. Each application runs in a VM and exposes a unique port that you can attach a debugger to - via DDMS. If you want to debug multiple applications, attaching to each port might become - tedious, so DDMS provides a port forwarding feature that can forward a specific VM's debugging - port to port 8700. You can switch freely from application to application by highlighting it in the - Devices tab of DDMS. DDMS forwards the appropriate port to port 8700. Most modern Java IDEs include a JDWP debugger, - or you can use a command line debugger such as - jdb.
    -
    - -

    Debugging Environment

    - -

    Figure 1 shows how the various debugging tools work together in a typical - debugging environment.

    - Debugging workflow -

    In addition to the main debugging tools, the Android SDK provides additional tools to help you - debug and profile your applications:

    - -
    -
    Heirarchy Viewer - and layoutopt
    - -
    Graphical programs that let you debug and profile user interfaces.
    - -
    Traceview
    - -
    A graphical viewer that displays trace file data for method calls and times saved by your - application, which can help you profile the performance of your application.
    - -
    Dev Tools - Android application
    - -
    The Dev Tools application included in the emulator system image exposes several settings - that provide useful information such as CPU usage and frame rate. You can also transfer the - application to a hardware device.
    -
    - - -

    Debugging Tips

    - -

    While debugging, keep these helpful tips in mind to help you figure out common problems with your -applications:

    - -
    -
    Dump the stack trace
    -
    To obtain a stack dump from emulator, you can log -in with adb shell, use ps to find the process you -want, and then kill -3. The stack trace appears in the log file. -
    - -
    Display useful info on the emulator screen
    -
    The device can display useful information such as CPU usage or highlights -around redrawn areas. Turn these features on and off in the developer settings -window as described in -Debugging with the Dev Tools App. -
    - -
    Get application and system state information from the emulator
    -
    You can access dumpstate information from the adb shell commands. See -dumpsys and -dumpstate on the adb topic page.
    - - - -
    Get wireless connectivity information
    -
    You can get information about wireless connectivity using DDMS. -From the Device menu, select Dump -radio state.
    - -
    Log trace data
    -
    You can log method calls and other tracing data in an activity by calling -{@link android.os.Debug#startMethodTracing(String) startMethodTracing()}. See Profiling with Traceview and -dmtracedump for details.
    - -
    Log radio data
    -
    By default, radio information is not logged to the system (it is a lot of -data). However, you can enable radio logging using the following commands: - -
    -adb shell
    -logcat -b radio
    -
    -
    - -
    Capture screenshots
    -
    The Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Select -Device > Screen capture.
    - -
    Use debugging helper classes
    -
    Android provides debug helper classes such as {@link android.util.Log - util.Log} and {@link android.os.Debug} for your convenience.
    - -
    Garbage collection
    -
    -The debugger and garbage collector are currently loosely integrated. The VM guarantees that any -object the debugger is aware of is not garbage collected until after the debugger disconnects. -This can result in a buildup of objects over time while the debugger is connected. For example, -if the debugger sees a running thread, the associated {@link java.lang.Thread} object is not -garbage collected even after the thread terminates. -
    - -
    - -

    See the Troubleshooting document -for answers to some common developing and debugging issues.

    - - - - - - - diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd deleted file mode 100644 index d91551a8e92d..000000000000 --- a/docs/html/guide/developing/device.jd +++ /dev/null @@ -1,267 +0,0 @@ -page.title=Using Hardware Devices -@jd:body - -
    -
    -

    In this document

    -
      -
    1. Setting up a Device for Development -
        -
      1. USB Vendor IDs
      2. -
      -
    2. -
    -

    See also

    -
      -
    1. Google USB Driver
    2. -
    3. OEM USB Drivers
    4. -
    -
    -
    - -

    When building a mobile application, it's important that you always test your application on a -real device before releasing it to users. This page describes how to set up your development -environment and Android-powered device for testing and debugging on the device.

    - -

    You can use any Android-powered device as an environment for running, -debugging, and testing your applications. The tools included in the SDK make it easy to install and -run your application on the device each time you compile. You can install your application on the -device directly from Eclipse or from the command line with ADB. If -you don't yet have a device, check with the service providers in your area to determine which -Android-powered devices are available.

    - -

    If you want a SIM-unlocked phone, then you might consider the Google Nexus S. To find a place -to purchase the Nexus S and other Android-powered devices, visit google.com/phone.

    - -

    Note: When developing on a device, keep in mind that you should -still use the Android emulator to test your -application -on configurations that are not equivalent to those of your real device. Although the emulator -does not allow you to test every device feature (such as the accelerometer), it does -allow you to verify that your application functions properly on different versions of the Android -platform, in different screen sizes and orientations, and more.

    - - -

    Setting up a Device for Development

    - -

    With an Android-powered device, you can develop and debug your Android applications just as you -would on the emulator. Before you can start, there are just a few things to do:

    - -
      -
    1. Declare your application as "debuggable" in your Android Manifest. -

      When using Eclipse, you can skip this step, because running your app directly from -the Eclipse IDE automatically enables debugging.

      -

      In the AndroidManifest.xml file, add android:debuggable="true" to -the <application> element.

      -

      Note: If you manually enable debugging in the manifest - file, be sure to disable it before you build for release (your published application -should usually not be debuggable).

    2. -
    3. Turn on "USB Debugging" on your device. -

      On the device, go to Settings > Applications > Development - and enable USB debugging - (on an Android 4.0 device, the setting is -located in Settings > Developer options).

      -
    4. -
    5. Set up your system to detect your device. -
        -
      • If you're developing on Windows, you need to install a USB driver for adb. For an -installation guide and links to OEM drivers, see the OEM USB -Drivers document.
      • -
      • If you're developing on Mac OS X, it just works. Skip this step.
      • -
      • If you're developing on Ubuntu Linux, you need to add a -udev rules file that contains a USB configuration for each type of device -you want to use for development. In the rules file, each device manufacturer -is identified by a unique vendor ID, as specified by the -ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on -Ubuntu Linux: - -
          -
        1. Log in as root and create this file: - /etc/udev/rules.d/51-android.rules. -

          Use this format to add each vendor to the file:
          - SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev" -

          - - In this example, the vendor ID is for HTC. The MODE -assignment specifies read/write permissions, and GROUP defines -which Unix group owns the device node.

          - -

          Note: The rule syntax -may vary slightly depending on your environment. Consult the udev -documentation for your system as needed. For an overview of rule syntax, see -this guide to writing udev -rules.

          -
        2. -
        3. Now execute:
          - chmod a+r /etc/udev/rules.d/51-android.rules -
        4. -
        -
      • -
      -
    6. -
    - -

    When plugged in over USB, can verify that your device is connected by executing adb -devices from your SDK {@code platform-tools/} directory. If connected, -you'll see the device name listed as a "device."

    - -

    If using Eclipse, run or debug your application as usual. You will be -presented with a Device Chooser dialog that lists the available -emulator(s) and connected device(s). Select the device upon which you want to -install and run the application.

    - -

    If using the Android -Debug Bridge (adb), you can issue commands with the -d flag to -target your connected device.

    - -

    USB Vendor IDs

    - -

    This table provides a reference to the vendor IDs needed in order to add USB -device support on Linux. The USB Vendor ID is the value given to the -ATTR{idVendor} property in the rules file, as described -above.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CompanyUSB Vendor ID
    Acer0502
    ASUS0b05
    Dell413c
    Foxconn0489
    Fujitsu04c5
    Fujitsu Toshiba04c5
    Garmin-Asus091e
    Google18d1
    Hisense109b
    HTC0bb4
    Huawei12d1
    K-Touch24e3
    KT Tech2116
    Kyocera0482
    Lenovo17ef
    LG1004
    Motorola22b8
    NEC0409
    Nook2080
    Nvidia0955
    OTGV2257
    Pantech10a9
    Pegatron1d4d
    Philips0471
    PMC-Sierra04da
    Qualcomm05c6
    SK Telesys1f53
    Samsung04e8
    Sharp04dd
    Sony054c
    Sony Ericsson0fce
    Teleepoch2340
    Toshiba0930
    ZTE19d2
    diff --git a/docs/html/guide/developing/devices/emulator.jd b/docs/html/guide/developing/devices/emulator.jd deleted file mode 100644 index 5edd1f5ed0f0..000000000000 --- a/docs/html/guide/developing/devices/emulator.jd +++ /dev/null @@ -1,1571 +0,0 @@ -page.title=Using the Android Emulator -parent.title=Managing Virtual Devices -parent.link=index.html -@jd:body - - - -Image of the Android Emulator -

    The Android SDK includes a virtual mobile device emulator -that runs on your computer. The emulator lets you prototype, develop and test -Android applications without using a physical device.

    - -

    The Android emulator mimics all of the hardware and software features -of a typical mobile device, except that it cannot place actual phone -calls. It provides a variety of navigation and control keys, which you can "press" -using your mouse or keyboard to generate events for your application. It also -provides a screen in which your application is displayed, together with any other -active Android applications.

    - -

    To let you model and test your application more easily, the emulator utilizes -Android Virtual Device (AVD) configurations. AVDs let you define certain hardware -aspects of your emulated phone and allow you to create many configurations to test -many Android platforms and hardware permutations. Once your application is running on -the emulator, it can use the services of the Android platform to invoke other -applications, access the network, play audio and video, store and retrieve data, -notify the user, and render graphical transitions and themes.

    - -

    The emulator also includes a variety of debug capabilities, such as a console -from which you can log kernel output, simulate application interrupts (such as -arriving SMS messages or phone calls), and simulate latency effects and dropouts -on the data network.

    - - - -

    Overview

    - -

    The Android emulator is an application that provides a virtual -mobile device on which you can run your Android applications. It runs a full -Android system stack, down to the kernel level, that includes a set of -preinstalled applications (such as the dialer) that you can access from your -applications. You can choose what version of the Android system you want to -run in the emulator by configuring AVDs, and you can also customize the -mobile device skin and key mappings. When launching the emulator and at runtime, -you can use a variety of commands and options to control its behavior. -

    - -

    The Android system images available through the Android SDK Manager contain -code for the Android Linux kernel, the native libraries, the Dalvik VM, and the -various Android packages (such as the Android framework and preinstalled -applications). The emulator provides dynamic binary translation of device -machine code to the OS and processor architecture of your development -machine.

    - -

    The Android emulator supports many hardware features likely to be found on -mobile devices, including:

    - -
      -
    • An ARMv5 CPU and the corresponding memory-management unit (MMU)
    • -
    • A 16-bit LCD display
    • -
    • One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone -buttons)
    • -
    • A sound chip with output and input capabilities
    • -
    • Flash memory partitions (emulated through disk image files on the -development machine)
    • -
    • A GSM modem, including a simulated SIM Card
    • -
    • A camera, using a webcam connected to your development computer.
    • -
    • Sensors like an accelerometer, using data from a USB-connected Android device.
    • -
    - -

    The following sections describe the emulator and its use for development of Android -applications in more detail.

    - - -

    Android Virtual Devices and the Emulator

    - -

    To use the emulator, you first must create one or more AVD configurations. In each -configuration, you specify an Android platform to run in the emulator and the set of hardware -options and emulator skin you want to use. Then, when you launch the emulator, you specify -the AVD configuration that you want to load.

    - -

    Each AVD functions as an independent device, with its own private storage for -user data, SD card, and so on. When you launch the emulator with an AVD configuration, -it automatically loads the user data and SD card data from the AVD directory. By default, -the emulator stores the user data, SD card data, and cache in the AVD directory.

    - -

    To create and manage AVDs you use the AVD Manager UI or the android tool -that is included in the SDK. -For complete information about how to set up AVDs, see Managing Virtual Devices.

    - - -

    Starting and Stopping the Emulator

    - -

    During development and testing of your application, you install and run your -application in the Android emulator. You can launch the emulator as a standalone -application from a command line, or you can run it from within your Eclipse -development environment. In either case, you specify the AVD configuration to -load and any startup options you want to use, as described in this document. -

    - -

    You can run your application on a single instance of the emulator or, -depending on your needs, you can start multiple emulator instances and run your -application in more than one emulated device. You can use the emulator's -built-in commands to simulate GSM phone calling or SMS between emulator -instances, and you can set up network redirection that allows emulators to send -data to one another. For more information, see Telephony -Emulation, SMS Emulation, and -Emulator Networking

    - -

    To start an instance of the emulator from the command line, navigate to the -tools/ folder of the SDK. Enter emulator command -like this:

    - -
    emulator -avd <avd_name> [<options>]
    - -

    This initializes the emulator, loads an AVD configuration and displays the emulator -window. For more information about command line options for the emulator, see the -Android Emulator tool reference.

    - -

    Note: You can run multiple -instances of the emulator concurrently, each with its own AVD configuration and -storage area for user data, SD card, and so on.

    - -

    If you are working in Eclipse, the ADT plugin for Eclipse installs your -application and starts the emulator automatically, when you run or debug -the application. You can specify emulator startup options in the Run/Debug -dialog, in the Target tab. When the emulator is running, you can issue -console commands as described later in this document.

    - -

    If you are not working in Eclipse, see Installing Applications -on the Emulator for information about how to install your application.

    - -

    To stop an emulator instance, just close the emulator's window.

    - -

    For a reference of the emulator's startup commands and keyboard mapping, see -the Android Emulator tool -reference.

    - - -

    Installing Applications on the Emulator

    - -

    If you don't have access to Eclipse or the ADT Plugin, you can install your application on the -emulator using the adb utility. Before -installing the application, you need to build and package it into an .apk as described -in Building and -Running Apps. Once the application is installed, you can start the emulator from the command -line as described previously, using any startup options necessary. -When the emulator is running, you can also connect to the emulator instance's -console to issue commands as needed.

    - -

    As you update your code, you periodically package and install it on the emulator. -The emulator preserves the application and its state data across restarts, -in a user-data disk partition. To ensure that the application runs properly -as you update it, you may need to delete the emulator's user-data partition. -To do so, start the emulator with the -wipe-data option. -For more information about the user-data partition and other emulator storage, -see Working with Emulator Disk Images.

    - - -

    Using Hardware Acceleration

    - -

    In order to make the Android emulator run faster and be more responsive, you can configure it to -take advantage of hardware acceleration, using a combination of configuration options, specific -Android system images and hardware drivers.

    - - -

    Configuring Graphics Acceleration

    - -

    Caution: As of SDK Tools Revision 17, the graphics -acceleration feature for the emulator is experimental; be alert for incompatibilities and -errors when using this feature.

    - -

    Graphics acceleration for the emulator takes advantage of your development computer's graphics -hardware, specifically its graphics processing unit (GPU), to make screen drawing faster. To use -the graphics acceleration feature, you must have the following versions of the Android development -tools installed:

    - -
      -
    • Android SDK Tools, Revision 17 or higher
    • -
    • Android SDK Platform API 15, Revision 3 or higher
    • -
    - -

    Use the Android SDK -Manager to install these components:

    - -

    Note: Not all applications are compatible with graphics hardware -acceleration. In particular, the Browser application and applications using the {@link -android.webkit.WebView} component are not compatible with graphics acceleration.

    - -

    To configure an AVD to use graphics acceleration:

    - -
      -
    1. Make sure you have the required SDK components installed (listed above).
    2. -
    3. Start the AVD Manager and create a new AVD with the Target value of -Android 4.0.3 (API Level 15), revision 3 or higher.
    4. -
    5. If you want to have graphics acceleration enabled by default for this AVD, in the -Hardware section, click New, select GPU emulation -and set the value to Yes. -

      Note: You can also enable graphics acceleration when you -start an emulator using command line options as describe in the next section.

      -
    6. -
    7. Name the AVD instance and select any other configuration options. -

      Caution: Do not select the Snapshot: Enabled -option. Snapshots are not supported for emulators with graphics acceleration enabled.

      -
    8. -
    9. Click Create AVD to save the emulator configuration.
    10. -
    - -

    If you set GPU emulation to Yes for your AVD, then graphics -acceleration is automatically enabled when you run it. If you did not enable GPU -emulation when you created the AVD, you can still enable it at runtime.

    - -

    To enable graphics acceleration at runtime for an AVD:

    - -
      -
    • If you are running the emulator from the command line, just include the {@code -gpu on} -option: -
      emulator -avd <avd_name> -gpu on
      -

      Note: You must specify an AVD configuration that uses -Android 4.0.3 (API Level 15, revision 3) or higher system image target. Graphics acceleration is not -available for earlier system images.

      -
    • -
    • If you are running the emulator from Eclipse, run your Android application using an AVD with -the {@code -gpu on} option enabled: -
        -
      1. In Eclipse, click your Android project folder and then select Run > Run -Configurations...
      2. -
      3. In the left panel of the Run Configurations dialog, select your Android -project run configuration or create a new configuration.
      4. -
      5. Click the Target tab.
      6. -
      7. Select the AVD you created in the previous procedure.
      8. -
      9. In the Additional Emulator Command Line Options field, enter:
        - {@code -gpu on}
      10. -
      11. Run your Android project using this run configuration.
      12. -
      -
    • -
    - - -

    Configuring Virtual Machine Acceleration

    - -

    Caution: As of SDK Tools Revision 17, the virtual machine -acceleration feature for the emulator is experimental; be alert for incompatibilities and errors -when using this feature.

    - -

    Many modern CPUs provide extensions for running virtual machines (VMs) more efficiently. Taking -advantage of these extensions with the Android emulator requires some additional configuration of -your development system, but can significantly improve the execution speed. Before attempting to use -this type of acceleration, you should first determine if your development system’s CPU supports one -of the following virtualization extensions technologies:

    - -
      -
    • Intel Virtualization Technology (VT, VT-x, vmx) extensions
    • -
    • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)
    • -
    - -

    The specifications from the manufacturer of your CPU should indicate if it supports -virtualization extensions. If your CPU does not support one of these virtualization technologies, -then you cannot use virtual machine acceleration.

    - -

    Note: Virtualization extensions are typically enabled through -your computer's BIOS and are frequently turned off by default. Check the documentation for your -system's motherboard to find out how to enable virtualization extensions.

    - -

    Once you have determined that your CPU supports virtualization extensions, make sure you can work -within these additional requirements of running an emulator inside an accelerated virtual -machine:

    - -
      -
    • x86 AVD Only - You must use an AVD that is uses an x86 system image target. -AVDs that use ARM-based system images cannot be accelerated using the emulator configurations -described here.
    • -
    • Not Inside a VM - You cannot run a VM-accelerated emulator inside another -virtual machine, such as a VirtualBox or VMWare-hosted virtual machine. You must run the emulator -directly on your system hardware.
    • -
    • Other VM Drivers - If you are running another virtualization technology on -your system such as VirtualBox or VMWare, you may need to unload the driver for that virtual machine -hosting software before running an accelerated emulator.
    • -
    • OpenGL® Graphics - Emulation of OpenGL ES graphics may not perform at the -same level as an actual device.
    • -
    - -

    To use virtual machine acceleration with the emulator, you need the following version of Android -development tools. Use the Android SDK -Manager to install these components:

    - -
      -
    • Android SDK Tools, Revision 17 or higher
    • -
    • Android x86-based system image
    • -
    - -

    If your development environment meets all of the requirements for running a VM-accelerated -emulator, you can use the AVD Manager to create an x86-based AVD configuration:

    - -
      -
    1. In the Android SDK Manager, make sure you have an x86-based System Image - installed for your target Android version. If you do not have an x86 System - Image installed, select one in the Android SDK Manager and install it. -

      Tip: System images are listed under each API Level in the SDK - Manager. An x86 system image may not be available for all API levels.

      -
    2. -
    3. Start the AVD Manager and create a new AVD with an x86 value for the -CPU/ABI field. You may need to select a specific Target value, or -select a Target value and then select a specific CPU/ABI -option.
    4. -
    5. Name the emulator instance and select any other configuration options.
    6. -
    7. Click Create AVD to save the emulator configuration.
    8. -
    - -

    Configuring VM Acceleration on Windows

    - -

    Virtual machine acceleration for Windows requires the installation of the Intel Hardware -Accelerated Execution Manager (Intel HAXM). The software requires an Intel CPU with -Virtualization Technology (VT) support and one of the following operating systems:

    - -
      -
    • Windows 7 (32/64-bit)
    • -
    • Windows Vista (32/64-bit)
    • -
    • Windows XP (32-bit only)
    • -
    - -

    To install the virtualization driver:

    - -
      -
    1. Start the Android SDK Manager, select Extras and then select Intel -Hardware Accelerated Execution Manager.
    2. -
    3. After the download completes, execute {@code -<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe}.
    4. -
    5. Follow the on-screen instructions to complete installation.
    6. -
    7. After installation completes, confirm that the virtualization driver is operating correctly by -opening a command prompt window and running the following command: -
      sc query intelhaxm
      -

      You should see a status message including the following information:

      -
      -SERVICE_NAME: intelhaxm
      -       ...
      -       STATE              : 4  RUNNING
      -       ...
      -
      -
    8. -
    - -

    To run an x86-based emulator with VM acceleration:

    -
      -
    • If you are running the emulator from the command line, just specify an x86-based AVD: -
      emulator -avd <avd_name>
      -

      Note: You must provide an x86-based AVD configuration -name, otherwise VM acceleration will not be enabled.

      -
    • -
    • If you are running the emulator from Eclipse, run your Android application with an x86-based -AVD: -
        -
      1. In Eclipse, click your Android project folder and then select Run > Run -Configurations...
      2. -
      3. In the left panel of the Run Configurations dialog, select your Android -project run configuration or create a new configuration.
      4. -
      5. Click the Target tab.
      6. -
      7. Select the x86-based AVD you created previously.
      8. -
      9. Run your Android project using this run configuration.
      10. -
      -
    • -
    - -

    You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running -its installer.

    - -

    You can stop using the virtualization driver by uninstalling it. Re-run the installer or use -the Control Panel to remove the software.

    - - -

    Configuring VM Acceleration on Mac

    - -

    Virtual machine acceleration on a Mac requires the installation of the Intel Hardware Accelerated -Execution Manager (Intel HAXM) kernel extension to allow the Android emulator to make use of CPU -virtualization extensions. The kernel extension is compatible with Mac OS X Snow Leopard (version -10.6.0) and higher.

    - -

    To install the Intel HAXM kernel extension:

    - -
      -
    1. Start the Android SDK Manager, select Extras and then select Intel -Hardware Accelerated Execution Manager. -
    2. After the download completes, execute - {@code <sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.dmg}.
    3. -
    4. Double click the IntelHAXM.mpkg icon to begin installation.
    5. -
    6. Follow the on-screen instructions to complete installation.
    7. -
    8. After installation completes, confirm that the new kernel extension is operating correctly by -opening a terminal window and running the following command: -
      kextstat | grep intel
      -

      You should see a status message containing the following extension name, indicating that the - kernel extension is loaded:

      -
      com.intel.kext.intelhaxm
      -
    9. -
    - -

    To run an x86-based emulator with VM acceleration:

    -
      -
    • If you are running the emulator from the command line, just specify an x86-based AVD: -
      emulator -avd <avd_name>
      -

      Note: You must provide an x86-based AVD configuration -name, otherwise VM acceleration will not be enabled.

      -
    • -
    • If you are running the emulator from Eclipse, run your Android application with an x86-based -AVD: -
        -
      1. In Eclipse, click your Android project folder and then select Run > Run -Configurations...
      2. -
      3. In the left panel of the Run Configurations dialog, select your Android -project run configuration or create a new configuration.
      4. -
      5. Click the Target tab.
      6. -
      7. Select the x86-based AVD you created previously.
      8. -
      9. Run your Android project using this run configuration.
      10. -
      -
    • -
    - -

    You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running -the installer.

    - -

    You can stop using the virtualization kernel driver by uninstalling it. Before removing it, shut -down any running x86 emulators. To unload the virtualization kernel driver, run the following -command in a terminal window:

    - -
    sudo /System/Library/Extensions/intelhaxm.kext/Contents/Resources/uninstall.sh
    - -

    Configuring VM Acceleration on Linux

    - -

    Linux-based systems support virtual machine acceleration through the KVM software package. Follow -instructions for installing KVM on your -Linux system, and verify that KVM is enabled. In addition to following the installation -instructions, be aware of these configuration requirements:

    - -
      -
    • Running KVM requires specific user permissions, make sure you have sufficient permissions -according to the KVM installation instructions.
    • -
    • If you use another virtualization technology in your Linux platform, unload its kernel driver -before running the x86 emulator. For example, the VirtualBox driver program is {@code vboxdrv}.
    • -
    - -

    To run an x86-based emulator with VM acceleration:

    - -
      -
    • If you are running the emulator from the command line, start the emulator with an x86-based -AVD and include the KVM options: -
      emulator -avd <avd_name> -qemu -m 512 -enable-kvm
      -

      Note: You must provide an x86-based AVD configuration -name, otherwise VM acceleration will not be enabled.

      -
    • -
    • If you are running the emulator from Eclipse, run your Android application with an x86-based -AVD and include the KVM options: -
        -
      1. In Eclipse, click your Android project folder and then select Run > Run -Configurations...
      2. -
      3. In the left panel of the Run Configurations dialog, select your Android -project run configuration or create a new configuration.
      4. -
      5. Click the Target tab.
      6. -
      7. Select the x86-based AVD you created previously.
      8. -
      9. In the Additional Emulator Command Line Options field, enter: -
        -qemu -m 512 -enable-kvm
        -
      10. -
      11. Run your Android project using this run configuration.
      12. -
      -
    • -
    - -

    Important: When using the {@code -qemu} command line option, make sure -it is the last parameter in your command. All subsequent options are interpreted as qemu-specific -parameters.

    - - -

    SD Card Emulation

    - -

    You can create a disk image and then load it to the emulator at startup, to -simulate the presence of a user's SD card in the device. To do this, you can specify -an SD card image when you create an AVD, or you can use the mksdcard utility included -in the SDK.

    - -

    The following sections describe how to create an SD card disk image, how to copy -files to it, and how to load it in the emulator at startup.

    - -

    Note that you can only load a disk image at emulator startup. Similarly, you -can not remove a simulated SD card from a running emulator. However, you can -browse, send files to, and copy/remove files from a simulated SD card either -with adb or the emulator.

    - -

    The emulator supports emulated SDHC cards, so you can create an SD card image -of any size up to 128 gigabytes.

    - - -

    Creating an SD card image

    - -

    There are several ways of creating an SD card image. The easiest way is to use the -AVD Manager to create a new SD card by specifying a size when you create an AVD. -You can also use the {@code android} command line tool when creating an AVD. Just add the --c option to your command:

    - -
    android create avd -n <avd_name> -t <targetID> -c <size>[K|M]
    - -

    The -c option can also be used to to specify a path to an SD card -image for the new AVD. For more information, see Managing Virtual Devices -from the Command Line. -

    - -

    You can also use the mksdcard tool, included in the SDK, to create a FAT32 disk -image that you can load in the emulator at startup. You can access mksdcard in -the tools/ directory of the SDK and create a disk image like this:

    - -
    mksdcard <size> <file>
    - -

    For example:

    - -
    mksdcard 1024M sdcard1.iso
    - -

    For more information, see mksdcard.

    - - -

    Copying files to an SD card image

    - -

    Once you have created the disk image, you can copy files to it prior to -loading it in the emulator. To copy files, you can mount the image as a loop -device and then copy the files to it, or you can use a utility such as {@code mtools} to -copy the files directly to the image. The {@code mtools} package is available for Linux, -Mac, and Windows.

    - -

    Alternatively, you can use the {@code adb push} command to move files onto an SD card image -while it is loaded in an emulator. For more information see the {@code adb push} documentation.

    - -

    Loading an SD card image

    - -

    By default, the emulator loads the SD card image that is stored with the active -AVD (see the -avd startup option).

    - -

    Alternatively, you can start the emulator with the --sdcard flag and specify the name and path of your image (relative -to the current working directory):

    - -
    emulator -sdcard <filepath>
    - - -

    Working with Emulator Disk Images

    - -

    The emulator uses mountable disk images stored on your development machine to -simulate flash (or similar) partitions on an actual device. For example, it uses a -disk image containing an emulator-specific kernel, the Android system, a -ramdisk image, and writeable images for user data and simulated SD card.

    - -

    To run properly, the emulator requires access to a specific set of disk image -files. By default, the Emulator always looks for the disk images in the -private storage area of the AVD in use. If no images exist there when -the Emulator is launched, it creates the images in the AVD directory based on -default versions stored in the SDK.

    - -

    Note: The default storage location for -AVDs is in ~/.android/avd on OS X and Linux, C:\Documents and -Settings\<user>\.android\ on Windows XP, and -C:\Users\<user>\.android\ -on Windows Vista.

    - -

    To let you use alternate or custom versions of the image files, the emulator -provides startup options that override the default locations and filenames of -the image files. When you use one of these options, the emulator searches for the image -file under the image name or location that you specify; if it can not locate the -image, it reverts to using the default names and location.

    - -

    The emulator uses three types of image files: default image files, runtime -image files, and temporary image files. The sections below describe how to -override the location/name of each type of file.

    - -

    Default image files

    - -

    When the emulator launches, but does not find an existing user data image in -the active AVD's storage area, it creates a new one from a default version -included in the SDK. The default user data image is read-only. The image -files are read-only.

    - -

    The emulator provides the -system <dir> startup option to -let you override the location where the emulator looks for the default -user data image.

    - -

    The emulator also provides a startup option that lets you override the name -of the default user data image, as described in the following table. When you use the -option, the emulator looks in the default directory, or in a custom location -(if you specified -system <dir>).

    - - - - - - - - - - - - - - - - -
    NameDescriptionComments
    userdata.imgThe initial user-data disk imageOverride using -initdata <file>. Also see --data <file>, below.
    - -

    Runtime images: user data and SD card

    - -

    At runtime, the emulator reads and writes data to two disk images: a -user-data image and (optionally) an SD card image. These images emulate the user-data -partition and removable storage media on actual device.

    - -

    The emulator provides a default user-data disk image. At startup, the emulator -creates the default image as a copy of the system user-data image (user-data.img), -described above. The emulator stores the new image with the files of the active AVD.

    - - - -

    The emulator provides startup options to let you override the actual names and storage -locations of the runtime images to load, as described in the following table. When you use one -of these options, the emulator looks for the specified file(s) in the current working directory, -in the AVD directory, or in a custom location (if you specified a path with the filename).

    - - - - - - - - - - - - - - - - - - - -
    NameDescriptionComments
    userdata-qemu.imgAn image to which the emulator writes runtime user-data for a unique user.Override using -data <filepath>, where <filepath> is the -path the image, relative to the current working directory. If you supply a filename only, -the emulator looks for the file in the current working directory. If the file at <filepath> does -not exist, the emulator creates an image from the default userdata.img, stores it under the name you -specified, and persists user data to it at shutdown.
    sdcard.imgAn image representing an SD card inserted into the emulated device.Override using -sdcard <filepath>, where <filepath> is the -path the image, relative to the current working directory. If you supply a filename only, -the emulator looks for the file in the current working directory.
    - -

    User-Data Image

    - -

    Each emulator instance uses a writeable user-data image to store user- and -session-specific data. For example, it uses the image to store a unique user's -installed application data, settings, databases, and files.

    - -

    At startup, the emulator attempts to load a user-data image stored during -a previous session. It looks for the file in the current working directory, -in the AVD directory described in a previous section and at the custom location/name -that you specified at startup.

    - -
      -
    • If it finds a user-data image, it mounts the image and makes it available -to the system for reading and writing of user data.
    • -
    • If it does not find one, it creates an image by copying the system user-data -image (userdata.img), described above. At device power-off, the system persists -the user data to the image, so that it will be available in the next session. -Note that the emulator stores the new disk image at the location/name that you -specify in -data startup option.
    • -
    - -

    Note: Because of the AVD configurations used in the emulator, -each emulator instance gets its own dedicated storage. There is no longer a need -to use the -d option to specify an instance-specific storage area.

    - -

    SD Card

    - -

    Optionally, you can create a writeable disk image that the emulator can use -to simulate removeable storage in an actual device. For information about how to create an -emulated SD card and load it in the emulator, see SD Card Emulation

    - -

    You can also use the android tool to automatically create an SD Card image -for you, when creating an AVD. For more information, see Managing Virtual Devices with AVD -Manager. - - -

    Temporary Images

    - -

    The emulator creates two writeable images at startup that it deletes at -device power-off. The images are:

    - -
      -
    • A writable copy of the Android system image
    • -
    • The /cache partition image
    • -
    - -

    The emulator does not permit renaming the temporary system image or -persisting it at device power-off.

    - -

    The /cache partition image is initially empty, and is used by -the browser to cache downloaded web pages and images. The emulator provides an --cache <file>, which specifies the name of the file in which -to persist the /cache image at device power-off. If <file> - does not exist, the emulator creates it as an empty file.

    - -

    You can also disable the use of the cache partition by specifying the --nocache option at startup.

    - - -

    Emulator Networking

    - -

    The emulator provides versatile networking capabilities that you can use to -set up complex modeling and testing environments for your application. The -sections below introduce the emulator's network architecture and capabilities. -

    - -

    Network Address Space

    - -

    Each instance of the emulator runs behind a virtual router/firewall service -that isolates it from your development machine's network interfaces and settings -and from the internet. An emulated device can not see your development machine -or other emulator instances on the network. Instead, it sees only that it is -connected through Ethernet to a router/firewall.

    - -

    The virtual router for each instance manages the 10.0.2/24 network address -space — all addresses managed by the router are in the form of -10.0.2.<xx>, where <xx> is a number. Addresses within this space are -pre-allocated by the emulator/router as follows:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Network AddressDescription
    10.0.2.1Router/gateway address
    10.0.2.2Special alias to your host loopback interface (i.e., 127.0.0.1 on your -development machine)
    10.0.2.3First DNS server
    10.0.2.4 / 10.0.2.5 / 10.0.2.6Optional second, third and fourth DNS server (if any)
    10.0.2.15The emulated device's own network/ethernet interface
    127.0.0.1The emulated device's own loopback interface
    - -

    Note that the same address assignments are used by all running emulator -instances. That means that if you have two instances running concurrently on -your machine, each will have its own router and, behind that, each will have an -IP address of 10.0.2.15. The instances are isolated by a router and can -not see each other on the same network. For information about how to -let emulator instances communicate over TCP/UDP, see Connecting Emulator Instances.

    - -

    Also note that the address 127.0.0.1 on your development machine corresponds -to the emulator's own loopback interface. If you want to access services running -on your development machine's loopback interface (a.k.a. 127.0.0.1 on your -machine), you should use the special address 10.0.2.2 instead.

    - -

    Finally, note that each emulated device's pre-allocated addresses are -specific to the Android emulator and will probably be very different on real -devices (which are also very likely to be NAT-ed, i.e., behind a -router/firewall)

    - - -

    Local Networking Limitations

    - -

    Android applications running in an emulator can connect to the network available on your -workstation. However, they connect through the emulator, not directly to hardware, and the emulator -acts like a normal application on your workstation. This means that the emulator, and thus your -Android applications, are subject to some limitations:

    - -
      -
    • Communication with the emulated device may be blocked by a firewall -program running on your machine.
    • -
    • Communication with the emulated device may be blocked by another -(physical) firewall/router to which your machine is connected.
    • -
    - -

    The emulator's virtual router should be able to handle all outbound TCP and -UDP connections/messages on behalf of the emulated device, provided your -development machine's network environment allows it to do so. There are no -built-in limitations on port numbers or ranges except the one imposed by your -host operating system and network.

    - -

    Depending on the environment, the emulator may not be able to support other -protocols (such as ICMP, used for "ping") might not be supported. Currently, the -emulator does not support IGMP or multicast.

    - -

    Using Network Redirection

    - -

    To communicate with an emulator instance behind its virtual router, you need -to set up network redirection on the virtual router. Clients can then connect -to a specified guest port on the router, while the router directs traffic -to/from that port to the emulated device's host port.

    - -

    To set up the network redirection, you create a mapping of host and guest -ports/addresses on the the emulator instance. There are two ways to set up -network redirection: using emulator console commands and using the ADB tool, as -described below.

    - - -

    Setting up Redirection through the Emulator Console

    - -

    Each emulator instance provides a control console the you can connect to, to -issue commands that are specific to that instance. You can use the -redir console command to set up redirection as needed for an -emulator instance.

    - -

    First, determine the console port number for the target emulator instance. -For example, the console port number for the first emulator instance launched is -5554. Next, connect to the console of the target emulator instance, specifying -its console port number, as follows:

    - -
    telnet localhost 5554
    - -

    Once connected, use the redir command to work with redirection. -To add a redirection, use:

    - -
    add <protocol>:<host-port>:<guest-port>
    -
    - -

    where <protocol> is either tcp or udp, -and <host-port> and <guest-port> sets the -mapping between your own machine and the emulated system, respectively.

    - -

    For example, the following command sets up a redirection that handles all -incoming TCP connections to your host (development) machine on 127.0.0.1:5000 -and will pass them through to the emulated system's 10.0.2.15:6000.:

    - -
    redir add tcp:5000:6000
    - -

    To delete a redirection, you can use the redir del command. To -list all redirection for a specific instance, you can use redir -list. For more information about these and other console commands, see -Using the Emulator Console.

    - -

    Note that port numbers are restricted by your local environment. this typically -means that you cannot use host port numbers under 1024 without special -administrator privileges. Also, you won't be able to set up a redirection for a -host port that is already in use by another process on your machine. In that -case, redir generates an error message to that effect.

    - -

    Setting Up Redirection through ADB

    - -

    The Android Debug Bridge (ADB) tool provides port forwarding, an alternate -way for you to set up network redirection. For more information, see Forwarding Ports in the ADB -documentation.

    - -

    Note that ADB does not currently offer any way to remove a redirection, -except by killing the ADB server.

    - - -

    Configuring the Emulator's DNS Settings

    - -

    At startup, the emulator reads the list of DNS servers that your system is -currently using. It then stores the IP addresses of up to four servers on this -list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, -10.0.2.5 and 10.0.2.6 as needed.

    - -

    On Linux and OS X, the emulator obtains the DNS server addresses by parsing -the file /etc/resolv.conf. On Windows, the emulator obtains the -addresses by calling the GetNetworkParams() API. Note that this -usually means that the emulator ignores the content of your "hosts" file -(/etc/hosts on Linux/OS X, %WINDOWS%/system32/HOSTS - on Windows).

    - -

    When starting the emulator at the command line, you can also use the --dns-server <serverList> option to manually specify the -addresses of DNS servers to use, where <serverList> is a comma-separated -list of server names or IP addresses. You might find this option useful if you -encounter DNS resolution problems in the emulated network (for example, an -"Unknown Host error" message that appears when using the web browser).

    - - -

    Using the Emulator with a Proxy

    - -

    If your emulator must access the Internet through a proxy server, you can use -the -http-proxy <proxy> option when starting the emulator, to -set up the appropriate redirection. In this case, you specify proxy information -in <proxy> in one of these formats:

    - -
    http://<machineName>:<port>
    - -

    or

    - -
    http://<username>:<password>@<machineName>:<port>
    - -

    The -http-proxy option forces the emulator to use the specified -HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not -currently supported.

    - -

    Alternatively, you can define the environment variable -http_proxy to the value you want to use for -<proxy>. In this case, you do not need to specify a value for -<proxy> in the -http-proxy command — the -emulator checks the value of the http_proxy environment variable at -startup and uses its value automatically, if defined.

    - -

    You can use the -verbose-proxy option to diagnose proxy -connection problems.

    - - -

    Interconnecting Emulator Instances

    - -

    To allow one emulator instance to communicate with another, you must set up -the necessary network redirection as illustrated below.

    - -

    Assume that your environment is

    - -
      -
    • A is you development machine
    • -
    • B is your first emulator instance, running on A
    • -
    • C is your second emulator instance, also running on A
    • -
    - -

    and you want to run a server on B, to which C will connect, here is how you -could set it up:

    - -
      -
    1. Set up the server on B, listening to -10.0.2.15:<serverPort>
    2. -
    3. On B's console, set up a redirection from -A:localhost:<localPort> to -B:10.0.2.15:<serverPort>
    4. -
    5. On C, have the client connect to 10.0.2.2:<localPort>
    6. -
    - -

    For example, if you wanted to run an HTTP server, you can select -<serverPort> as 80 and <localPort> as -8080:

    - -
      -
    • B listens on 10.0.2.15:80
    • -
    • On B's console, issue redir add tcp:8080:80
    • -
    • C connects to 10.0.2.2:8080
    • -
    - -

    Sending a Voice Call or SMS to Another Emulator Instance

    - -

    The emulator automatically forwards simulated voice calls and SMS messages from one instance to -another. To send a voice call or SMS, use the dialer application or SMS application, respectively, -from one of the emulators.

    - -

    To initiate a simulated voice call to another emulator instance:

    -
      -
    1. Launch the dialer application on the originating emulator instance.
    2. -
    3. As the number to dial, enter the console port number of the instance you'd like to call. You can determine - the console port number of the target instance by checking its window title, where the - console port number is reported as "Android Emulator (<port>).
    4. -
    5. Press "Dial". A new inbound call appears in the target emulator instance.
    6. -
    - -

    To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance.

    - -

    You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see Telephony Emulation and SMS Emulation. - - -

    Using the Emulator Console

    - -

    Each running emulator instance provides a console that lets you query and control the emulated -device environment. For example, you can use the console to manage port redirection, network -characteristics, and telephony events while your application is running on the emulator. To -access the console and enter commands, use telnet to connect to the console's port number.

    - -

    To connect to the console of any running emulator instance at any time, use this command:

    - -
    telnet localhost <console-port>
    - -

    An emulator instance occupies a pair of adjacent ports: a console port and an {@code adb} port. -The port numbers differ by 1, with the {@code adb} port having the higher port number. The console -of the first emulator instance running on a given machine uses console port 5554 and {@code adb} -port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, -5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.

    - -

    To connect to the emulator console, you must specify a valid console port. If multiple emulator instances are running, you need to determine the console port of the emulator instance you want to connect to. You can find the instance's console port listed in the title of the instance window. For example, here's the window title for an instance whose console port is 5554:

    - -

    Android Emulator (5554)

    - -

    Alternatively, you can use the adb devices command, which prints a list of running emulator instances and their console port numbers. For more information, see Querying for Emulator/Device Instances in the adb documentation.

    - -

    Note: The emulator listens for connections on ports 5554-5587 and accepts connections only from localhost.

    - -

    Once you are connected to the console, you can then enter help [command] to see a list of console commands and learn about specific commands.

    - -

    To exit the console session, use quit or exit.

    - -

    The following sections below describe the major functional areas of the console.

    - - -

    Port Redirection

    - -

    You can use the console to add and remove port redirection while the emulator is running. After -you connect to the console, manage port redirection by entering the following command:

    - -
    redir <list|add|del> 
    - -

    The redir command supports the subcommands listed in the table below.

    - - - - - - - - - - - - - - - - - - - - - - - - -
    Subcommand - DescriptionComments
    listList the current port redirection. 
    add <protocol>:<host-port>:<guest-port>Add a new port redirection.
    • <protocol> must be either "tcp" or "udp"
    • -
    • <host-port> is the port number to open on the host
    • -
    • <guest-port> is the port number to route data to on the emulator/device
    • -
    del <protocol>:<host-port>Delete a port redirection.The meanings of <protocol> and <host-port> are listed in the previous row.
    - - -

    Geo Location Provider Emulation

    - -

    You can use the console to set the geographic location reported to the applications running -inside an emulator. Use the geo command to send a simple GPS fix to the -emulator, with or without NMEA 1083 formatting:

    - -
    geo <fix|nmea>
    - -

    The geo command supports the subcommands listed in the table below.

    - - - - - - - - - - - - - - - - - - -
    SubcommandDescriptionComments
    fix <longitude> <latitude> [<altitude>]Send a simple GPS fix to the emulator instance.Specify longitude and latitude in decimal degrees. Specify altitude in meters.
    nmea <sentence>Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem.<sentence> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported.
    - -

    You can issue the geo command as soon as an emulator instance is running. The -emulator sets the location you enter by creating a mock location provider. This provider responds to -location listeners set by applications, and also supplies the location to the {@link -android.location.LocationManager}. Any application can query the location manager to obtain the -current GPS fix for the emulated device by calling: - -

    LocationManager.getLastKnownLocation("gps")
    - -

    For more information about the Location Manager, see {@link android.location.LocationManager}. -

    - -

    Hardware Events Emulation

    - -

    The {@code event} console commands sends hardware events to the emulator. The syntax for this -command is as follows:

    - -
    event <send|types|codes|text>
    - -

    The event command supports the subcommands listed in the table below.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Subcommand - DescriptionComments
    send <type>:<code>:<value> [...]Send one or more events to the Android kernel. You can use text names or integers for <type> and <value>.
    typesList all <type> string aliases supported by the event subcommands. 
    codes <type>List all <codes> string aliases supported by the event - subcommands for the specified <type>. 
    event text <message>Simulate keypresses to send the specified string of characters as a message,The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently.
    - - -

    Device Power Characteristics

    - -

    The {@code power} command controls the power state reported by the emulator to applications. The -syntax for this command is as follows:

    - -
    power <display|ac|status|present|health|capacity>
    - -

    The event command supports the subcommands listed in the table below.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Subcommand DescriptionComments
    displayDisplay battery and charger state. 
    ac <on|off>Set AC charging state to on or off.  
    status <unknown|charging|discharging|not-charging|full>Change battery status as specified. 
    present <true|false>Set battery presence state. 
    health <unknown|good|overheat|dead|overvoltage|failure>Set battery health state. 
    power health <percent>Set remaining battery capacity state (0-100). 
    - - -

    Network Status

    - -

    You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use the netstatus command. Here's an example of the command and its output.

    - -
    network status
    -
    - - -

    Network Delay Emulation

    - -

    The emulator lets you simulate various network latency levels, so that you can test your -application in an environment more typical of the actual conditions in which it will run. You can -set a latency level or range at emulator startup or you can use the console to change the latency, -while the application is running in the emulator.

    - -

    To set latency at emulator startup, use the -netdelay emulator option with a -supported <delay> value, as listed in the table below. Here are some -examples:

    - -
    emulator -netdelay gprs
    -emulator -netdelay 40 100
    - -

    To make changes to network delay while the emulator is running, connect to the console and use -the netdelay command with a supported <delay> value from the table -below.

    - -
    network delay gprs
    - -

    The format of network <delay> is one of the following (numbers are milliseconds):

    - - - - - - - - - - - - - - - - - - - - - - - -
    ValueDescriptionComments
    gprsGPRS(min 150, max 550)
    edgeEDGE/EGPRS(min 80, max 400)
    umtsUMTS/3G(min 35, max 200)
    noneNo latency(min 0, max 0)
    <num>Emulate an exact latency (milliseconds). 
    <min>:<max>Emulate an specified latency range (min, max milliseconds). 
    - - -

    Network Speed Emulation

    - -

    The emulator also lets you simulate various network transfer rates. -You can set a transfer rate or range at emulator startup or you can use the console to change the -rate, while the application is running in the emulator.

    - -

    To set the network speed at emulator startup, use the -netspeed emulator option with a supported -<speed> value, as listed in the table below. Here are some examples:

    - -
    emulator -netspeed gsm
    -emulator -netspeed 14.4 80
    - -

    To make changes to network speed while the emulator is running, connect to the console and use -the netspeed command with a supported <speed> value from the table -below.

    - -
    network speed 14.4 80
    - -

    The format of network <speed> is one of the following (numbers are -kilobits/sec):

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ValueDescriptionComments
    gsmGSM/CSD(Up: 14.4, down: 14.4)
    hscsdHSCSD(Up: 14.4, down: 43.2)
    gprsGPRS(Up: 40.0, down: 80.0)
    edgeEDGE/EGPRS(Up: 118.4, down: 236.8)
    umtsUMTS/3G(Up: 128.0, down: 1920.0)
    hsdpaHSDPA(Up: 348.0, down: 14400.0)
    fullno limit(Up: 0.0, down: 0.0)
    <num>Set an exact rate used for both upload and download.
    <up>:<down>Set exact rates for upload and download separately.
    - - -

    Telephony Emulation

    - -

    The Android emulator includes its own GSM emulated modem that lets you simulate telephony -functions in the emulator. For example, you can simulate inbound phone calls, establish data -connections and terminate them. The Android system handles simulated calls exactly as it would -actual calls. The emulator does not support call audio.

    - -

    You can use the {@code gsm} command to access the emulator's telephony functions after connecting -to the console. The syntax for this command is as follows:

    - -
    gsm <call|accept|busy|cancel|data|hold|list|voice|status> 
    - -

    The gsm command supports the subcommands listed in the table below.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Subcommand DescriptionComments
    call <phonenumber>Simulate an inbound phone call from <phonenumber>. 
    accept <phonenumber>Accept an inbound call from <phonenumber> and change the call's state "active".You can change a call's state to "active" only if its current state is "waiting" or "held".
    busy <phonenumber>Close an outbound call to <phonenumber> and change the call's state to "busy".You can change a call's state to "busy" only if its current state is "waiting".
    cancel <phonenumber>Terminate an inbound or outbound phone call to/from <phonenumber>. 
    data <state>Change the state of the GPRS data connection to <state>.Supported <state> values are:
    -
      -
    • unregistered -- No network available
    • -
    • home -- On local network, non-roaming
    • -
    • roaming -- On roaming network
    • -
    • searching -- Searching networks
    • -
    • denied -- Emergency calls only
    • -
    • off -- Same as 'unregistered'
    • -
    • on -- same as 'home'
    • -
    -
    holdChange the state of a call to "held". You can change a call's state to "held" only if its current state is "active" or "waiting".
    listList all inbound and outbound calls and their states. 
    voice <state>Change the state of the GPRS voice connection to <state>.Supported <state> values are:
    -
      -
    • unregistered -- No network available
    • -
    • home -- On local network, non-roaming
    • -
    • roaming -- On roaming network
    • -
    • searching -- Searching networks
    • -
    • denied -- Emergency calls only
    • -
    • off -- Same as 'unregistered'
    • -
    • on -- Same as 'home'
    • -
    -
    statusReport the current GSM voice/data state.Values are those described for the voice and data commands.
    - - -

    SMS Emulation

    - -

    The Android emulator console lets you generate an SMS message and direct it to an emulator -instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using -the following command:

    - -
    sms send <senderPhoneNumber> <textmessage>
    - -

    where <senderPhoneNumber> contains an arbitrary numeric string.

    - -

    The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type.

    - - -

    VM State

    - -

    You can use the vm command to control the VM on an emulator instance. The syntax for -this command is as follows:

    - -
    vm <start|stop|status>
    - -

    The vm command supports the subcommands listed in the table below.

    - - - - - - - - - - - - - - - - - - - - - - -
    SubcommandDescriptionComments
    startStart the VM on the instance.  
    stopStop the VM on the instance.  
    startDisplay the current status of the VM (running or stopped).  
    - - -

    Emulator Window

    - -

    You can use the window command to manage the emulator window. The syntax for this -command is as follows:

    - -
    window <scale>
    - -

    The vm command supports the subcommands listed in the table below.

    - - - - - - - - - - - - -
    SubcommandDescriptionComments
    scale <scale>Scale the emulator window.A number between 0.1 and 3 that sets the scaling factor. You can - also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" - tells the emulator to select the best window size.
    - - -

    Terminating an Emulator Instance

    - -

    You can terminate an emulator instance through the console, using the kill command.

    - - -

    Emulator Limitations

    - -

    The functional limitations of the emulator include:

    -
      -
    • No support for placing or receiving actual phone calls. You can simulate phone calls (placed - and received) through the emulator console, however.
    • -
    • No support for USB connections
    • -
    • No support for device-attached headphones
    • -
    • No support for determining network connected state
    • -
    • No support for determining battery charge level and AC charging state
    • -
    • No support for determining SD card insert/eject
    • -
    • No support for Bluetooth
    • -
    - - -

    Troubleshooting Emulator Problems

    - -

    The {@code adb} utility sees the emulator as an actual physical device. For this reason, you -might have to use the {@code -d} flag with some common {@code adb} commands, such as -install. The {@code -d} flag lets you specify which of several connected devices to use -as the target of a command. If you don't specify {@code -d}, the emulator targets the first -device in its list. For more information about {@code adb}, see Android Debug Bridge.

    - -

    For emulators running on Mac OS X, if you see an error {@code Warning: No DNS servers found} -when starting the emulator, check to see whether you have an /etc/resolv.conf file. If -not, please run the following line in a command window:

    -
    ln -s /private/var/run/resolv.conf /etc/resolv.conf
    - -

    See Frequently Asked Questions for more -troubleshooting information.

    diff --git a/docs/html/guide/developing/devices/index.jd b/docs/html/guide/developing/devices/index.jd deleted file mode 100644 index 64651a1ec907..000000000000 --- a/docs/html/guide/developing/devices/index.jd +++ /dev/null @@ -1,78 +0,0 @@ -page.title=Managing Virtual Devices -@jd:body - - -

    An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual - device by defining hardware and software options to be emulated by the Android Emulator.

    - -

    The easiest way to create an AVD is to use the graphical AVD Manager, which you launch - from Eclipse by clicking Window > AVD Manager. You can also start the AVD -Manager from the command line by calling the android tool with the avd -options, from the <sdk>/tools/ directory.

    - -

    You can also create AVDs on the command line by passing the android tool options. - For more information on how to create AVDs in this manner, see Managing Virtual - Devices from the Command Line.

    - -

    An AVD consists of:

    - -
      -
    • A hardware profile: Defines the hardware features of the virtual - device. For example, you can define whether the device has a camera, whether it uses a physical - QWERTY keyboard or a dialing pad, how much memory it has, and so on.
    • - -
    • A mapping to a system image: You can define what version of the Android platform will run - on the virtual device. You can choose a version of the standard Android platform or the system - image packaged with an SDK add-on.
    • - -
    • Other options: You can specify the emulator skin you want to use with the AVD, which lets - you control the screen dimensions, appearance, and so on. You can also specify the emulated SD - card to use with the AVD.
    • - -
    • A dedicated storage area on your development machine: the device's user data (installed - applications, settings, and so on) and emulated SD card are stored in this area.
    • -
    - -

    You can create as many AVDs as you need, based on the types of device you want to model. - To thoroughly test your application, you should create an AVD for each general device configuration - (for example, different screen sizes and platform versions) with which your application is compatible - and test your application on each one.

    - -

    Keep these points in mind when you are selecting a system image target for your AVD:

    - -
      -
    • The API Level of the target is important, because your application will not be able to run - on a system image whose API Level is less than that required by your application, as specified - in the - minSdkVersion attribute of the application's manifest file. For more - information about the relationship between system API Level and application - minSdkVersion, see Specifying Minimum System API Version.
    • - -
    • You should create at least one AVD that uses a target whose API Level is greater than that required - by your application, because it allows you to test the - forward-compatibility of your application. Forward-compatibility testing ensures that, when - users who have downloaded your application receive a system update, your application will - continue to function normally.
    • - -
    • If your application declares a - uses-library - element in its manifest file, the application can only run on a system image in which that external - library is present. If you want to run your application on an emulator, create an AVD that - includes the required library. Usually, you must create such an AVD using an Add-on component for the - AVD's platform (for example, the Google APIs Add-on contains the Google Maps library).
    • -
    - -

    To learn how to manage AVDs using a graphical tool, read Managing AVDs with AVD Manager. To -learn how to manage AVDs on the command line, read - Managing AVDs - from the Command Line.

    - - - - - - diff --git a/docs/html/guide/developing/devices/managing-avds-cmdline.jd b/docs/html/guide/developing/devices/managing-avds-cmdline.jd deleted file mode 100644 index 867433452a7b..000000000000 --- a/docs/html/guide/developing/devices/managing-avds-cmdline.jd +++ /dev/null @@ -1,369 +0,0 @@ -page.title=Managing AVDs from the Command Line -parent.title=Managing Virtual Devices -parent.link=index.html -@jd:body - - - - -

    The android tool lets you manage AVDs on the command line. For a complete reference -of the command line options that you can use, see the reference for the -android tool.

    - - - -

    Listing Targets

    - -

    To generate a list of system image targets, use this command:

    - -
    android list targets
    - -

    The android tool scans the <sdk>/platforms/ and -<sdk>/add-ons/ directories looking for valid system images and -then generates the list of targets. Here's an example of the command output: -

    - -
    Available Android targets:
    -id: 1 or "android-3"
    -     Name: Android 1.5
    -     Type: Platform
    -     API level: 3
    -     Revision: 4
    -     Skins: QVGA-L, HVGA-L, HVGA (default), HVGA-P, QVGA-P
    -id: 2 or "android-4"
    -     Name: Android 1.6
    -     Type: Platform
    -     API level: 4
    -     Revision: 3
    -     Skins: QVGA, HVGA (default), WVGA800, WVGA854
    -id: 3 or "android-7"
    -     Name: Android 2.1-update1
    -     Type: Platform
    -     API level: 7
    -     Revision: 2
    -     Skins: QVGA, WQVGA400, HVGA (default), WVGA854, WQVGA432, WVGA800
    -id: 4 or "android-8"
    -     Name: Android 2.2
    -     Type: Platform
    -     API level: 8
    -     Revision: 2
    -     Skins: WQVGA400, QVGA, WVGA854, HVGA (default), WVGA800, WQVGA432
    -id: 5 or "android-9"
    -     Name: Android 2.3
    -     Type: Platform
    -     API level: 9
    -     Revision: 1
    -     Skins: HVGA (default), WVGA800, WQVGA432, QVGA, WVGA854, WQVGA400
    -
    - - - -

    Creating AVDs

    - -

    In addition to creating AVDs with the -AVD Manager user interface, -you can also create them by passing in command line arguments to the android tool. -

    - -

    Open a terminal window and change to -the <sdk>/tools/ directory, if needed.

    - -

    To create each AVD, you issue the command android create avd, -with options that specify a name for the new AVD and the system image you want -to run on the emulator when the AVD is invoked. You can specify other options on -the command line also, such as the emulated SD card size, the emulator skin, or a custom -location for the user data files.

    - -

    Here's the command-line usage for creating an AVD:

    - -
    android create avd -n <name> -t <targetID> [-<option> <value>] ... 
    - -

    You can use any name you want for the AVD, but since you are likely to be -creating multiple AVDs, you should choose a name that lets you recognize the -general characteristics offered by the AVD. The target ID is an integer assigned by the -android tool. The target ID is not derived from the system image name, -version, or API Level, or other attribute, so you need to run the android list targets -command to list the target ID of each system image. You should do this before you run -the android create avd command. See the android -tool documentation for more information on the command line options.

    - - -

    When you've selected the target you want to use and made a note of its ID, -use the android create avd command to create the AVD, supplying the -target ID as the -t argument. Here's an example that creates an -AVD with name "my_android1.5" and target ID "2" (the standard Android 1.5 -system image in the list above):

    - -
    android create avd -n my_android1.5 -t 2
    - -

    If the target you selected was a standard Android system image ("Type: -platform"), the android tool next asks you whether you want to -create a custom hardware profile.

    -
    Android 1.5 is a basic Android platform.
    -Do you wish to create a custom hardware profile [no]
    - -

    If you want to set custom hardware emulation options for the AVD, enter -"yes" and set values as needed. If you want to use the default hardware -emulation options for the AVD, just press the return key (the default is "no"). -The android tool creates the AVD with name and system image mapping you -requested, with the options you specified. For more information, see -Setting Hardware Emulation Options. - -

    Note: If you are creating an AVD whose target is an SDK add-on, the -android tool does not allow you to set hardware emulation options. -It assumes that the provider of the add-on has set emulation options -appropriately for the device that the add-on is modeling, and so prevents you -from resetting the options.

    - - -

    Customize the device resolution or density

    - -

    When testing your application, we recommend that you test your application in several different -AVDs, using different screen configurations (different combinations of size and density). In -addition, you should set up the AVDs to run at a physical size that closely matches an actual -device.

    - -

    To set up your AVDs for a specific resolution or density, follow these steps:

    - -
      -
    1. Use the create avd command to create a new AVD, specifying -the --skin option with a value that references either a default -skin name (such as "WVGA800") or a custom skin resolution (such as 240x432). -Here's an example: -
      android create avd -n <name> -t <targetID> --skin WVGA800
      -
    2. -
    3. To specify a custom density for the skin, answer "yes" when asked whether -you want to create a custom hardware profile for the new AVD.
    4. -
    5. Continue through the various profile settings until the tool asks you to -specify "Abstracted LCD density" (hw.lcd.density). Enter an appropriate -value, such as "120" for a low-density screen, "160" for a medium density screen, -or "240" for a high-density screen.
    6. -
    7. Set any other hardware options and complete the AVD creation.
    8. -
    - -

    In the example above (WVGA medium density), the new AVD will emulate a 5.8" -WVGA screen.

    - -

    As an alternative to adjusting the emulator skin configuration, you can use -the emulator skin's default density and add the -dpi-device option -to the emulator command line when -starting the AVD. For example:

    - -
    emulator -avd WVGA800 -scale 96dpi -dpi-device 160
    - - - -

    Default location of AVD files

    - -

    When you create an AVD, the android tool creates a dedicated directory for it -on your development computer. The directory contains the AVD configuration file, -the user data image and SD card image (if available), and any other files -associated with the device. Note that the directory does not contain a system -image — instead, the AVD configuration file contains a mapping to the -system image, which it loads when the AVD is launched.

    - -

    The android tool also creates an <AVD_name>.ini file for the AVD at the -root of the .android/avd/ directory on your computer. The file specifies the -location of the AVD directory and always remains at the root the .android -directory.

    - -

    By default, the android tool creates the AVD directory inside -~/.android/avd/ (on Linux/Mac), C:\Documents and -Settings\<user>\.android\ on Windows XP, and -C:\Users\<user>\.android\ on Windows 7 and Vista. -If you want to use a custom location for the AVD directory, you -can do so by using the -p <path> option when -you create the AVD:

    - -
    android create avd -n my_android1.5 -t 2 -p path/to/my/avd
    - -

    If the .android directory is hosted on a network drive, we recommend using -the -p option to place the AVD directory in another location. -The AVD's .ini file remains in the .android directory on the network -drive, regardless of the location of the AVD directory. - - -

    Setting hardware emulation options

    - -

    When you are creating a new AVD that uses a standard Android system image ("Type: -platform"), the android tool lets you set hardware emulation -options for virtual device. The table below lists the options available and the -default values, as well as the names of properties that store the emulated -hardware options in the AVD's configuration file (the config.ini file in the -AVD's local directory).

    - -

    Table 1. Available hardware profile options for AVDs and -the default values

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CharacteristicDescriptionProperty
    Device ram sizeThe amount of physical RAM on the device, in megabytes. Default value is "96". -hw.ramSize
    Touch-screen supportWhether there is a touch screen or not on the device. Default value is "yes".hw.touchScreen - -
    Trackball support Whether there is a trackball on the device. Default value is "yes".hw.trackBall
    Keyboard supportWhether the device has a QWERTY keyboard. Default value is "yes".hw.keyboard
    DPad supportWhether the device has DPad keys. Default value is "yes".hw.dPad
    GSM modem supportWhether there is a GSM modem in the device. Default value is "yes".hw.gsmModem
    Camera supportWhether the device has a camera. Default value is "no".hw.camera
    Maximum horizontal camera pixelsDefault value is "640".hw.camera.maxHorizontalPixels
    Maximum vertical camera pixelsDefault value is "480".hw.camera.maxVerticalPixels
    GPS supportWhether there is a GPS in the device. Default value is "yes".hw.gps
    Battery supportWhether the device can run on a battery. Default value is "yes".hw.battery
    AccelerometerWhether there is an accelerometer in the device. Default value is "yes".hw.accelerometer
    Audio recording supportWhether the device can record audio. Default value is "yes".hw.audioInput
    Audio playback supportWhether the device can play audio. Default value is "yes".hw.audioOutput
    SD Card supportWhether the device supports insertion/removal of virtual SD Cards. Default value is "yes".hw.sdCard
    Cache partition supportWhether we use a /cache partition on the device. Default value is "yes".disk.cachePartition
    Cache partition sizeDefault value is "66MB".disk.cachePartition.size
    Abstracted LCD densitySets the generalized density characteristic used by the AVD's screen. Default value is "160".hw.lcd.density
    Trackball supportWhether there is a trackball present.hw.trackBall
    - - -

    Moving an AVD

    - -

    If you want to move or rename an AVD, you can do so using this command:

    - -
    android move avd -n <name> [-<option> <value>] ...
    - -

    Updating an AVD

    - -

    If, for any reason, the platform/add-on root folder has its name changed (maybe because the user has installed an update of the platform/add-on) then the AVD will not be able to load the system image that it is mapped to. In this case, the android list targets command will produce this output: - -

    The following Android Virtual Devices could not be loaded: 
    -Name: foo 
    -Path: <path>/.android/avd/foo.avd 
    -Error: Invalid value in image.sysdir. Run 'android update avd -n foo' 
    - -

    To fix this error, use the android update avd command to recompute the path to the system images.

    - -

    Deleting an AVD

    - -

    You can use the android tool to delete an AVD. Here is the command usage:

    - -
    android delete avd -n <name> 
    - -

    When you issue the command, the android tool looks for an AVD matching the -specified name deletes the AVD's directory and files.

    diff --git a/docs/html/guide/developing/devices/managing-avds.jd b/docs/html/guide/developing/devices/managing-avds.jd deleted file mode 100644 index 412bd913d613..000000000000 --- a/docs/html/guide/developing/devices/managing-avds.jd +++ /dev/null @@ -1,237 +0,0 @@ -page.title=Managing AVDs with AVD Manager -parent.title=Managing Virtual Devices -parent.link=index.html -@jd:body - -
    -
    -

    In this document

    - -
      -
    1. Creating an AVD -
        -
      1. Hardware options
      2. -
      -
    2. -
    -
    -
    - -

    The AVD Manager is an easy to use user interface to manage your AVD (Android Virtual Device) - configurations. An AVD is a device configuration for the Android emulator that allows you to - model different configurations of Android-powered devices. When you start the AVD Manager in Eclipse - or run the android tool on the command line, you will see the AVD Manager as shown in - figure 1:

    - - - -

    Figure 1. Screenshot of the AVD Manager.

    - -

    From the main screen, you can create, delete, repair and start AVDs as well as see the details - of each AVD.

    - - -

    Creating an AVD

    - -

    You can create as many AVDs as you would like to test on. It is recommended that you test your - applications on all API levels higher than the target API level for your application.

    - -

    To create an AVD:

    - -
      -
    1. Start the AVD Manager: - -
        -
      • In Eclipse: select Window > AVD Manager, or click - the AVD Manager icon in the Eclipse toolbar.
      • - -
      • In other IDEs: Navigate to your SDK's tools/ directory and execute the - android tool with no arguments.
      • -
      -
    2. - -
    3. In the Virtual Devices panel, you'll see a list of existing AVDs. Click - New to create a new AVD. The Create New AVD dialog appears.

      - - AVD Dialog -

      Figure 2. Screenshot of the Create AVD window

      -
    4. - -
    5. Fill in the details for the AVD. - -

      Give it a name, a platform target, an SD card size, and a skin (HVGA is default). You can - also add specific hardware features of the emulated device by clicking the - New... button and selecting the feature. For a list of hardware features, - see Hardware options.

      - -

      Note: Be sure to define a target for your AVD that satisfies - your application's Build Target (the AVD platform target must have an API Level equal to or - greater than the API Level that your application compiles against).

      -
    6. - -
    7. Click Create AVD.
    8. -
    - -

    Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or - launch an emulator with the AVD by selecting a device and clicking Start.

    - -

    Hardware options

    -

    If you are creating a new AVD, you can specify the following hardware options for the AVD -to emulate:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CharacteristicDescriptionProperty
    Device ram sizeThe amount of physical RAM on the device, in megabytes. Default value is "96".hw.ramSize
    Touch-screen supportWhether there is a touch screen or not on the device. Default value is "yes".hw.touchScreen
    Trackball supportWhether there is a trackball on the device. Default value is "yes".hw.trackBall
    Keyboard supportWhether the device has a QWERTY keyboard. Default value is "yes".hw.keyboard
    DPad supportWhether the device has DPad keys. Default value is "yes".hw.dPad
    GSM modem supportWhether there is a GSM modem in the device. Default value is "yes".hw.gsmModem
    Camera supportWhether the device has a camera. Default value is "no".hw.camera
    Maximum horizontal camera pixelsDefault value is "640".hw.camera.maxHorizontalPixels
    Maximum vertical camera pixelsDefault value is "480".hw.camera.maxVerticalPixels
    GPS supportWhether there is a GPS in the device. Default value is "yes".hw.gps
    Battery supportWhether the device can run on a battery. Default value is "yes".hw.battery
    AccelerometerWhether there is an accelerometer in the device. Default value is "yes".hw.accelerometer
    Audio recording supportWhether the device can record audio. Default value is "yes".hw.audioInput
    Audio playback supportWhether the device can play audio. Default value is "yes".hw.audioOutput
    SD Card supportWhether the device supports insertion/removal of virtual SD Cards. Default value is - "yes".hw.sdCard
    Cache partition supportWhether we use a /cache partition on the device. Default value is "yes".disk.cachePartition
    Cache partition sizeDefault value is "66MB".disk.cachePartition.size
    Abstracted LCD densitySets the generalized density characteristic used by the AVD's screen. Default value is - "160".hw.lcd.density
    - diff --git a/docs/html/guide/developing/eclipse-adt.html b/docs/html/guide/developing/eclipse-adt.html deleted file mode 100644 index 879a35635ba7..000000000000 --- a/docs/html/guide/developing/eclipse-adt.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/developing/index.jd b/docs/html/guide/developing/index.jd deleted file mode 100644 index 3af4a8c06ca7..000000000000 --- a/docs/html/guide/developing/index.jd +++ /dev/null @@ -1,150 +0,0 @@ -page.title=Introduction -@jd:body - -

    Developing applications for Android devices is facilitated by a group of tools that are - provided with the SDK. You can access these tools through an Eclipse plugin called ADT (Android - Development Tools) or from the command line. Developing with Eclipse is the preferred method because - it can directly invoke the tools that you need while developing applications.

    - -

    However, you may choose to develop with another IDE or a simple text editor and invoke the - tools on the command line or with scripts. This is a less streamlined way to develop because you - will sometimes have to call command line tools manually, but you will have access to the same - number of features that you would have in Eclipse.

    - -
    - Development process for Android applications -

    - Figure 1. The development process for Android applications. -

    -
    - -

    The basic steps for developing applications (with or without Eclipse) are shown in figure 1. The -development steps encompass four development phases, which include:

    - -
      -
    • Setup -

      During this phase you install and set up your development environment. You also create - Android Virtual Devices (AVDs) and connect hardware devices on which you can install your - applications.

      -

      See Managing Virtual Devices - and Using Hardware Devices for more - information. -

    • -
    • Development -

      During this phase you set up and develop your Android project, which contains all of the - source code and resource files for your application. For more informations, see - Create an Android project.

      -
    • -
    • Debugging and Testing -

      During this phase you build your project into a debuggable .apk package that you - can install and run on the emulator or an Android-powered device. If you are using Eclipse, - builds are generated each time you project is saved. If you're using another IDE, - you can build your project using Ant and install it on a device using - adb. For more information, see - Build and run your application.

      -

      Next, you debug your application using a JDWP-compliant debugger along with the debugging - and logging tools that are provided with the Android SDK. Eclipse already comes packaged with - a compatible debugger. For more information see, - Debug your application with the - SDK debugging and logging tools.

      -

      Last, you test your application using various Android SDK testing tools. For more - information, see Test your application - with the Testing and Instrumentation framework.

      -
    • -
    • Publishing -

      During this phase you configure and build your application for release and distribute your - application to users. For more information, see - Publishing Overview.

      -
    • -
    - -

    Essential command line tools

    - -

    When developing in IDEs or editors other than Eclipse, be familiar with - all of the tools below, because you will have to run them from the command line.

    - -
    -
    android
    - -
    Create and update Android projects and create, move, and delete AVDs.
    - -
    Android Emulator
    - -
    Run your Android applications on an emulated Android platform.
    - -
    Android Debug Bridge
    - -
    Interface with your emulator or connected device (install apps, shell the device, issue - commands, etc.).
    -
    - -

    In addition to the above tools that are included with the SDK, you need the following open - source and third-party tools:

    - -
    -
    Ant
    - -
    To compile and build your Android project into an installable .apk file.
    - -
    Keytool
    - -
    To generate a keystore and private key, used to sign your .apk file. Keytool is part of the - JDK.
    - -
    Jarsigner (or similar signing tool)
    - -
    To sign your .apk file with a private key generated by Keytool. Jarsigner is part of the - JDK.
    -
    - -

    If you are using Eclipse and ADT, tools such as adb and android - are automatically called by Eclipse and ADT so you don't have to manually invoke these tools. - You need to be familiar with adb, however, because certain functions are not -accessible from - Eclipse, such as the adb shell commands. You might also need to call Keytool and -Jarsigner to - sign your applications, but you can set up Eclipse to do this automatically as well.

    - -

    For more information on the tools provided with the Android SDK, see the - Tools section of the documentation.

    - -

    Other Third-Party Development Tools

    -

    - The tools described in this section are not developed by the Android SDK team. The Android Dev Guide - does not provide documentation for these tools. Please refer to the linked documents in each - section for documentation. -

    -

    Developing in IntelliJ IDEA

    -
    -The IntelliJ graphical user interface -
    -

    - IntelliJ IDEA is a powerful Java IDE from JetBrains that provides - full-cycle Android development support in both the free Community - Edition and the Ultimate edition. -

    -

    - The IDE ensures compatibility with the latest Android SDK and offers a - smart code editor with completion, quick navigation between code and - resources, a graphical debugger, unit testing support using Android - Testing Framework, and the ability to run applications in either the - emulator or a USB-connected device. -

    -

    - Links: -

    - - diff --git a/docs/html/guide/developing/other-ide.html b/docs/html/guide/developing/other-ide.html deleted file mode 100644 index 41dba0529b19..000000000000 --- a/docs/html/guide/developing/other-ide.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/developing/projects/index.jd b/docs/html/guide/developing/projects/index.jd deleted file mode 100644 index b16e466e4a1f..000000000000 --- a/docs/html/guide/developing/projects/index.jd +++ /dev/null @@ -1,446 +0,0 @@ -page.title=Managing Projects -@jd:body - - - -

    Projects act as containers for storing things such as code and resource files. The SDK tools - expect your projects to follow a specific structure so it can compile and package your - application correctly, so it is highly recommended that you create them with Eclipse and ADT or - with the android tool on the command line. There are three types of projects, and - they all share the same general structure but differ in function:

    - -
    -
    Android Projects
    - -
    An Android project is the container for your application's source code, resource files, and - files such as the Ant build and Android Manifest file. An application project is the main type - of project and the contents are eventually built into an .apk file that you install on a - device.
    - -
    Test Projects
    - -
    These projects contain code to test your application projects and are built into - applications that run on a device.
    - -
    Library Projects
    - -
    These projects contain shareable Android source code and resources that you can reference - in Android projects. This is useful when you have common code that you want to reuse. - Library projects cannot be installed onto a device, however, they are - pulled into the .apk file at build time.
    -
    - -

    When you use the Android development tools to create a new project, the essential files and - folders will be created for you. There are only a handful of files and folders generated for you, - and some of them depend on whether you use the Eclipse plugin or the {@code android} tool to - generate your project. As your application grows in complexity, you might require new kinds of - resources, directories, and files.

    - -

    Android Projects

    - -

    Android projects are the projects that eventually get built into an .apk file that you install - onto a device. They contain things such as application source code and resource files. - Some are generated for you by default, while others should be created if - required. The following directories and files comprise an Android project:

    - -
    -
    src/
    - -
    Contains your stub Activity file, which is stored at - src/your/package/namespace/ActivityName.java. All other source code - files (such as .java or .aidl files) go here as well.
    - -
    bin
    - -
    Output directory of the build. This is where you can find the final .apk file and other - compiled resources.
    - -
    jni
    - -
    Contains native code sources developed using the Android NDK. For more information, see the - Android NDK documentation.
    - -
    gen/
    - -
    Contains the Java files generated by ADT, such as your R.java file and - interfaces created from AIDL files.
    - -
    assets/
    - -
    This is empty. You can use it to store raw asset files. Files that you save here are - compiled into an .apk file as-is, and the original filename is preserved. You can navigate this - directory in the same way as a typical file system using URIs and read files as a stream of - bytes using the the {@link android.content.res.AssetManager}. For example, this is a good - location for textures and game data.
    - -
    res/
    - -
    - Contains application resources, such as drawable files, layout files, and string values. See - Application Resources for more - information. - -
    -
    anim/
    - -
    For XML files that are compiled into animation objects. See the Animation resource - type.
    - -
    color/
    - -
    For XML files that describe colors. See the Color Values resource - type.
    - -
    drawable/
    - -
    For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML files that describe - Drawable shapes or a Drawable objects that contain multiple states (normal, pressed, or - focused). See the Drawable resource type.
    - -
    layout/
    - -
    XML files that are compiled into screen layouts (or part of a screen). See the Layout resource type.
    - -
    menu/
    - -
    For XML files that define application menus. - See the Menus - resource type.
    - -
    raw/
    - -
    For arbitrary raw asset files. Saving asset files here instead of in the - assets/ directory only differs in the way that you access them. These files - are processed by aapt and must be referenced from the application using a resource - identifier in the {@code R} class. For example, this is a good place for media, such as MP3 - or Ogg files.
    - -
    values/
    - -
    For XML files that are compiled into many kinds of resource. Unlike other resources in - the res/ directory, resources written to XML files in this folder are not - referenced by the file name. Instead, the XML element type controls how the resources is - defined within them are placed into the {@code R} class.
    - -
    xml/
    - -
    For miscellaneous XML files that configure application components. For example, an XML - file that defines a {@link android.preference.PreferenceScreen}, {@link - android.appwidget.AppWidgetProviderInfo}, or Searchability - Metadata. See Application Resources - for more information about configuring these application components.
    -
    -
    - -
    libs/
    - -
    Contains private libraries.
    - -
    AndroidManifest.xml
    - -
    The control file that describes the nature of the application and each of its components. - For instance, it describes: certain qualities about the activities, services, intent receivers, - and content providers; what permissions are requested; what external libraries are needed; what - device features are required, what API Levels are supported or required; and others. See the - AndroidManifest.xml - documentation for more information
    - -
    project.properties
    - -
    This file contains project settings, such as the build target. This file is integral to - the project, so maintain it in a source revision control system. To edit project - properties in Eclipse, right-click the project folder and select - Properties.
    - -
    local.properties
    - -
    Customizable computer-specific properties for the build system. If you use Ant to build - the project, this contains the path to the SDK installation. Because the content of the file - is specific to the local installation of the SDK, the local.properties should not -be maintained in a source revision control system. If you use Eclipse, this file is not -used.
    - -
    ant.properties
    - -
    Customizable properties for the build system. You can edit this file to override default - build settings used by Ant and also provide the location of your keystore and key alias so that - the build tools can sign your application when building in release mode. This file is integral - to the project, so maintain it in a source revision control system. If you use Eclipse, this - file is not used.
    - -
    build.xml
    - -
    The Ant build file for your project. This is only applicable for projects that - you build with Ant.
    - -
    - -

    Library Projects

    - - - -

    An Android library project is a development project that holds shared Android - source code and resources. Other Android application projects can reference the library project - and, at build time, include its compiled sources in their .apk files. Multiple - application projects can reference the same library project and any single application project - can reference multiple library projects.

    - -

    Note: You need SDK Tools r14 or newer to use the new library - project feature that generates each library project into its own JAR file. - You can download the tools and platforms using the - Android SDK Manager, as described in - Adding SDK Packages.

    - -

    If you have source code and resources that are common to multiple Android projects, you - can move them to a library project so that it is easier to maintain across applications and - versions. Here are some common scenarios in which you could make use of library projects:

    - -
      -
    • If you are developing multiple related applications that use some of the same components, - you move the redundant components out of their respective application projects and create a - single, reuseable set of the same components in a library project.
    • - -
    • If you are creating an application that exists in both free and paid versions. You move - the part of the application that is common to both versions into a library project. The two - dependent projects, with their different package names, will reference the library project - and provide only the difference between the two application versions.
    • -
    - -

    Structurally, a library project is similar to a standard Android application project. For - example, it includes a manifest file at the project root, as well as src/, - res/ and similar directories. The project can contain the same types of source - code and resources as a standard Android project, stored in the same way. For example, source - code in the library project can access its own resources through its R class.

    - -

    However, a library project differs from an standard Android application project in that you - cannot compile it directly to its own .apk and run it on an Android device. - Similarly, you cannot export the library project to a self-contained JAR file, as you would do - for a true library. Instead, you must compile the library indirectly, by referencing the - library in the dependent application and building that application.

    - -

    When you build an application that depends on a library project, the SDK tools compile the - library into a temporary JAR file and uses it in the main project, then uses the - result to generate the .apk. In cases where a resource ID is defined in both the - application and the library, the tools ensure that the resource declared in the application gets - priority and that the resource in the library project is not compiled into the application - .apk. This gives your application the flexibility to either use or redefine any - resource behaviors or values that are defined in any library.

    - -

    To organize your code further, your application can add references to multiple library - projects, then specify the relative priority of the resources in each library. This lets you - build up the resources actually used in your application in a cumulative manner. When two - libraries referenced from an application define the same resource ID, the tools select the - resource from the library with higher priority and discard the other.

    - -

    Once you have added references to library projects to your Android project, - you can set their relative priority. At build time, the - libraries are merged with the application one at a time, starting from the lowest priority to - the highest.

    - -

    Library projects can reference other library projects and can import an external library - (JAR) in the normal way.

    - -

    Development considerations

    - -

    As you develop your library project and dependent applications, keep the points listed below - in mind:

    - -
      -
    • Resource conflicts

      -

      Since the tools merge the resources of a library project with those of a dependent application - project, a given resource ID might be defined in both projects. In this case, the tools select - the resource from the application, or the library with highest priority, and discard the other - resource. As you develop your applications, be aware that common resource IDs are likely to be - defined in more than one project and will be merged, with the resource from the application or - highest-priority library taking precedence.

      -
    • - -
    • Use prefixes to avoid resource conflicts

      - -

      To avoid resource conflicts for common resource IDs, consider using a prefix or other - consistent naming scheme that is unique to the project (or is unique across all projects).

    • - -
    • You cannot export a library project to a JAR file

      - -

      A library cannot be distributed as a binary file (such as a JAR file). This will -be added in a future - version of the SDK Tools.

    • - -
    • A library project can include a JAR library

      - -

      You can develop a library project that itself includes a JAR library, however you need to - manually edit the dependent application project's build path and add a path to the JAR file.

    • - -
    • A library project can depend on an external JAR library

      - -

      You can develop a library project that depends on an external library (for example, the Maps - external library). In this case, the dependent application must build against a target that - includes the external library (for example, the Google APIs Add-On). Note also that both the - library project and the dependent application must declare the external library in their manifest - files, in a <uses-library> - element.

    • - -
    • Library projects cannot include raw assets

      - -

      The tools do not support the use of raw asset files (saved in the assets/ directory) - in a library project. Any asset resources - used by an application must be stored in the assets/ directory of the application - project itself. However, resource files saved in the - res/ directory are supported.

    • - -
    • Platform version must be lower than or equal to the Android project

      - -

      A library is compiled as part of the dependent application project, so the API used in the - library project must be compatible with the version of the Android library used to compile the - application project. In general, the library project should use an API level that is the same as — or lower - than — that used by the application. If the library project uses an API level that is - higher than that of the application, the application project will not compile. It is - perfectly acceptable to have a library that uses the Android 1.5 API (API level 3) and that is - used in an Android 1.6 (API level 4) or Android 2.1 (API level 7) project, for instance.

    • - -
    • No restriction on library package names

      - -

      There is no requirement for the package name of a library to be the same as that of - applications that use it.

    • - -
    • Each library project creates its own R class

      - -

      When you build the dependent application project, library projects are compiled and - merged with the application project. Each library has its own R class, named according - to the library's package name. The R class generated from main - project and the library project is created in all the packages that are needed including the main - project's package and the libraries' packages.

    • - -
    • Library project storage location

      - -

      There are no specific requirements on where you should store a library project, relative to a - dependent application project, as long as the application project can reference the library - project by a relative link. What is important is that the main - project can reference the library project through a relative link.

    • -
    - -

    Test Projects

    - -

    Test projects contain Android applications that you write using the - Testing and - Instrumentation framework. The framework is an extension of the JUnit test framework and adds - access to Android system objects. The file structure of a test project is the same as an - Android project.

    - -
    -
    src/
    - -
    Includes your test source files. Test projects do not require an Activity .java - file, but can include one.
    - -
    gen/
    - -
    This contains the Java files generated by ADT, such as your R.java file and - interfaces created from AIDL files.
    - -
    assets/
    - -
    This is empty. You can use it to store raw asset files.
    - -
    res/
    - -
    A folder for your application resources, such as drawable files, layout files, string - values, etc. See Application - Resources.
    - -
    AndroidManifest.xml
    - -
    The Android Manifest for your project. See The AndroidManifest.xml File. Test - Projects have a special - <instrumentation> - element that connects the test project with the application project.
    - -
    project.properties
    - -
    This file contains project settings, such as the build target and links to the project being -tested. This file is integral to the project, so maintain it in a source -revision control system. To edit project properties in Eclipse, right-click the project folder -and select Properties.
    - -
    local.properties
    - -
    Customizable computer-specific properties for the build system. If you use Ant to build - the project, this contains the path to the SDK installation. Because the content of the file - is specific to the local installation of the SDK, it should not be maintained in a Source - Revision Control system. If you use Eclipse, this file is not used.
    - -
    ant.properties
    - -
    Customizable properties for the build system. You can edit this file to override default - build settings used by Ant and provide the location to your keystore and key alias, so that the - build tools can sign your application when building in release mode. This file is integral to - the project, so maintain it in a source revision control system. - If you use Eclipse, this file is not used.
    - -
    build.xml
    - -
    The Ant build file for your project. This is only applicable for projects that - you build with Ant.
    -
    - -

    For more information, see the Testing section.

    - - -

    Testing a Library Project

    - -

    There are two recommended ways of setting up testing on code and resources in a library - project:

    - -
      -
    • You can set up a test - project that instruments an application project that depends on the library project. You - can then add tests to the project for library-specific features.
    • - -
    • You can set up a set up a standard application project that depends on the library and put - the instrumentation in that project. This lets you create a self-contained project that - contains both the tests/instrumentations and the code to test.
    • -
    \ No newline at end of file diff --git a/docs/html/guide/developing/projects/projects-cmdline.jd b/docs/html/guide/developing/projects/projects-cmdline.jd deleted file mode 100644 index b8db5f333a1a..000000000000 --- a/docs/html/guide/developing/projects/projects-cmdline.jd +++ /dev/null @@ -1,295 +0,0 @@ -page.title=Managing Projects from the Command Line -parent.title=Managing Projects -parent.link=index.html -@jd:body - - - -

    The android tool provides you with commands to create all three types of - projects. An Android project contains all of the files and resources that are needed to build a - project into an .apk file for installation. - -

      -
    • An Android project contains all of the files and resources that are needed to build a project into - an .apk file for installation. You need to create an Android project for any application that you - want to eventually install on a device.
    • - -
    • You can also designate an Android project as a library project, which allows it to be shared - with other projects that depend on it. Once an Android project is designated as a library - project, it cannot be installed onto a device.
    • - -
    • Test projects extend JUnit test functionality to include Android specific functionality. For - more information on creating a test project, see Testing from other IDEs.
    • -
    - - -

    Creating an Android Project

    - -

    To create an Android project, you must use the android tool. When you create a - new project with android, it will generate a project directory with some default - application files, stub files, configuration files and a build file.

    - -

    To create a new Android project, open a command-line, navigate to the tools/ - directory of your SDK and run:

    -
    -android create project \
    ---target <target_ID> \
    ---name <your_project_name> \
    ---path path/to/your/project \
    ---activity <your_activity_name> \
    ---package <your_package_namespace>
    -
    - -
      -
    • target is the "build target" for your application. It corresponds to an - Android platform library (including any add-ons, such as Google APIs) that you would like to - build your project against. To see a list of available targets and their corresponding IDs, - execute: android list targets.
    • - -
    • name is the name for your project. This is optional. If provided, this name - will be used for your .apk filename when you build your application.
    • - -
    • path is the location of your project directory. If the directory does not - exist, it will be created for you.
    • - -
    • activity is the name for your default {@link android.app.Activity} class. This - class file will be created for you inside - <path_to_your_project>/src/<your_package_namespace_path>/ - . This will also be used for your .apk filename unless you provide a name.
    • - -
    • package is the package namespace for your project, following the same rules as - for packages in the Java programming language.
    • -
    - -

    Here's an example:

    -
    -android create project \
    ---target 1 \
    ---name MyAndroidApp \
    ---path ./MyAndroidAppProject \
    ---activity MyAndroidAppActivity \
    ---package com.example.myandroid
    -
    - -

    Once you've created your project, you're ready to begin development. You can move your project - folder wherever you want for development, but keep in mind that you must use the Android Debug Bridge (adb) — located in the - SDK platform-tools/ directory — to send your application to the emulator (discussed - later). So you need access between your project solution and the platform-tools/ folder.

    - -

    Tip: Add the platform-tools/ as well as the tools/ directory - to your PATH environment variable.

    - -

    Caution: You should refrain from moving the location of the - SDK directory, because this will break the SDK location property located in local.properties. - If you need to update the SDK location, use the android update project command. - See Updating a Project for more information.

    - -

    Updating a Project

    - -

    If you're upgrading a project from an older version of the Android SDK or want to create a new - project from existing code, use the android update project command to update the - project to the new development environment. You can also use this command to revise the build - target of an existing project (with the --target option) and the project name (with - the --name option). The android tool will generate any files and - folders (listed in the previous section) that are either missing or need to be updated, as needed - for the Android project.

    - -

    To update an existing Android project, open a command-line and navigate to the - tools/ directory of your SDK. Now run:

    -
    -android update project --name <project_name> --target <target_ID>
    ---path <path_to_your_project>
    -
    - -
      -
    • target is the "build target" for your application. It corresponds to an - Android platform library (including any add-ons, such as Google APIs) that you would like to - build your project against. To see a list of available targets and their corresponding IDs, - execute: android list targets.
    • - -
    • path is the location of your project directory.
    • - -
    • name is the name for the project. This is optional—if you're not - changing the project name, you don't need this.
    • -
    - -

    Here's an example:

    -
    -android update project --name MyApp --target 2 --path ./MyAppProject
    -
    - -

    Setting up a Library Project

    - -

    A library project is a standard Android project, so you can create a new one in the same way - as you would a new application project. Specifically, you can use the android tool - to generate a new library project with all of the necessary files and folders.

    - -

    To create a new library project, navigate to the <sdk>/tools/ directory and - use this command:

    -
    -android create lib-project --name <your_project_name> \
    ---target <target_ID> \
    ---path path/to/your/project \
    ---package <your_library_package_namespace>
    -
    - -

    The create lib-project command creates a standard project structure that includes - preset property that indicates to the build system that the project is a library. It does this by - adding this line to the project's project.properties file:

    -
    -android.library=true
    -
    - -

    Once the command completes, the library project is created and you can begin moving source - code and resources into it, as described in the sections below.

    - -

    If you want to convert an existing application project to a library project, so that other - applications can use it, you can do so by adding a the android.library=true property - to the application's project.properties file.

    - -

    Creating the manifest file

    - -

    A library project's manifest file must declare all of the shared components that it includes, - just as would a standard Android application. For more information, see the documentation for - AndroidManifest.xml.

    - -

    For example, the TicTacToeLib example library - project declares the Activity GameActivity:

    -
    -<manifest>
    -  ...
    -  <application>
    -    ...
    -    <activity android:name="GameActivity" />
    -    ...
    -  </application>
    -</manifest>
    -
    - -

    Updating a library project

    - -

    If you want to update the build properties (build target, location) of the library project, - use this command:

    -
    -android update lib-project \
    ---target <target_ID> \
    ---path path/to/your/project
    -
    - -

    Referencing a Library Project

    - -

    If you are developing an application and want to include the shared code or resources from a - library project, you can do so easily by adding a reference to the library project in the - application project's build properties.

    - -

    To add a reference to a library project, navigate to the <sdk>/tools/ - directory and use this command:

    -
    -android update project \
    ---target <target_ID> \
    ---path path/to/your/project
    ---library path/to/library_projectA
    -
    - -

    This command updates the application project's build properties to include a reference to the - library project. Specifically, it adds an android.library.reference.n - property to the project's project.properties file. For example:

    -
    -android.library.reference.1=path/to/library_projectA
    -
    - -

    If you are adding references to multiple libraries, note that you can set their relative - priority (and merge order) by manually editing the project.properties file and - adjusting the each reference's .n index as appropriate. For example, assume - these references:

    -
    -android.library.reference.1=path/to/library_projectA
    -android.library.reference.2=path/to/library_projectB
    -android.library.reference.3=path/to/library_projectC
    -
    - -

    You can reorder the references to give highest priority to library_projectC in - this way:

    -
    -android.library.reference.2=path/to/library_projectA
    -android.library.reference.3=path/to/library_projectB
    -android.library.reference.1=path/to/library_projectC
    -
    - -

    Note that the .n index in the references must begin at "1" and increase - uniformly without "holes". References appearing in the index after a hole are ignored.

    - -

    At build time, the libraries are merged with the application one at a time, starting from the - lowest priority to the highest. Note that a library cannot itself reference another library and - that, at build time, libraries are not merged with each other before being merged with the - application.

    - -

    Declaring library components in the manifest file

    - -

    In the manifest file of the application project, you must add declarations of all components - that the application will use that are imported from a library project. For example, you must - declare any <activity>, <service>, - <receiver>, <provider>, and so on, as well as - <permission>, <uses-library>, and similar elements.

    - -

    Declarations should reference the library components by their fully-qualified package names, - where appropriate.

    - -

    For example, the TicTacToeMain example - application declares the library Activity GameActivity like this:

    -
    -<manifest>
    -  ...
    -  <application>
    -    ...
    -    <activity android:name="com.example.android.tictactoe.library.GameActivity" />
    -    ...
    -  </application>
    -</manifest>
    -
    - -

    For more information about the manifest file, see the documentation for - AndroidManifest.xml.

    - -

    Building a dependent application

    - -

    To build an application project that depends on one or more library projects, you can use the - standard Ant build commands and compile modes, as described in Building and Running. The tools -compile and merge all libraries referenced by the application as part of - compiling the dependent application project. No additional commands or steps are necessary.

    - diff --git a/docs/html/guide/developing/projects/projects-eclipse.jd b/docs/html/guide/developing/projects/projects-eclipse.jd deleted file mode 100644 index 90f7820631ae..000000000000 --- a/docs/html/guide/developing/projects/projects-eclipse.jd +++ /dev/null @@ -1,237 +0,0 @@ -page.title=Managing Projects from Eclipse with ADT -parent.title=Managing Projects -parent.link=index.html -@jd:body - - - -

    Eclipse and the ADT plugin provide GUIs and wizards to create all three types of projects - (Android project, Library project, and Test project): - -

      -
    • An Android project contains all of the files and resources that are needed to build a project into - an .apk file for installation. You need to create an Android project for any application that you - want to eventually install on a device.
    • - -
    • You can also designate an Android project as a library project, which allows it to be shared - with other projects that depend on it. Once an Android project is designated as a library - project, it cannot be installed onto a device.
    • - -
    • Test projects extend JUnit test functionality to include Android specific functionality. For - more information on creating a test project, see Testing from Eclipse with ADT.
    • -
    - -

    Creating an Android Project

    - -

    The ADT plugin provides a New Project Wizard that you can use to quickly create a new Android - project (or a project from existing code). To create a new project:

    - -
      -
    1. Select File > New > Project.
    2. - -
    3. Select Android > Android Project, and click - Next.
    4. - -
    5. Select the contents for the project: - -
        -
      • Enter a Project Name. This will be the name of the folder where your project - is created.
      • - -
      • Under Contents, select Create new project in workspace. Select your - project workspace location.
      • - -
      • Under Target, select an Android target to be used as the project's Build Target. The - Build Target specifies which Android platform you'd like your application built against. - -

        Select the lowest platform with which your application is compatible.

        - -

        Note: You can change your the Build Target for your - project at any time: Right-click the project in the Package Explorer, select - Properties, select Android and then check the desired - Project Target.

        -
      • - -
      • Under Properties, fill in all necessary fields. - -
          -
        • Enter an Application name. This is the human-readable title for your - application — the name that will appear on the Android device.
        • - -
        • Enter a Package name. This is the package namespace (following the same - rules as for packages in the Java programming language) where all your source code will - reside.
        • - -
        • Select Create Activity (optional, of course, but common) and enter a name - for your main Activity class.
        • - -
        • Enter a Min SDK Version. This is an integer that indicates the minimum API - Level required to properly run your application. Entering this here automatically sets - the minSdkVersion attribute in the <uses-sdk> of your - Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level - listed for the Build Target you selected in the Target tab.
        • -
        -
      • -
      -
    6. - -
    7. Click Finish.
    8. -
    - -

    Tip: You can also start the New Project Wizard from the - New icon in the toolbar.

    - -

    Setting up a Library Project

    - -

    A library project is a standard Android project, so you can create a new one in the same way - as you would a new application project.

    - -

    When you are creating the library project, you can select any application name, package, and - set other fields as needed, as shown in figure 1.

    - -

    Next, set the project's properties to indicate that it is a library project:

    - -
      -
    1. In the Package Explorer, right-click the library project and select - Properties.
    2. - -
    3. In the Properties window, select the "Android" properties group at left - and locate the Library properties at right.
    4. - -
    5. Select the "is Library" checkbox and click Apply.
    6. - -
    7. Click OK to close the Properties window.
    8. -
    - -

    The new project is now marked as a library project. You can begin moving source code and - resources into it, as described in the sections below.

    - -

    You can also convert an existing application project into a library. To do so, simply open the - Properties for the project and select the "is Library" checkbox. Other application projects can - now reference the existing project as a library project.

    - - - -

    Figure 1. Marking a project as an - Android library project.

    - -

    Creating the manifest file

    - -

    A library project's manifest file must declare all of the shared components that it includes, - just as would a standard Android application. For more information, see the documentation for - AndroidManifest.xml.

    - -

    For example, the TicTacToeLib example library - project declares the Activity GameActivity:

    -
    -<manifest>
    -  ...
    -  <application>
    -    ...
    -    <activity android:name="GameActivity" />
    -    ...
    -  </application>
    -</manifest>
    -
    - -

    Referencing a library project

    - -

    If you are developing an application and want to include the shared code or resources from a - library project, you can do so easily by adding a reference to the library project in the - application project's Properties.

    - -

    To add a reference to a library project, follow these steps:

    - -
      -
    1. In the Package Explorer, right-click the dependent project and select - Properties.
    2. - -
    3. In the Properties window, select the "Android" properties group at left - and locate the Library properties at right.
    4. - -
    5. Click Add to open the Project Selection dialog.
    6. - -
    7. From the list of available library projects, select a project and click - OK.
    8. - -
    9. When the dialog closes, click Apply in the Properties - window.
    10. - -
    11. Click OK to close the Properties window.
    12. -
    - -

    As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents - of the library project.

    - -

    Figure 2 shows the Properties dialog that lets you add library references and move - them up and down in priority.

    - -

    Figure 2. Adding a reference to a - library project in the properties of an application project.

    - -

    If you are adding references to multiple libraries, note that you can set their relative - priority (and merge order) by selecting a library and using the Up and - Down controls. The tools merge the referenced libraries with your application - starting from lowest priority (bottom of the list) to highest (top of the list). If more than one - library defines the same resource ID, the tools select the resource from the library with higher - priority. The application itself has highest priority and its resources are always used in - preference to identical resource IDs defined in libraries.

    - -

    Declaring library components in the manifest file

    - -

    In the manifest file of the application project, you must add declarations of all components - that the application will use that are imported from a library project. For example, you must - declare any <activity>, <service>, - <receiver>, <provider>, and so on, as well as - <permission>, <uses-library>, and similar elements.

    - -

    Declarations should reference the library components by their fully-qualified package names, - where appropriate.

    - -

    For example, the TicTacToeMain example - application declares the library Activity GameActivity like this:

    -
    -<manifest>
    -  ...
    -  <application>
    -    ...
    -    <activity android:name="com.example.android.tictactoe.library.GameActivity" />
    -    ...
    -  </application>
    -</manifest>
    -
    - -

    For more information about the manifest file, see the documentation for AndroidManifest.xml.

    - - - - - - - diff --git a/docs/html/guide/developing/testing/index.jd b/docs/html/guide/developing/testing/index.jd deleted file mode 100644 index 8a0895989182..000000000000 --- a/docs/html/guide/developing/testing/index.jd +++ /dev/null @@ -1,36 +0,0 @@ -page.title=Testing -@jd:body -

    - Android includes powerful tools for setting up and running test applications. - Whether you are working in Eclipse with ADT or working from the command line, these tools - help you set up and run your tests within an emulator or the device you are targeting. - The documents listed below explain how to work with the tools in your development environment. -

    -

    - If you aren't yet familiar with the Android testing framework, please read the topic - Testing Fundamentals - before you get started. - For a step-by-step introduction to Android testing, try the Hello, Testing - tutorial, which introduces basic testing concepts and procedures. - For a more advanced tutorial, try Activity Testing, - which guides you through a more complex testing scenario. -

    -
    -
    Testing from Eclipse, with ADT
    -
    - The ADT plugin lets you quickly set up and manage test projects directly in - the Eclipse UI. Once you have written your tests, you can build and run them and - then see the results in the Eclipse JUnit view. You can also use the SDK command-line - tools to execute your tests if needed. -
    -
    Testing from Other IDEs
    -
    - The SDK command-line tools provide the same capabilities as the ADT plugin. You can - use them to set up and manage test projects, build your test application, - run your tests, and see the results. You use - the android tool to create and manage test projects, the Ant build system - to compile them, and the adb tool to install and run them. -
    -
    diff --git a/docs/html/guide/developing/testing/testing_eclipse.jd b/docs/html/guide/developing/testing/testing_eclipse.jd deleted file mode 100644 index 4e9ecca991b3..000000000000 --- a/docs/html/guide/developing/testing/testing_eclipse.jd +++ /dev/null @@ -1,535 +0,0 @@ -page.title=Testing from Eclipse with ADT -parent.title=Testing -parent.link=index.html -@jd:body - -

    - This topic explains how create and run tests of Android applications in Eclipse with ADT. - Before you read this topic, you should read about how to create an Android application with the - basic processes for creating and running applications with ADT, as described in - Managing Projects from -Eclipse - and Building and Running -from Eclipse. - You may also want to read - Testing Fundamentals, - which provides an overview of the Android testing framework. -

    -

    - ADT provides several features that help you set up and manage your testing environment - effectively: -

    -
      -
    • - It lets you quickly create a test project and link it to the application under test. - When it creates the test project, it automatically inserts the necessary - <instrumentation> element in the test package's manifest file. -
    • -
    • - It lets you quickly import the classes of the application under test, so that your - tests can inspect them. -
    • -
    • - It lets you create run configurations for your test package and include in - them flags that are passed to the Android testing framework. -
    • -
    • - It lets you run your test package without leaving Eclipse. ADT builds both the - application under test and the test package automatically, installs them if - necessary to your device or emulator, runs the test package, and displays the - results in a separate window in Eclipse. -
    • -
    -

    - If you are not developing in Eclipse or you want to learn how to create and run tests from the - command line, see - Testing from Other IDEs. -

    -

    Creating a Test Project

    -

    - To set up a test environment for your Android application, you must first create a separate - project that holds the test code. The new project follows the directory structure - used for any Android application. It includes the same types of content and files, such as - source code, resources, a manifest file, and so forth. The test package you - create is connected to the application under test by an - - <instrumentation> element in its manifest file. -

    -

    - The New Android Test Project dialog makes it easy for you to generate a - new test project that has the proper structure, including the - <instrumentation> element in the manifest file. You can use the New - Android Test Project dialog to generate the test project at any time. The dialog appears - just after you create a new Android main application project, but you can also run it to - create a test project for a project that you created previously. -

    -

    - To create a test project in Eclipse with ADT: -

    -
      -
    1. - In Eclipse, select File > New > Other. This opens the Select a - Wizard dialog. -
    2. -
    3. - In the dialog, in the Wizards drop-down list, find the entry for Android, then - click the toggle to the left. Select Android Test Project, then at the - bottom of the dialog click Next. The New Android Test Project - wizard appears. -
    4. -
    5. - Next to Test Project Name, enter a name for the project. You may use any name, - but you may want to associate the name with the project name for the application under test. - One way to do this is to take the application's project name, append the string "Test" to - it, and then use this as the test package project name. -

      - The name becomes part of the suggested project path, but you can change this in the - next step. -

      -
    6. -
    7. - In the Content panel, examine the suggested path to the project. - If Use default location is set, then the wizard will suggest a path that is - a concatenation of the workspace path and the project name you entered. For example, - if your workspace path is /usr/local/workspace and your project name is - MyTestApp, then the wizard will suggest - /usr/local/workspace/MyTestApp. To enter your own - choice for a path, unselect Use default location, then enter or browse to the - path where you want your project. -

      - To learn more about choosing the location of test projects, please read - - Testing Fundamentals. -

      -
    8. -
    9. - In the Test Target panel, set An Existing Android Project, click Browse, then select your - Android application from the list. You now see that the wizard has completed the Test - Target Package, Application Name, and Package Name fields for you (the latter two are in - the Properties panel). -
    10. -
    11. - In the Build Target panel, select the Android SDK platform that the application under test - uses. -
    12. -
    13. - Click Finish to complete the wizard. If Finish is disabled, look for error messages at the - top of the wizard dialog, and then fix any problems. -
    14. -
    -

    Creating a Test Package

    -

    - Once you have created a test project, you populate it with a test package. This package does not - require an Activity, although you can define one if you wish. Although your test package can - combine Activity classes, test case classes, or ordinary classes, your main test case - should extend one of the Android test case classes or JUnit classes, because these provide the - best testing features. -

    -

    - Test packages do not need to have an Android GUI. When you run the package in - Eclipse with ADT, its results appear in the JUnit view. Running tests and seeing the results is - described in more detail in the section Running Tests. -

    - -

    - To create a test package, start with one of Android's test case classes defined in - {@link android.test android.test}. These extend the JUnit - {@link junit.framework.TestCase TestCase} class. The Android test classes for Activity objects - also provide instrumentation for testing an Activity. To learn more about test case - classes, please read the topic - Testing Fundamentals. -

    -

    - Before you create your test package, you choose the Java package identifier you want to use - for your test case classes and the Android package name you want to use. To learn more - about this, please read - - Testing Fundamentals. -

    -

    - To add a test case class to your project: -

    -
      -
    1. - In the Project Explorer tab, open your test project, then open the src - folder. -
    2. -
    3. - Find the Java package identifier set by the projection creation wizard. If you haven't - added classes yet, this node won't have any children, and its icon will not be filled in. - If you want to change the identifier value, right-click the identifier and select - Refactor > Rename, then enter the new name. -
    4. -
    5. - When you are ready, right-click the Java package identifier again and select - New > Class. This displays the New Java Class - dialog, with the Source folder and Package values already set. -
    6. -
    7. - In the Name field, enter a name for the test case class. One way to choose a - class name is to append the string "Test" to the class of the component you are testing. - For example, if you are testing the class MyAppActivity, your test case class - name would be MyAppActivityTest. Leave the modifiers set to public. -
    8. -
    9. - In the Superclass field, enter the name of the Android test case class you - are extending. You can also browse the available classes. -
    10. -
    11. - In Which method stubs would you like to create?, unset all the options, then - click Finish. You will set up the constructor manually. -
    12. -
    13. - Your new class appears in a new Java editor pane. -
    14. -
    -

    - You now have to ensure that the constructor is set up correctly. Create a constructor for your - class that has no arguments; this is required by JUnit. As the first statement in this - constructor, add a call to the base class' constructor. Each base test case class has its - own constructor signature. Refer to the class documentation in the documentation for - {@link android.test} for more information. -

    -

    - To control your test environment, you will want to override the setUp() and - tearDown() methods: -

    -
      -
    • - setUp(): This method is invoked before any of the test methods in the class. - Use it to set up the environment for the test (the test fixture. You can use - setUp() to instantiate a new Intent with the action ACTION_MAIN. - You can then use this intent to start the Activity under test. -
    • -
    • - tearDown(): This method is invoked after all the test methods in the class. Use - it to do garbage collection and to reset the test fixture. -
    • -
    -

    - Another useful convention is to add the method testPreconditions() to your test - class. Use this method to test that the application under test is initialized correctly. If this - test fails, you know that that the initial conditions were in error. When this happens, further - test results are suspect, regardless of whether or not the tests succeeded. -

    -

    - The Resources tab contains an - Activity Testing - tutorial with more information about creating test classes and methods. -

    -

    Running Tests

    - -

    - When you run a test package in Eclipse with ADT, the output appears in the Eclipse JUnit view. - You can run the entire test package or one test case class. To do run tests, Eclipse runs the - adb command for running a test package, and displays the output, so there is no - difference between running tests inside Eclipse and running them from the command line. -

    -

    - As with any other package, to run a test package in Eclipse with ADT you must either attach a - device to your computer or use the Android emulator. If you use the emulator, you must have an - Android Virtual Device (AVD) that uses the same target as the test package. -

    -

    - To run a test in Eclipse, you have two choices:

    -
      -
    • - Run a test just as you run an application, by selecting - Run As... > Android JUnit Test from the project's context menu or - from the main menu's Run item. -
    • -
    • - Create an Eclipse run configuration for your test project. This is useful if you want - multiple test suites, each consisting of selected tests from the project. To run - a test suite, you run the test configuration. -

      - Creating and running test configurations is described in the next section. -

      -
    • -
    -

    - To create and run a test suite using a run configuration: -

    -
      -
    1. - In the Package Explorer, select the test project, then from the main menu, select - Run > Run Configurations.... The Run Configurations dialog appears. -
    2. -
    3. - In the left-hand pane, find the Android JUnit Test entry. In the right-hand pane, click the - Test tab. The Name: text box shows the name of your project. The Test class: dropdown box - shows one of the test classes in your project. -
    4. -
    5. - To run one test class, click Run a single test, then enter your project name in the - Project: text box and the class name in the Test class: text box. -

      - To run all the test classes, click Run all tests in the selected project or package, - then enter the project or package name in the text box. -

      -
    6. -
    7. - Now click the Target tab. -
        -
      • - Optional: If you are using the emulator, click Automatic, then in the Android - Virtual Device (AVD) selection table, select an existing AVD. -
      • -
      • - In the Emulator Launch Parameters pane, set the Android emulator flags you want to - use. These are documented in the topic - - Android Emulator. -
      • -
      -
    8. -
    9. - Click the Common tab. In the Save As pane, click Local to save this run configuration - locally, or click Shared to save it to another project. -
    10. -
    11. - Optional: Add the configuration to the Run toolbar and the Favorites - menu: in the Display in Favorites pane click the checkbox next to Run. -
    12. -
    13. - Optional: To add this configuration to the Debug menu and toolbar, click - the checkbox next to Debug. -
    14. -
    15. - To save your settings, click Close.
      -

      Note: - Although you can run the test immediately by clicking Run, you should save the test - first and then run it by selecting it from the Eclipse standard toolbar. -

      -
    16. -
    17. - On the Eclipse standard toolbar, click the down arrow next to the green Run arrow. This - displays a menu of saved Run and Debug configurations. -
    18. -
    19. - Select the test run configuration you just created. The test starts. -
    20. -
    -

    - The progress of your test appears in the Console view as a series of messages. Each message is - preceded by a timestamp and the .apk filename to which it applies. For example, - this message appears when you run a test to the emulator, and the emulator is not yet started: -

    - -
    -    [yyyy-mm-dd hh:mm:ss - testfile] Waiting for HOME ('android.process.acore') to be launched...
    -
    -

    - In the following description of these messages, devicename is the name of - the device or emulator you are using to run the test, and port is the - port number for the device. The name and port number are in the format used by the - adb devices - command. Also, testfile is the .apk filename of the test - package you are running, and appfile is the filename of the application under test. -

    -
      -
    • - If you are using an emulator and you have not yet started it, then Eclipse - first starts the emulator. When this is complete, you see - the message: -

      - HOME is up on device 'devicename-port' -

      -
    • -
    • - If you have not already installed your test package, then you see - the message: -

      - Uploading testfile onto device 'devicename-port' - -

      -

      - then the message Installing testfile. -

      -

      - and finally the message Success! -

      -
    • -
    -

    - The following lines are an example of this message sequence: -

    - -[2010-07-01 12:44:40 - MyTest] HOME is up on device 'emulator-5554'
    -[2010-07-01 12:44:40 - MyTest] Uploading MyTest.apk onto device 'emulator-5554'
    -[2010-07-01 12:44:40 - MyTest] Installing MyTest.apk...
    -[2010-07-01 12:44:49 - MyTest] Success!
    -
    -
    -
      -
    • - Next, if you have not yet installed the application under test to the device or - emulator, you see the message -

      - Project dependency found, installing: appfile -

      -

      - then the message Uploading appfile onto device - 'devicename-port' -

      -

      - then the message Installing appfile -

      -

      - and finally the message Success! -

      -
    • -
    -

    - The following lines are an example of this message sequence: -

    - -[2010-07-01 12:44:49 - MyTest] Project dependency found, installing: MyApp
    -[2010-07-01 12:44:49 - MyApp] Uploading MyApp.apk onto device 'emulator-5554'
    -[2010-07-01 12:44:49 - MyApp] Installing MyApp.apk...
    -[2010-07-01 12:44:54 - MyApp] Success!
    -
    -
    -
      -
    • - Next, you see the message - Launching instrumentation instrumentation_class on device - devicename-port -

      - instrumentation_class is the fully-qualified class name of the - instrumentation test runner you have specified (usually - {@link android.test.InstrumentationTestRunner}. -

      -
    • -
    • - Next, as {@link android.test.InstrumentationTestRunner} builds a list of tests to run, - you see the message -

      - Collecting test information -

      -

      - followed by -

      -

      - Sending test information to Eclipse -

      -
    • -
    • - Finally, you see the message Running tests, which indicates that your tests - are running. At this point, you should start seeing the test results in the JUnit view. - When the tests are finished, you see the console message Test run complete. - This indicates that your tests are finished. -
    • -
    -

    - The following lines are an example of this message sequence: -

    - -[2010-01-01 12:45:02 - MyTest] Launching instrumentation android.test.InstrumentationTestRunner on device emulator-5554
    -[2010-01-01 12:45:02 - MyTest] Collecting test information
    -[2010-01-01 12:45:02 - MyTest] Sending test information to Eclipse
    -[2010-01-01 12:45:02 - MyTest] Running tests...
    -[2010-01-01 12:45:22 - MyTest] Test run complete
    -
    -
    -

    - The test results appear in the JUnit view. This is divided into an upper summary pane, - and a lower stack trace pane. -

    -

    - The upper pane contains test information. In the pane's header, you see the following - information: -

    -
      -
    • - Total time elapsed for the test package (labeled Finished after x seconds). -
    • -
    • - Number of runs (Runs:) - the number of tests in the entire test class. -
    • -
    • - Number of errors (Errors:) - the number of program errors and exceptions encountered - during the test run. -
    • -
    • - Number of failures (Failures:) - the number of test failures encountered during the test - run. This is the number of assertion failures. A test can fail even if the program does - not encounter an error. -
    • -
    • - A progress bar. The progress bar extends from left to right as the tests run. If all the - tests succeed, the bar remains green. If a test fails, the bar turns from green to red. -
    • -
    -

    - The body of the upper pane contains the details of the test run. For each test case class - that was run, you see a line with the class name. To look at the results for the individual - test methods in that class, you click the left arrow to expand the line. You now see a - line for each test method in the class, and to its right the time it took to run. - If you double-click the method name, Eclipse opens the test class source in an editor view - pane and moves the focus to the first line of the test method. -

    -

    - The results of a successful test are shown in figure 1. -

    - - Messages for a successful test - -

    - Figure 1. Messages for a successful test. -

    -

    - The lower pane is for stack traces. If you highlight a failed test in the upper pane, the - lower pane contains a stack trace for the test. If a line corresponds to a point in your - test code, you can double-click it to display the code in an editor view pane, with the - line highlighted. For a successful test, the lower pane is empty. -

    -

    The results of a failed test are shown in figure 2.

    - - - -

    - Figure 2. Messages for a test failure. -

    diff --git a/docs/html/guide/developing/testing/testing_otheride.jd b/docs/html/guide/developing/testing/testing_otheride.jd deleted file mode 100644 index 7745ae775f41..000000000000 --- a/docs/html/guide/developing/testing/testing_otheride.jd +++ /dev/null @@ -1,694 +0,0 @@ -page.title=Testing from Other IDEs -parent.title=Testing -parent.link=index.html -@jd:body - - -

    - This document describes how to create and run tests directly from the command line. - You can use the techniques described here if you are developing in an IDE other than Eclipse - or if you prefer to work from the command line. This document assumes that you already know how - to create a Android application in your programming environment. Before you start this - document, you should read the topic - Testing Fundamentals, - which provides an overview of Android testing. -

    -

    - If you are developing in Eclipse with ADT, you can set up and run your tests - directly in Eclipse. For more information, please read - - Testing from Eclipse with ADT. -

    -

    Working with Test Projects

    -

    - You use the android tool to create test projects. - You also use android to convert existing test code into an Android test project, - or to add the run-tests Ant target to an existing Android test project. - These operations are described in more detail in the section - Updating a test project. The run-tests target is described in - Quick build and run with Ant. -

    -

    Creating a test project

    -

    - To create a test project with the android tool, enter: -

    -
    -android create test-project -m <main_path> -n <project_name> -p <test_path>
    -
    -

    - You must supply all the flags. The following table explains them in detail: -

    - - - - - - - - - - - - - - - - - - - - - -
    FlagValueDescription
    -m, --main - Path to the project of the application under test, relative to the test package - directory. - - For example, if the application under test is in source/HelloAndroid, and - you want to create the test project in source/HelloAndroidTest, then the - value of --main should be ../HelloAndroid. -

    - To learn more about choosing the location of test projects, please read - - Testing Fundamentals. -

    -
    -n, --nameName that you want to give the test project. 
    -p, --pathDirectory in which you want to create the new test project. - The android tool creates the test project files and directory structure - in this directory. If the directory does not exist, android creates it. -
    -

    - If the operation is successful, android lists to STDOUT the names of the files - and directories it has created. -

    -

    - This creates a new test project with the appropriate directories and build files. The directory - structure and build file contents are identical to those in a regular Android application - project. They are described in detail in the topic - Managing Projects. -

    -

    - The operation also creates an AndroidManifest.xml file with instrumentation - information. When you run the test, Android uses this information to load the application you - are testing and control it with instrumentation. -

    -

    - For example, suppose you create the - Hello, World tutorial application in the directory ~/source/HelloAndroid. - In the tutorial, this application uses the package name com.example.helloandroid - and the activity name HelloAndroid. You can to create the test for this in - ~/source/HelloAndroidTest. To do so, you enter: -

    -
    -$ cd ~/source
    -$ android create test-project -m ../HelloAndroid -n HelloAndroidTest -p HelloAndroidTest
    -
    -

    - This creates a directory called ~/src/HelloAndroidTest. In the new directory you - see the file AndroidManifest.xml. This file contains the following - instrumentation-related elements and attributes: -

    -
      -
    • - <application>: to contain the - <uses-library> element. -
    • -
    • - <uses-library android:name="android.test.runner": - specifies this testing application uses the android.test.runner library. -
    • -
    • - <instrumentation>: contains attributes that control Android - instrumentation. The attributes are: -
        -
      • - android:name="android.test.InstrumentationTestRunner": - {@link android.test.InstrumentationTestRunner} runs test cases. It extends both - JUnit test case runner classes and Android instrumentation classes. -
      • -
      • - android:targetPackage="com.example.helloandroid": specifies - that the tests in HelloAndroidTest should be run against the application with the - Android package name com.example.helloandroid. This is the - package name of the Hello, World - tutorial application. -
      • -
      • - android:label="Tests for .HelloAndroid": specifies a - user-readable label for the instrumentation class. By default, - the android tool gives it the value "Tests for " plus - the name of the main Activity of the application under test. -
      • -
      -
    • -
    -

    Updating a test project

    -

    - You use the android tool when you need to change the path to the - project of the application under test. If you are changing an existing test project created in - Eclipse with ADT so that you can also build and run it from the command line, you must use the - "create" operation. See the section Creating a test project. -

    -

    - Note: If you change the Android package name of the application under test, - you must manually change the value of the <android:targetPackage> - attribute within the AndroidManifest.xml file of the test package. - Running android update test-project does not do this. -

    -

    - To update a test project with the android tool, enter: -

    -
    android update test-project -m <main_path> -p <test_path>
    - - - - - - - - - - - - - - - - - -
    FlagValueDescription
    -m, --mainThe path to the project of the application under test, relative to the test project - For example, if the application under test is in source/HelloAndroid, and - the test project is in source/HelloAndroidTest, then the value for - --main is ../HelloAndroid. -
    -p, --pathThe of the test project. - For example, if the test project is in source/HelloAndroidTest, then the - value for --path is HelloAndroidTest. -
    -

    - If the operation is successful, android lists to STDOUT the names of the files - and directories it has created. -

    -

    Creating a Test Package

    -

    - Once you have created a test project, you populate it with a test package. - The application does not require an {@link android.app.Activity Activity}, - although you can define one if you wish. Although your test package can - combine Activities, Android test class extensions, JUnit extensions, or - ordinary classes, you should extend one of the Android test classes or JUnit classes, - because these provide the best testing features. -

    -

    - If you run your tests with {@link android.test.InstrumentationTestRunner} - (or a related test runner), then it will run all the methods in each class. You can modify - this behavior by using the {@link junit.framework.TestSuite TestSuite} class. -

    - -

    - To create a test package, start with one of Android's test classes in the Java package - {@link android.test android.test}. These extend the JUnit - {@link junit.framework.TestCase TestCase} class. With a few exceptions, the Android test - classes also provide instrumentation for testing. -

    -

    - For test classes that extend {@link junit.framework.TestCase TestCase}, you probably want to - override the setUp() and tearDown() methods: -

    -
      -
    • - setUp(): This method is invoked before any of the test methods in the class. - Use it to set up the environment for the test. You can use setUp() - to instantiate a new Intent object with the action ACTION_MAIN. - You can then use this intent to start the Activity under test. -

      - Note: If you override this method, call - super.setUp() as the first statement in your code. -

      -
    • -
    • - tearDown(): This method is invoked after all the test methods in the class. Use - it to do garbage collection and re-setting before moving on to the next set of tests. -

      Note: If you override this method, you must call - super.tearDown() as the last statement in your code.

      -
    • -
    -

    - Another useful convention is to add the method testPreConditions() to your test - class. Use this method to test that the application under test is initialized correctly. If this - test fails, you know that that the initial conditions were in error. When this happens, further - test results are suspect, regardless of whether or not the tests succeeded. -

    -

    - To learn more about creating test packages, see the topic Testing Fundamentals, - which provides an overview of Android testing. If you prefer to follow a tutorial, - try the Activity Testing - tutorial, which leads you through the creation of tests for an actual Android application. -

    -

    Running Tests

    -

    - You run tests from the command line, either with Ant or with an - - Android Debug Bridge (adb) shell. -

    -

    Quick build and run with Ant

    -

    - You can use Ant to run all the tests in your test project, using the target - run-tests, which is created automatically when you create a test project with - the android tool. -

    -

    - This target re-builds your main project and test project if necessary, installs the test - application to the current AVD or device, and then runs all the test classes in the test - application. The results are directed to STDOUT. -

    -

    - You can update an existing test project to use this feature. To do this, use the - android tool with the update test-project option. This is described - in the section Updating a test project. -

    -

    Running tests on a device or emulator

    -

    - When you run tests from the command line with - - Android Debug Bridge (adb), you get more options for choosing the tests - to run than with any other method. You can select individual test methods, filter tests - according to their annotation, or specify testing options. Since the test run is controlled - entirely from a command line, you can customize your testing with shell scripts in various ways. -

    -

    - To run a test from the command line, you run adb shell to start a command-line - shell on your device or emulator, and then in the shell run the am instrument - command. You control am and your tests with command-line flags. -

    -

    - As a shortcut, you can start an adb shell, call am instrument, and - specify command-line flags all on one input line. The shell opens on the device or emulator, - runs your tests, produces output, and then returns to the command line on your computer. -

    -

    - To run a test with am instrument: -

    -
      -
    1. - If necessary, rebuild your main application and test package. -
    2. -
    3. - Install your test package and main application Android package files - (.apk files) to your current Android device or emulator
    4. -
    5. - At the command line, enter: -
      -$ adb shell am instrument -w <test_package_name>/<runner_class>
      -
      -

      - where <test_package_name> is the Android package name of your test - application, and <runner_class> is the name of the Android test - runner class you are using. The Android package name is the value of the - package attribute of the manifest element in the manifest file - (AndroidManifest.xml) of your test package. The Android test runner - class is usually {@link android.test.InstrumentationTestRunner}. -

      -

      - Your test results appear in STDOUT. -

      -
    6. -
    -

    - This operation starts an adb shell, then runs am instrument - with the specified parameters. This particular form of the command will run all of the tests - in your test package. You can control this behavior with flags that you pass to - am instrument. These flags are described in the next section. -

    -

    Using the am instrument Command

    -

    - The general syntax of the am instrument command is: -

    -
    -    am instrument [flags] <test_package>/<runner_class>
    -
    -

    - The main input parameters to am instrument are described in the following table: -

    - - - - - - - - - - - - - - - - -
    - Parameter - - Value - - Description -
    - <test_package> - - The Android package name of the test package. - - The value of the package attribute of the manifest - element in the test package's manifest file. -
    - <runner_class> - - The class name of the instrumented test runner you are using. - - This is usually {@link android.test.InstrumentationTestRunner}. -
    -

    - The flags for am instrument are described in the following table: -

    - - - - - - - - - - - - - - - - - - - - - -
    - Flag - - Value - - Description -
    - -w - - (none) - - Forces am instrument to wait until the instrumentation terminates - before terminating itself. The net effect is to keep the shell open until the tests - have finished. This flag is not required, but if you do not use it, you will not - see the results of your tests. -
    - -r - - (none) - - Outputs results in raw format. Use this flag when you want to collect - performance measurements, so that they are not formatted as test results. This flag is - designed for use with the flag -e perf true (documented in the section - Instrument options). -
    - -e - - <test_options> - - Provides testing options as key-value pairs. The - am instrument tool passes these to the specified instrumentation class - via its onCreate() method. You can specify multiple occurrences of - -e <test_options>. The keys and values are described in the - section am instrument options. -

    - The only instrumentation class that uses these key-value pairs is - {@link android.test.InstrumentationTestRunner} (or a subclass). Using them with - any other class has no effect. -

    -
    - -

    am instrument options

    -

    - The am instrument tool passes testing options to - InstrumentationTestRunner or a subclass in the form of key-value pairs, - using the -e flag, with this syntax: -

    -
    -    -e <key> <value>
    -
    -

    - Some keys accept multiple values. You specify multiple values in a comma-separated list. - For example, this invocation of InstrumentationTestRunner provides multiple - values for the package key: -

    -
    -$ adb shell am instrument -w -e package com.android.test.package1,com.android.test.package2 \
    -> com.android.test/android.test.InstrumentationTestRunner
    -
    -

    - The following table describes the key-value pairs and their result. Please review the - Usage Notes following the table. -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    KeyValueDescription
    - package - - <Java_package_name> - - The fully-qualified Java package name for one of the packages in the test - application. Any test case class that uses this package name is executed. Notice that - this is not an Android package name; a test package has a single - Android package name but may have several Java packages within it. -
    class<class_name> - The fully-qualified Java class name for one of the test case classes. Only this test - case class is executed. -
    <class_name>#method name - A fully-qualified test case class name, and one of its methods. Only this method is - executed. Note the hash mark (#) between the class name and the method name. -
    functrue - Runs all test classes that extend {@link android.test.InstrumentationTestCase}. -
    unittrue - Runs all test classes that do not extend either - {@link android.test.InstrumentationTestCase} or - {@link android.test.PerformanceTestCase}. -
    size - [small | medium | large] - - Runs a test method annotated by size. The annotations are @SmallTest, - @MediumTest, and @LargeTest. -
    perftrue - Runs all test classes that implement {@link android.test.PerformanceTestCase}. - When you use this option, also specify the -r flag for - am instrument, so that the output is kept in raw format and not - re-formatted as test results. -
    debugtrue - Runs tests in debug mode. -
    logtrue - Loads and logs all specified tests, but does not run them. The test - information appears in STDOUT. Use this to verify combinations of other - filters and test specifications. -
    emmatrue - Runs an EMMA code coverage analysis and writes the output to - /data//coverage.ec on the device. To override the file location, use the - coverageFile key that is described in the following entry. -

    - Note: This option requires an EMMA-instrumented build of the test - application, which you can generate with the coverage target. -

    -
    coverageFile<filename> - Overrides the default location of the EMMA coverage file on the device. Specify this - value as a path and filename in UNIX format. The default filename is described in the - entry for the emma key. -
    --e Flag Usage Notes -
      -
    • - am instrument invokes - {@link android.test.InstrumentationTestRunner#onCreate(Bundle)} - with a {@link android.os.Bundle} containing the key-value pairs. -
    • -
    • - The package key takes precedence over the class key. If you - specifiy a package, and then separately specify a class within that package, Android - will run all the tests in the package and ignore the class key. -
    • -
    • - The func key and unit key are mutually exclusive. -
    • -
    -

    Usage examples

    -

    -The following sections provide examples of using am instrument to run tests. -They are based on the following structure:

    -
      -
    • - The test package has the Android package name com.android.demo.app.tests -
    • -
    • - There are three test classes: -
        -
      • - UnitTests, which contains the methods - testPermissions and testSaveState. -
      • -
      • - FunctionTests, which contains the methods - testCamera, testXVGA, and testHardKeyboard. -
      • -
      • - IntegrationTests, - which contains the method testActivityProvider. -
      • -
      -
    • -
    • - The test runner is {@link android.test.InstrumentationTestRunner}. -
    • -
    -

    Running the entire test package

    -

    - To run all of the test classes in the test package, enter: -

    -
    -$ adb shell am instrument -w com.android.demo.app.tests/android.test.InstrumentationTestRunner
    -
    -

    Running all tests in a test case class

    -

    - To run all of the tests in the class UnitTests, enter: -

    -
    -$ adb shell am instrument -w  \
    -> -e class com.android.demo.app.tests.UnitTests \
    -> com.android.demo.app.tests/android.test.InstrumentationTestRunner
    -
    -

    - am instrument gets the value of the -e flag, detects the - class keyword, and runs all the methods in the UnitTests class. -

    -

    Selecting a subset of tests

    -

    - To run all of the tests in UnitTests, and the testCamera method in - FunctionTests, enter: -

    -
    -$ adb shell am instrument -w \
    -> -e class com.android.demo.app.tests.UnitTests,com.android.demo.app.tests.FunctionTests#testCamera \
    -> com.android.demo.app.tests/android.test.InstrumentationTestRunner
    -
    -

    - You can find more examples of the command in the documentation for - {@link android.test.InstrumentationTestRunner}. -

    diff --git a/docs/html/guide/developing/tools/MonkeyDevice.jd b/docs/html/guide/developing/tools/MonkeyDevice.jd deleted file mode 100644 index abcf8fdbb10f..000000000000 --- a/docs/html/guide/developing/tools/MonkeyDevice.jd +++ /dev/null @@ -1,1355 +0,0 @@ -page.title=MonkeyDevice -parent.title=monkeyrunner -parent.link=index.html -@jd:body - -

    - A monkeyrunner class that represents a device or emulator accessible by the workstation running -monkeyrunner. -

    -

    - This class is used to control an Android device or emulator. The methods send UI events, - retrieve information, install and remove applications, and run applications. -

    -

    - You normally do not have to create an instance of MonkeyDevice. Instead, you - use - -MonkeyRunner.waitForConnection() to create a new object from a connection to a device or -emulator. For example, instead of -using:

    -
    -newdevice = MonkeyDevice()
    -
    -

    - you would use: -

    -
    -newdevice = MonkeyRunner.waitForConnection()
    -
    -

    Summary

    - - - - - - - - - - - - - - - - - - - -
    Constants
    stringDOWN - Use this with the type argument of - press() or touch() - - to send a DOWN event. -
    stringUP - Use this with the type argument of - press() or touch() - - to send an UP event. -
    stringDOWN_AND_UP - Use this with the type argument of - press() or touch() - - to send a DOWN event immediately followed by an UP event. -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Methods
    - - void - - - - - broadcastIntent - - (string uri, - string action, - string data, - string mimetype, - iterable categories - dictionary extras, - component component, - iterable flags) - -
    - Broadcasts an Intent to this device, as if the Intent were coming from an - application. -
    -
    - - void - - - - - drag - - (tuple start, - tuple end, - float duration, - integer steps) - -
    - Simulates a drag gesture (touch, hold, and move) on this device's screen. -
    -
    - - object - - - - - getProperty - - (string key) - -
    - Given the name of a system environment variable, returns its value for this device. - The available variable names are listed in the - detailed description of this method. -
    -
    - - object - - - - - getSystemProperty - - (string key) - -
    -. The API equivalent of adb shell getprop <key>. This is provided for use - by platform developers. -
    -
    - - void - - - - - installPackage - - (string path) - -
    - Installs the Android application or test package contained in packageFile onto this - device. If the application or test package is already installed, it is replaced. -
    -
    - - dictionary - - - - - instrument - - (string className, - dictionary args) - -
    - Runs the specified component under Android instrumentation, and returns the results - in a dictionary whose exact format is dictated by the component being run. The - component must already be present on this device. -
    -
    - - void - - - - - press - - (string name, - dictionary type) - -
    - Sends the key event specified by type to the key specified by - keycode. -
    -
    - - void - - - - - reboot - - (string into) - -
    - Reboots this device into the bootloader specified by bootloadType. -
    -
    - - void - - - - - removePackage - - (string package) - -
    - Deletes the specified package from this device, including its data and cache. -
    -
    - - object - - - - - shell - - (string cmd) - -
    - Executes an adb shell command and returns the result, if any. -
    -
    - - void - - - - - startActivity - - (string uri, - string action, - string data, - string mimetype, - iterable categories - dictionary extras, - component component, - flags) - -
    - Starts an Activity on this device by sending an Intent constructed from the - supplied arguments. -
    -
    - - - - MonkeyImage - - - - - - - takeSnapshot() - - -
    - Captures the entire screen buffer of this device, yielding a - - - MonkeyImage - - object containing a screen capture of the current display. -
    -
    - - void - - - - - touch - - (integer x, - integer y, - integer type) - -
    - Sends a touch event specified by type to the screen location specified - by x and y. -
    -
    - - void - - - - - type - - (string message) - -
    - Sends the characters contained in message to this device, as if they - had been typed on the device's keyboard. This is equivalent to calling - press() for each keycode in message - using the key event type DOWN_AND_UP. -
    -
    - - void - - - - - wake - - () - -
    - Wakes the screen of this device. -
    -
    - -

    Constants

    - -
    -

    - - string - - DOWN -

    -
    -
    -

    - press() or - touch() value. - Specifies that a DOWN event type should be sent to the device, corresponding to - pressing down on a key or touching the screen. -

    -
    -
    -
    - -
    -

    - - string - - UP -

    -
    -
    -

    - press() or - touch() value. - Specifies that an UP event type should be sent to the device, corresponding to - releasing a key or lifting up from the screen. -

    -
    -
    -
    - - -
    -

    - - string - - DOWN_AND_UP -

    -
    -
    -

    - press(), - touch() or - type() value. - Specifies that a DOWN event type followed by an UP event type should be sent to the - device, corresponding to typing a key or clicking the screen. -

    -
    -
    -
    - - -

    Public Methods

    - -
    -

    - - void - - broadcastIntent - - ( - string uri, - string action, - string data, - string mimetype, - iterable categories - dictionary extras, - component component, - iterable flags) - -

    -
    - -
    -

    - Broadcasts an Intent to this device, as if the Intent were coming from an - application. See {@link android.content.Intent Intent} for more information about the - arguments. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    uri - The URI for the Intent. - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). -
    action - The action for this Intent - (see {@link android.content.Intent#setAction(java.lang.String) Intent.setAction()}). -
    data - The data URI for this Intent - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). -
    mimetype - The MIME type for the Intent - (see {@link android.content.Intent#setType(java.lang.String) Intent.setType()}). -
    categories - An iterable data structure containing strings that define categories for this - Intent - (see - {@link android.content.Intent#addCategory(java.lang.String) Intent.addCategory()}). -
    extras - A dictionary of extra data for this Intent - (see {@link android.content.Intent#putExtra(java.lang.String,java.lang.String) - Intent.putExtra()} - for an example). -

    - The key for each dictionary item should be a string. The item's value - can be any simple or structured data type. -

    -
    component - The component for this Intent (see {@link android.content.ComponentName}). - Using this argument will direct the Intent to a specific class within a specific - Android package. -
    flags - An iterable data structure containing flags that control how the Intent is handled - (see {@link android.content.Intent#setFlags(int) Intent.setFlags()}). -
    -
    -
    -
    - -
    -

    - - void - - drag - - ( - tuple start, - tuple end, - float duration, - integer steps) - -

    -
    - -
    -

    - Simulates a drag gesture (touch, hold, and move) on this device's screen. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - - - - - -
    start - The starting point of the drag gesture, in the form of a tuple - (x,y) where x and y are integers. -
    end - The end point of the drag gesture, in the form of a tuple (x,y) - where x and y are integers. -
    durationThe duration of the drag gesture in seconds. The default is 1.0 seconds.
    stepsThe number of steps to take when interpolating points. The default is 10.
    -
    -
    -
    - -
    -

    - - object - - getProperty - - (string key) - -

    -
    - -
    -

    - Given the name of a system environment variable, returns its value for this device. -

    -
    -
    -
    Arguments
    - - - - - -
    key - The name of the system environment variable. The available variable names are listed in - Table 1. Property variable names at the end of this topic. -
    -
    -
    -
    Returns
    -
      -
    • - The value of the variable. The data format varies according to the variable requested. -
    • -
    -
    -
    -
    - -
    -

    - - object - - getSystemProperty - - (string key) - -

    -
    - -
    -

    - Synonym for getProperty(). -

    -
    -
    -
    Arguments
    - - - - - -
    key - The name of the system environment variable. The available variable names are listed in - Table 1. Property Variable Names. -
    -
    -
    -
    Returns
    -
      -
    • - The value of the variable. The data format varies according to the variable requested. -
    • -
    -
    -
    -
    - -
    -

    - - void - - installPackage - - (string path) - -

    -
    - -
    -

    - Installs the Android application or test package contained in packageFile - onto this device. If the application or test package is already installed, it is - replaced. -

    -
    -
    -
    Arguments
    - - - - - -
    path - The fully-qualified path and filename of the .apk file to install. -
    -
    -
    -
    - -
    -

    - - dictionary - - instrument - - ( - string className, - dictionary args) - -

    -
    - -
    -

    - Runs the specified component with Android instrumentation, and returns the results - in a dictionary whose exact format is dictated by the component being run. The - component must already be present on this device. -

    -

    - Use this method to start a test case that uses one of Android's test case classes. - See Testing - Fundamentals to learn more about unit testing with the Android testing - framework. -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    className - The name of an Android component that is already installed on this device, in the - standard form packagename/classname, where packagename is the - Android package name of a .apk file on this device, and - classname is the class name of an Android component (Activity, - ContentProvider, Service, or BroadcastReceiver) in that file. Both - packagename and classname must be fully qualified. See - {@link android.content.ComponentName} for more details. -
    args - A dictionary containing flags and their values. These are passed to the component as it - is started. If the flag does not take a value, set its dictionary value to an empty - string. -
    -
    -
    Returns
    -
      -
    • -

      - A dictionary containing the component's output. The contents of the dictionary - are defined by the component itself. -

      -

      - If you use {@link android.test.InstrumentationTestRunner} as the class name in - the componentName argument, then the result dictionary contains - the single key "stream". The value of "stream" is a string containing - the test output, as if InstrumentationTestRunner was run from the - command line. The format of this output is described in - - Testing in Other IDEs. -

      -
    • -
    -
    -
    -
    -
    - -
    -

    - - void - - press - - (string name, - integer type) - -

    -
    -
    -

    - Sends the key event specified by type to the key specified by - keycode. -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    name - The name of the keycode to send. See {@link android.view.KeyEvent} for a list of - keycode names. Use the keycode name, not its integer value. -
    type - The type of key event to send. The allowed values are - DOWN, UP, and - DOWN_AND_UP. -
    -
    -
    -
    - -
    -

    - - void - - reboot - - (string bootloadType) - -

    -
    - -
    -

    - Reboots this device into the bootloader specified by bootloadType. -

    -
    -
    -
    Arguments
    - - - - - -
    into - The type of bootloader to reboot into. The allowed values are - "bootloader", "recovery", or "None". -
    -
    -
    -
    - -
    -

    - - void - - removePackage - - (string package) - -

    -
    - -
    -

    - Deletes the specified package from this device, including its data and cache. -

    -
    -
    -
    Arguments
    - - - - -
    package - The Android package name of an .apk file on this device. -
    -
    -
    -
    - -
    -

    - - object - - shell - - (string cmd) - -

    -
    -
    -

    - Executes an adb shell command and returns the result, if any. -

    -
    -
    -
    Arguments
    - - - - - -
    cmd - The command to execute in the adb shell. The form of these commands is - described in the topic Android - Debug Bridge. -
    -
    -
    -
    Returns
    -
      -
    • - The results of the command, if any. The format of the results is determined by the - command. -
    • -
    -
    -
    -
    - -
    -

    - - void - - startActivity - - ( - string uri, - string action, - string data, - string mimetype, - iterable categories - dictionary extras, - component component, - iterable flags) - -

    -
    -
    -

    - Starts an Activity on this device by sending an Intent constructed from the - supplied arguments. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    uri - The URI for the Intent. - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). -
    action - The action for the Intent - (see {@link android.content.Intent#setAction(java.lang.String) Intent.setAction()}). -
    data - The data URI for the Intent - (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). -
    mimetype - The MIME type for the Intent - (see {@link android.content.Intent#setType(java.lang.String) Intent.setType()}). -
    categories - An iterable data structure containing strings that define categories for the - Intent - (see - {@link android.content.Intent#addCategory(java.lang.String) Intent.addCategory()}). -
    extras - A dictionary of extra data for the Intent - (see - {@link android.content.Intent#putExtra(java.lang.String,java.lang.String) - Intent.putExtra()} - for an example). -

    - The key for each dictionary item should be a string. The item's value - can be any simple or structured data type. -

    -
    component - The component for the Intent - (see {@link android.content.ComponentName}). Using this argument will direct the - Intent to a specific class within a specific Android package. -
    flags - An iterable data structure containing flags that control how the Intent is handled - (see {@link android.content.Intent#setFlags(int) Intent.setFlags()}). -
    -
    -
    -
    - -
    -

    - - - - MonkeyImage - - - - takeSnapshot - - () - -

    -
    -
    -

    - Captures the entire screen buffer of this device, yielding a - screen capture of the current display. -

    -
    -
    -
    Returns
    -
      -
    • - A - MonkeyImage object containing the image of the current display. -
    • -
    -
    -
    -
    - -
    -

    - - void - - touch - - ( - integer x, - integer y, - string type) - -

    -
    -
    -

    - Sends a touch event specified by type to the screen location specified - by x and y. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - -
    x - The horizontal position of the touch in actual device pixels, starting from the left of - the screen in its current orientation. -
    y - The vertical position of the touch in actual device pixels, starting from the top of - the screen in its current orientation. -
    type - The type of key event to send. The allowed values are - DOWN, UP, and - DOWN_AND_UP. -
    -
    -
    -
    - -
    -

    - - void - - type - - (string message) - -

    -
    -
    -

    - Sends the characters contained in message to this device, as if they - had been typed on the device's keyboard. This is equivalent to calling - press() for each keycode in message - using the key event type DOWN_AND_UP. -

    -
    -
    -
    Arguments
    - - - - - -
    message - A string containing the characters to send. -
    -
    -
    -
    - -
    -

    - - void - - wake - - () - -

    -
    -
    -

    - Wakes the screen of this device. -

    -
    -
    -
    -
    -

    Appendix

    -

    - Table 1.Property variable names used with - getProperty() and - getSystemProperty(). -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Property Group - - Property - - Description - - Notes -
    buildboardCode name for the device's system board - See {@link android.os.Build} -
    brandThe carrier or provider for which the OS is customized.
    deviceThe device design name.
    fingerprintA unique identifier for the currently-running build.
    host
    IDA changelist number or label.
    modelThe end-user-visible name for the device.
    productThe overall product name.
    tagsComma-separated tags that describe the build, such as "unsigned" and "debug".
    typeThe build type, such as "user" or "eng".
    user
    CPU_ABI - The name of the native code instruction set, in the form CPU type plus - ABI convention. -
    manufacturerThe product/hardware manufacturer.
    version.incremental - The internal code used by the source control system to represent this version - of the software. -
    version.releaseThe user-visible name of this version of the software.
    version.sdkThe user-visible SDK version associated with this version of the OS.
    version.codename - The current development codename, or "REL" if this version of the software has been - released. -
    displaywidthThe device's display width in pixels. - See - {@link android.util.DisplayMetrics} for details. -
    heightThe device's display height in pixels.
    density - The logical density of the display. This is a factor that scales - DIP (Density-Independent Pixel) units to the device's resolution. DIP is adjusted so - that 1 DIP is equivalent to one pixel on a 160 pixel-per-inch display. For example, - on a 160-dpi screen, density = 1.0, while on a 120-dpi screen, density = .75. -

    - The value does not exactly follow the real screen size, but is adjusted to - conform to large changes in the display DPI. See - {@link android.util.DisplayMetrics#density} for more details. -

    -
    am.currentpackageThe Android package name of the currently running package. - The am.current keys return information about the currently-running - Activity. -
    action - The current activity's action. This has the same format as the name - attribute of the action element in a package manifest. -
    comp.class - The class name of the component that started the current Activity. See - comp.package for more details.
    comp.package - The package name of the component that started the current Activity. A component - is specified by a package name and the name of class that the package contains. -
    dataThe data (if any) contained in the Intent that started the current Activity.
    categoriesThe categories specified by the Intent that started the current Activity.
    clockrealtime - The number of milliseconds since the device rebooted, including deep-sleep - time. - - See {@link android.os.SystemClock} for more information. -
    uptime - The number of milliseconds since the device rebooted, not including - deep-sleep time -
    milliscurrent time since the UNIX epoch, in milliseconds.
    diff --git a/docs/html/guide/developing/tools/MonkeyImage.jd b/docs/html/guide/developing/tools/MonkeyImage.jd deleted file mode 100644 index 2efc37368729..000000000000 --- a/docs/html/guide/developing/tools/MonkeyImage.jd +++ /dev/null @@ -1,437 +0,0 @@ -page.title=MonkeyImage -parent.title=monkeyrunner -parent.link=index.html -@jd:body - - -

    - A monkeyrunner class to hold an image of the device or emulator's screen. The image is - copied from the screen buffer during a screenshot. This object's methods allow you to - convert the image into various storage formats, write the image to a file, copy parts of - the image, and compare this object to other MonkeyImage objects. -

    -

    - You do not need to create new instances of MonkeyImage. Instead, use - -MonkeyDevice.takeSnapshot() to create a new instance from a screenshot. For example, use: -

    -
    -newimage = MonkeyDevice.takeSnapshot()
    -
    -

    Summary

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Methods
    - - string - - - - - convertToBytes - - (string format) - -
    - Converts the current image to a particular format and returns it as a - string that you can then access as an iterable of binary bytes. -
    -
    - - tuple - - - - - getRawPixel - - (integer x, - integer y) - -
    - Returns the single pixel at the image location (x,y), as an - a tuple of integer, in the form (a,r,g,b). -
    -
    - - integer - - - - - getRawPixelInt - - (integer x, - integer y) - -
    - Returns the single pixel at the image location (x,y), as - a 32-bit integer. -
    -
    - - - MonkeyImage - - - - - - getSubImage - - (tuple rect) - -
    - Creates a new MonkeyImage object from a rectangular selection of the - current image. -
    -
    - - boolean - - - - - sameAs - - (MonkeyImage - other, - float percent) - -
    - Compares this MonkeyImage object to another and returns the result of - the comparison. The percent argument specifies the percentage - difference that is allowed for the two images to be "equal". -
    -
    - - void - - - - - writeToFile - - (string path, - string format) - -
    - Writes the current image to the file specified by filename, in the - format specified by format. -
    -
    - - -

    Public Methods

    - -
    -

    - - string - - convertToBytes - - ( - string format) - -

    -
    - -
    -

    - Converts the current image to a particular format and returns it as a string - that you can then access as an iterable of binary bytes. -

    -
    -
    -
    Arguments
    - - - - - -
    format - The desired output format. All of the common raster output formats are supported. - The default value is "png" (Portable Network Graphics). -
    -
    -
    -
    - -
    -

    - - tuple - - getRawPixel - - (integer x, - integer y) - -

    -
    - -
    -

    - Returns the single pixel at the image location (x,y), as an - a tuple of integer, in the form (a,r,g,b). -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    x - The horizontal position of the pixel, starting with 0 at the left of the screen in the - orientation it had when the screenshot was taken. -
    y - The vertical position of the pixel, starting with 0 at the top of the screen in the - orientation it had when the screenshot was taken. -
    -
    -
    -
    Returns
    -
      -
    • - A tuple of integers representing the pixel, in the form (a,r,g,b) where - a is the alpha channel value, and r, g, and b are the red, green, and blue values, - respectively. -
    • -
    -
    -
    -
    - -
    -

    - - tuple - - getRawPixelInt - - (integer x, - integer y) - -

    -
    - -
    -

    - Returns the single pixel at the image location (x,y), as an - an integer. Use this method to economize on memory. -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    x - The horizontal position of the pixel, starting with 0 at the left of the screen in the - orientation it had when the screenshot was taken. -
    y - The vertical position of the pixel, starting with 0 at the top of the screen in the - orientation it had when the screenshot was taken. -
    -
    -
    -
    Returns
    -
      -
    • - The a,r,g, and b values of the pixel as 8-bit values combined into a 32-bit - integer, with a as the leftmost 8 bits, r the next rightmost, and so forth. -
    • -
    -
    -
    -
    - -
    -

    - - - MonkeyImage - - - getSubImage - - (tuple rect) - -

    -
    - -
    -

    - Creates a new MonkeyImage object from a rectangular selection of the - current image. -

    -
    -
    -
    Arguments
    - - - - - -
    rect - A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel - position of the upper left-hand corner of the selection. w specifies the width of the - region, and h specifies its height, both in units of pixels. -

    - The image's orientation is the same as the screen orientation at the time the - screenshot was made. -

    -
    -
    -
    -
    Returns
    -
      -
    • - A new MonkeyImage object containing the selection. -
    • -
    -
    -
    -
    - -
    -

    - - boolean - - sameAs - - ( - - MonkeyImage - otherImage, - float percent - ) - -

    -
    - -
    -

    - Compares this MonkeyImage object to another and returns the result of - the comparison. The percent argument specifies the percentage - difference that is allowed for the two images to be "equal". -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    other - Another MonkeyImage object to compare to this one. -
    - percent - - A float in the range 0.0 to 1.0, inclusive, indicating - the percentage of pixels that need to be the same for the method to return - true. The default is 1.0, indicating that all the pixels - must match. -
    -
    -
    -
    Returns
    -
      -
    • - Boolean true if the images match, or boolean false otherwise. -
    • -
    -
    -
    -
    - -
    -

    - - void - - writeToFile - - (string filename, - string format) - -

    -
    - -
    -

    - Writes the current image to the file specified by filename, in the - format specified by format. -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    path - The fully-qualified filename and extension of the output file. -
    - format - - The output format to use for the file. If no format is provided, then the - method tries to guess the format from the filename's extension. If no - extension is provided and no format is specified, then the default format of - "png" (Portable Network Graphics) is used. -
    -
    -
    -
    diff --git a/docs/html/guide/developing/tools/MonkeyRunner.jd b/docs/html/guide/developing/tools/MonkeyRunner.jd deleted file mode 100644 index ea8d69ef7db2..000000000000 --- a/docs/html/guide/developing/tools/MonkeyRunner.jd +++ /dev/null @@ -1,448 +0,0 @@ -page.title=MonkeyRunner -parent.title=monkeyrunner -parent.link=index.html -@jd:body - - -

    - A monkeyrunner class that contains static utility methods. -

    -

    Summary

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Methods
    - - void - - - - - alert - - (string message, - string title, - string okTitle) - -
    - Displays an alert dialog to the process running the current - program. -
    -
    - - integer - - - - - choice - - (string message, - iterable choices, - string title) - -
    - Displays a dialog with a list of choices to the process running the current program. -
    -
    - - void - - - - - help - - (string format) - -
    - Displays the monkeyrunner API reference in a style similar to that of Python's - pydoc tool, using the specified format. -
    -
    - - string - - - - - input - - (string message, - string initialValue, - string title, - string okTitle, - string cancelTitle) - -
    - Displays a dialog that accepts input. -
    -
    - - void - - - - - sleep - - (float seconds) - -
    - Pauses the current program for the specified number of seconds. -
    -
    - - - MonkeyDevice - - - - - - waitForConnection - - (float timeout, - string deviceId) - -
    - Tries to make a connection between the monkeyrunner backend and the - specified device or emulator. -
    -
    - - -

    Public Methods

    - -
    -

    - - string - - alert - - ( - string message, - string title, - string okTitle) - -

    -
    - -
    -

    - Displays an alert dialog to the process running the current - program. The dialog is modal, so the program pauses until the user clicks the dialog's - button. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - -
    message - The message to display in the dialog. -
    title - The dialog's title. The default value is "Alert". -
    okTitle - The text displayed in the dialog button. The default value is "OK". -
    -
    -
    -
    - -
    -

    - - integer - - choice - - (string message, - iterable choices, - string title) - -

    -
    - -
    -

    - Displays a dialog with a list of choices to the process running the current program. The - dialog is modal, so the program pauses until the user clicks one of the dialog's - buttons. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - -
    message - The prompt message displayed in the dialog. -
    choices - A Python iterable containing one or more objects that are displayed as strings. The - recommended form is an array of strings. -
    - title - - The dialog's title. The default is "Input". -
    -
    -
    -
    Returns
    -
      -
    • - If the user makes a selection and clicks the "OK" button, the method returns - the 0-based index of the selection within the iterable. - If the user clicks the "Cancel" button, the method returns -1. -
    • -
    -
    -
    -
    - -
    -

    - - void - - help - - (string format) - -

    -
    - -
    -

    - Displays the monkeyrunner API reference in a style similar to that of Python's - pydoc tool, using the specified format. -

    -
    -
    -
    Arguments
    - - - - - -
    format - The markup format to use in the output. The possible values are "text" for plain text - or "html" for HTML. -
    -
    -
    -
    - -
    -

    - - string - - input - - (string message - string initialValue, - string title, - string okTitle, - string cancelTitle) - -

    -
    - -
    -

    - Displays a dialog that accepts input and returns it to the program. The dialog is - modal, so the program pauses until the user clicks one of the dialog's buttons. -

    -

    - The dialog contains two buttons, one of which displays the okTitle value - and the other the cancelTitle value. If the user clicks the okTitle button, - the current value of the input box is returned. If the user clicks the cancelTitle - button, an empty string is returned. -

    -
    -
    -
    Arguments
    - - - - - - - - - - - - - - - - - - - - - -
    message - The prompt message displayed in the dialog. -
    initialValue - The initial value to display in the dialog. The default is an empty string. -
    title - The dialog's title. The default is "Input". -
    okTitle - The text displayed in the okTitle button. The default is "OK". -
    cancelTitle - The text displayed in the cancelTitle button. The default is "Cancel". -
    -
    -
    -
    Returns
    -
      -
    • - If the user clicks the okTitle button, then the method returns the current value of - the dialog's input box. If the user clicks the cancelTitle button, the method returns - an empty string. -
    • -
    -
    -
    -
    - -
    -

    - - void - - sleep - - ( - float seconds - ) - -

    -
    - -
    -

    - Pauses the current program for the specified number of seconds. -

    -
    -
    -
    Arguments
    - - - - - -
    seconds - The number of seconds to pause. -
    -
    -
    -
    - -
    -

    - - - MonkeyDevice - - - waitForConnection - - (float timeout, - string deviceId) - -

    -
    - -
    -

    - Tries to make a connection between the monkeyrunner backend and the - specified device or emulator. -

    -
    -
    -
    Arguments
    - - - - - - - - - -
    timeout - The number of seconds to wait for a connection. The default is to wait forever. -
    - deviceId - - A regular expression that specifies the serial number of the device or emulator. See - the topic - Android Debug Bridge - for a description of device and emulator serial numbers. -
    -
    -
    -
    Returns
    -
      -
    • - A MonkeyDevice - instance for the device or emulator. Use this object to control and communicate with the - device or emulator. -
    • -
    -
    -
    -
    diff --git a/docs/html/guide/developing/tools/aapt.html b/docs/html/guide/developing/tools/aapt.html deleted file mode 100644 index e66a2019e494..000000000000 --- a/docs/html/guide/developing/tools/aapt.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/adb.jd b/docs/html/guide/developing/tools/adb.jd deleted file mode 100644 index 50c72365d03d..000000000000 --- a/docs/html/guide/developing/tools/adb.jd +++ /dev/null @@ -1,669 +0,0 @@ -page.title=Android Debug Bridge -parent.title=Tools -parent.link=index.html -@jd:body - -
    -
    -

    ADB quickview

    -
      -
    • Manage the state of an emulator or device
    • -
    • Run shell commands on a device
    • -
    • Manage port forwarding on an emulator or device
    • -
    • Copy files to/from an emulator or device
    • -
    - -

    In this document

    -
      -
    1. Issuing ADB Commands
    2. -
    3. Querying for Emulator/Device Instances
    4. -
    5. Directing Commands to a Specific Emulator/Device Instance
    6. -
    7. Installing an Application
    8. -
    9. Forwarding Ports
    10. -
    11. Copying Files to or from an Emulator/Device Instance
    12. -
    13. Listing of adb Commands
    14. -
    15. Issuing Shell Commands
    16. -
    17. Enabling logcat Logging
    18. -
    19. Stopping the adb Server
    20. -
    - -

    See also

    -
      -
    1. Emulator
    2. -
    - -
    -
    - -

    Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an -emulator instance or connected Android-powered device. It is a client-server program that includes -three components:

    - -
      -
    • A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.
    • -
    • A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.
    • -
    • A daemon, which runs as a background process on each emulator or device instance.
    • -
    - -

    You can find the {@code adb} tool in {@code <sdk>/platform-tools/}.

    - -

    When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.

    - -

    The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:

    - -

    -Emulator 1, console: 5554
    -Emulator 1, adb: 5555
    -Emulator 2, console: 5556
    -Emulator 2, adb: 5557 ... -

    - -

    As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554.

    - -

    Once the server has set up connections to all emulator instances, you can use adb commands to control and access those instances. Because the server manages connections to emulator/device instances and handles commands from multiple adb clients, you can control any emulator/device instance from any client (or from a script).

    - -

    The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.

    - - - -

    Issuing adb Commands

    - -

    You can issue adb commands from a command line on your development machine or from a script. The usage is:

    - -
    adb [-d|-e|-s <serialNumber>] <command> 
    - -

    When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.

    - - - -

    Querying for Emulator/Device Instances

    - -

    Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the devices command:

    - -
    adb devices
    - -

    In response, adb prints this status information for each instance:

    - -
      -
    • Serial number — A string created by adb to uniquely identify an emulator/device instance by its - console port number. The format of the serial number is <type>-<consolePort>. - Here's an example serial number: emulator-5554
    • -
    • State — The connection state of the instance. Three states are supported: -
        -
      • offline — the instance is not connected to adb or is not responding.
      • -
      • device — the instance is now connected to the adb server. Note that this state does not - imply that the Android system is fully booted and operational, since the instance connects to adb - while the system is still booting. However, after boot-up, this is the normal operational state of - an emulator/device instance.
      • -
      -
    • -
    - -

    The output for each instance is formatted like this:

    - -
    [serialNumber] [state]
    - -

    Here's an example showing the devices command and its output:

    - -
    $ adb devices
    -List of devices attached 
    -emulator-5554  device
    -emulator-5556  device
    -emulator-5558  device
    - -

    If there is no emulator/device running, adb returns no device.

    - - - - -

    Directing Commands to a Specific Emulator/Device Instance

    - -

    If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:

    - -
    adb -s <serialNumber> <command> 
    - -

    As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator/device instances.

    - -

    Here is an example:

    - -
    adb -s emulator-5556 install helloWorld.apk
    - -

    Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error. - - - -

    Installing an Application

    -

    You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install:

    - -
    adb install <path_to_apk>
    - -

    For more information about how to create an .apk file that you can install on an emulator/device -instance, see Building and Running

    - -

    Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.

    - - - - -

    Forwarding Ports

    - -

    You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:

    -
    adb forward tcp:6100 tcp:7100
    -

    You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:

    -
    adb forward tcp:6100 local:logd 
    - - - -

    Copying Files to or from an Emulator/Device Instance

    - -

    You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. Unlike the install command, which only copies an .apk file to a specific location, the pull and push commands let you copy arbitrary directories and files to any location in an emulator/device instance.

    - -

    To copy a file or directory (recursively) from the emulator or device, use

    -
    adb pull <remote> <local>
    - -

    To copy a file or directory (recursively) to the emulator or device, use

    -
    adb push <local> <remote>
    - -

    In the commands, <local> and <remote> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote).

    - -

    Here's an example:

    -
    adb push foo.txt /sdcard/foo.txt
    - - - -

    Listing of adb Commands

    - -

    The table below lists all of the supported adb commands and explains their meaning and usage.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CategoryCommandDescriptionComments
    Options-dDirect an adb command to the only attached USB device.Returns an error if more than one USB device is attached.
    -eDirect an adb command to the only running emulator instance.Returns an error if more than one emulator instance is running.
    -s <serialNumber>Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556").If not specified, adb generates an error.
    GeneraldevicesPrints a list of all attached emulator/device instances.See Querying for Emulator/Device Instances for more information.
    helpPrints a list of supported adb commands. 
    versionPrints the adb version number.  
    Debuglogcat [<option>] [<filter-specs>]Prints log data to the screen.  
    bugreportPrints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting.  
    jdwpPrints a list of available JDWP processes on a given device. You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example:
    - adb forward tcp:8000 jdwp:472
    - jdb -attach localhost:8000

    -
    Datainstall <path-to-apk>Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device.  
    pull <remote> <local>Copies a specified file from an emulator/device instance to your development computer.  
    push <local> <remote>Copies a specified file from your development computer to an emulator/device instance.  
    Ports and Networkingforward <local> <remote>Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance. Port specifications can use these schemes: -
    • tcp:<portnum>
    • -
    • local:<UNIX domain socket name>
    • -
    • dev:<character device name>
    • -
    • jdwp:<pid>
    -
    ppp <tty> [parm]...Run PPP over USB. -
      -
    • <tty> — the tty for PPP stream. For example dev:/dev/omap_csmi_ttyl.
    • -
    • [parm]... — zero or more PPP/PPPD options, such as defaultroute, local, notty, etc.
    - -

    Note that you should not automatically start a PPP connection.

    Scriptingget-serialnoPrints the adb instance serial number string.See Querying for Emulator/Device Instances for more information.
    get-statePrints the adb state of an emulator/device instance.
    wait-for-deviceBlocks execution until the device is online — that is, until the instance state is device.You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here's an example: -
    adb wait-for-device shell getprop
    - -Note that this command does not cause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the install requires the Android package manager, which is available only after the system is fully booted. A command such as - -
    adb wait-for-device install <app>.apk
    - -would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error.
    Serverstart-serverChecks whether the adb server process is running and starts it, if not. 
    kill-serverTerminates the adb server process. 
    ShellshellStarts a remote shell in the target emulator/device instance.See Issuing Shell Commands for more information.
    shell [<shellCommand>]Issues a shell command in the target emulator/device instance and then exits the remote shell.
    - - - - -

    Issuing Shell Commands

    - -

    Adb provides an ash shell that you can use to run a variety of commands on an emulator -or device. The command binaries are stored in the file system of the emulator or device, -in this location:

    - -
    /system/bin/...
    - -

    You can use the shell command to issue commands, with or without entering the adb remote shell on the emulator/device.

    - -

    To issue a single command without entering a remote shell, use the shell command like this:

    - -
    adb [-d|-e|-s {<serialNumber>}] shell <shellCommand>
    - -

    To drop into a remote shell on a emulator/device instance, use the shell command like this:

    - -
    adb [-d|-e|-s {<serialNumber>}] shell
    - -

    When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.

    - -

    The sections below provide more information about shell commands that you can use.

    - - - -

    Examining sqlite3 Databases from a Remote Shell

    - -

    From an adb remote shell, you can use the -sqlite3 command-line program to -manage SQLite databases created by Android applications. The -sqlite3 tool includes many useful commands, such as -.dump to print out the contents of a table and -.schema to print the SQL CREATE statement for an existing table. -The tool also gives you the ability to execute SQLite commands on the fly.

    - -

    To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.

    - -

    Here's an example:

    - -
    $ adb -s emulator-5554 shell
    -# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db
    -SQLite version 3.3.12
    -Enter ".help" for instructions
    -.... enter commands, then quit...
    -sqlite> .exit 
    - -

    Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D. - - - - -

    UI/Application Exerciser Monkey

    - -

    The Monkey is a program that runs on your emulator or device and generates pseudo-random -streams of user events such as clicks, touches, or gestures, as well as a number of system-level -events. You can use the Monkey to stress-test applications that you are developing, -in a random yet repeatable manner.

    - -

    The simplest way to use the monkey is with the following command, which will launch your -application and send 500 pseudo-random events to it.

    - -
    $ adb shell monkey -v -p your.package.name 500
    - -

    For more information about command options for Monkey, see the complete -UI/Application Exerciser Monkey documentation page.

    - - - - -

    Other Shell Commands

    - -

    The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.

    - -
    adb shell ls /system/bin
    - -

    Help is available for most of the commands.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Shell CommandDescriptionComments
    dumpsysDumps system data to the screen.The Dalvik Debug Monitor Server -(DDMS) tool offers integrated debug environment that you may find easier to use.
    dumpstateDumps state to a file.
    logcat [<option>]... [<filter-spec>]...Enables radio logging and prints output to the screen.
    dmesgPrints kernel debugging messages to the screen.
    startStarts (restarts) an emulator/device instance. 
    stopStops execution of an emulator/device instance. 
    - - - -

    Enabling logcat Logging

    - -

    The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command.

    - - - -

    Using logcat Commands

    - -

    You can use the logcat command to view and follow the contents of the system's log buffers. The general usage is:

    - -
    [adb] logcat [<option>] ... [<filter-spec>] ...
    - -

    The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options.

    - -

    You can use the logcat command from your development computer or from a remote adb shell in an emulator/device instance. To view log output in your development computer, you use

    - -
    $ adb logcat
    - -

    and from a remote adb shell you use

    - -
    # logcat
    - - - -

    Filtering Log Output

    - -

    Every Android log message has a tag and a priority associated with it.

    - -
      -
    • The tag of a log message is a short string indicating the system component from which the message originates (for example, "View" for the view system).
    • - -
    • The priority is one of the following character values, ordered from lowest to highest priority:
    • - -
        -
      • V — Verbose (lowest priority)
      • -
      • D — Debug
      • -
      • I — Info (default priority)
      • -
      • W — Warning
      • -
      • E — Error
      • -
      • F — Fatal
      • -
      • S — Silent (highest priority, on which nothing is ever printed)
      • -
      -
    - -

    You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns -of each message, given as <priority>/<tag>.

    - -

    Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":

    - -
    I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}
    - -

    To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.

    - -

    A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited. The default output is to show all log messages with the Info priority (*:I).

    - -

    Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

    - -
    adb logcat ActivityManager:I MyApp:D *:S
    - -

    The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.

    - -

    The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

    - -
    adb logcat *:W
    - -

    If you're running logcat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by exporting a value for the environment variable ANDROID_LOG_TAGS:

    - -
    export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"
    - -

    Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are running logcat from a remote shell or using adb shell logcat.

    - - - - -

    Controlling Log Output Format

    - -

    Log messages contain a number of metadata fields, in addition to the tag and priority. You can modify the output format for messages so that they display a specific metadata field. To do so, you use the -v option and specify one of the supported output formats listed below.

    - -
      -
    • brief — Display priority/tag and the PID of process issuing the message (the default format).
    • -
    • process — Display PID only.
    • -
    • tag — Display the priority/tag only.
    • -
    • raw — Display the raw log message, with no other metadata fields.
    • -
    • time — Display the date, invocation time, priority/tag, and PID of the process issuing the message.
    • -
    • threadtime — Display the date, invocation time, priority, tag, and the PID and TID of the thread issuing the message.
    • -
    • long — Display all metadata fields and separate messages with a blank lines.
    • -
    - -

    When starting logcat, you can specify the output format you want by using the -v option:

    - -
    [adb] logcat [-v <format>]
    - -

    Here's an example that shows how to generate messages in thread output format:

    - -
    adb logcat -v thread
    - -

    Note that you can only specify one output format with the -v option.

    - - - -

    Viewing Alternative Log Buffers

    - -

    The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can start logcat with the -b option, to request viewing of an alternate circular buffer. You can view any of these alternate buffers:

    - -
      -
    • radio — View the buffer that contains radio/telephony related messages.
    • -
    • events — View the buffer containing events-related messages.
    • -
    • main — View the main log buffer (default)
    • -
    - -

    The usage of the -b option is:

    - -
    [adb] logcat [-b <buffer>]
    - -

    Here's an example of how to view a log buffer containing radio and telephony messages:

    - -
    adb logcat -b radio
    - - - -

    Viewing stdout and stderr

    - -

    By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In -processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priority I.

    - -

    To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here's how you do it:

    - -
    $ adb shell stop
    -$ adb shell setprop log.redirect-stdio true
    -$ adb shell start
    - -

    The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop -on the device.

    - - - -

    Listing of logcat Command Options

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    OptionDescription
    -b <buffer>Loads an alternate log buffer for viewing, such as event or radio. The main buffer is used by default. See Viewing Alternative Log Buffers.
    -cClears (flushes) the entire log and exits.
    -dDumps the log to the screen and exits.
    -f <filename>Writes log message output to <filename>. The default is stdout.
    -gPrints the size of the specified log buffer and exits.
    -n <count>Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option.
    -r <kbytes>Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option.
    -sSets the default filter spec to silent.
    -v <format>Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.
    - - - -

    Stopping the adb Server

    - -

    In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.

    - -

    To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.

    - - diff --git a/docs/html/guide/developing/tools/adt.jd b/docs/html/guide/developing/tools/adt.jd deleted file mode 100644 index d473e8589953..000000000000 --- a/docs/html/guide/developing/tools/adt.jd +++ /dev/null @@ -1,527 +0,0 @@ -page.title=Android Developer Tools -@jd:body - - - -

    ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of - tools that are integrated with the Eclipse IDE. It offers you access to many features that help - you develop Android applications quickly. ADT - provides GUI access to many of the command line SDK tools as well as a UI design tool for rapid - prototyping, designing, and building of your application's user interface.

    - -

    Because ADT is a plugin for Eclipse, you get the functionality of a well-established IDE, - along with Android-specific features that are bundled with ADT. The following - describes important features of Eclipse and ADT:

    - -
    -
    Integrated Android project creation, building, packaging, installation, and - debugging
    - -
    ADT integrates many development workflow tasks into Eclipse, making it easy for you to - rapidly develop and test your Android applications.
    - -
    SDK Tools integration
    - -
    Many of the SDK tools are integrated into Eclipse's menus, - perspectives, or as a part of background processes ran by ADT.
    - -
    Java programming language and XML editors
    - -
    The Java programming language editor contains common IDE features such as compile time - syntax checking, auto-completion, and integrated documentation for the Android framework APIs. - ADT also provides custom XML editors that let you - edit Android-specific XML files in a form-based UI. A graphical layout editor lets you design - user interfaces with a drag and drop interface.
    - -
    Integrated documentation for Android framework APIs
    -
    You can access documentation by hovering over classes, methods, or variables.
    -
    - -

    You can find the most up-to-date and more detailed information about changes and new features -on the Recent Changes page at the Android Tools -Project site.

    - -

    SDK Tools Integration

    - - - -

    Many of the tools that you can start or run from the command line are integrated into ADT. - They include:

    - -
      -
    • Traceview: - Allows you to profile your program's execution - (Window > Open Perspective > Traceview).
    • - -
    • android: Provides access to - the Android SDK Manager and AVD Manager. Other android features such as creating or - updating projects (application and library) are integrated throughout the Eclipse IDE.
    • - -
    • Hierarchy - Viewer: Allows you to visualize your application's view hierarchy to find inefficiencies - (Window > Open Perspective > Hierarchy Viewer).
    • - -
    • Pixel - Perfect: Allows you to closely examine your UI to help with designing and building. - (Window > Open Perspective > Pixel Perfect).
    • - -
    • DDMS: Provides - debugging features including: screen capturing, thread and heap information, and logcat - (Window > Open Perspective > DDMS).
    • - -
    • adb: Provides access to - a device from your development system. Some features of - adb are integrated into ADT such as project installation (Eclipse run menu), - file transfer, device enumeration, and logcat (DDMS). You must access the more advanced - features of adb, such as shell commands, from the command line.
    • - -
    • ProGuard: Allows code obfuscation, - shrinking, and optimization. ADT integrates ProGuard as part of the build, if you enable it.
    • -
    - -

    Code Editors

    - -

    In addition to Eclipse's standard editor features, ADT provides custom XML editors to help - you create and edit Android manifests, resources, menus, and layouts in a form-based or graphical - mode. Double-clicking on an XML file in Eclipse's package explorer opens the - appropriate XML editor. - -

    - -

    Note: You can edit Android-specific XML files (such as a layout -or manifest) in both a graphical mode and also an XML markup mode. You can switch between -these modes with the pair of tabs at the bottom of each custom XML editor.

    - -

    In addition, some special file types that don't have custom editors, such as drawables, animations, - and color files offer editing enhancements such as XML tag completion.

    - -

    ADT provides the following custom, form-based XML editors:

    - -
    - -
    Graphical Layout Editor
    - -
    Edit and design your XML layout files with a drag and drop interface. The layout editor - renders your interface as well, offering you a preview as you design your layouts. This editor - is invoked when you open an XML file with a view declared (usually declared in - res/layout. For more information, see Graphical Layout - Editor.
    - -
    Android Manifest Editor
    - -
    Edit Android manifests with a simple graphical interface. This editor is invoked - when you open an AndroidManifest.xml file.
    - -
    Menu Editor
    - -
    Edit menu groups and items with a simple graphical interface. This editor is - invoked when you open an XML file with a <menu> declared (usually located in - the res/menu folder).
    - -
    Resources Editor
    - -
    Edit resources with a simple graphical interface. This editor is invoked when - you open an XML file with a <resources> tag declared.
    - -
    XML Resources Editor
    - -
    Edit XML resources with a simple graphical interface. This editor is invoked - when you open an XML file.
    -
    - - -

    Resource linking enhancements

    -

    In addition to the normal code editing features of Eclipse, ADT provides enhancements to the Android - development experience that allow you to quickly jump to declarations of various types of resources such - as strings or layout files. You can access these enhancements by holding down the control key and - clicking on the following items: - -

      - -
    • A resource identifier, such as R.id.button1, jumps - to the XML definition of the view.
    • - -
    • A declaration in the R.java file, such as public - static final int Button01=0x7f050000", jumps to the corresponding XML definition.
    • - -
    • An activity or service definition in your manifest, such as - <activity android:name=".TestActivity">, jumps to the corresponding Java class. You can - jump from an activity definition (or service definition) into the corresponding Java class.
    • - -
    • You can jump to any value definition (e.g. @string:foo), regardless of -which XML file - "foo" is defined in.
    • - -
    • Any file-based declaration, such as @layout/bar, opens the file.
    • - -
    • Non-XML resources, such as @drawable/icon, launches - Eclipse's default application for the given file type, which in this case is an - image.
    • - -
    • @android namespace resources opens the resources found in - the SDK install area.
    • - -
    • Custom views in XML layouts, such as <foo.bar.MyView></foo.bar.MyView>, - or <view class="foo.bar.MyView">) jump to the corresponding custom view classes.
    • - -
    • An XML attribute such as @android:string/ok or android.R.string.id in Java code - opens the file that declares the strings. The XML tab opens when doing this, not - the form-based editor.
    • - -
    - -

    Graphical Layout Editor

    - -

    ADT provides many features to allow you to design and build your application's user interface. - Many of these features are in the graphical layout editor, which you can access by opening one of - your application's XML layout files in Eclipse. -

    - -

    The graphical layout editor is the main screen that you use to visually design and build your - UI. It is split up into the following parts:

    - -
    -
    Canvas
    - -
    In the middle of the editor is the canvas. It provides the rendered view of your - layout and supports dragging and dropping of UI widgets - directly from the palette. You can select the platform version used to render the items in - the canvas. Each platform version has its own look and feel, which might be the similar to or - radically different from another platform version. The canvas renders the appropriate look - and feel for the currently selected platform version. - This platform version does not need to be the same as the version that your - application targets. - -

    The canvas also provides - context-sensitive actions in the layout actions bar, such as adjusting layout margins and -orientation. - The layout actions bar displays available actions depending on the selected UI element in the - canvas.

    -
    - -
    Outline
    - -
    On the right side of the editor is the outline view. It displays a hierarchical - view of your layout where you can do things such as reorder of views. The outline - view exposes similar functionality as the canvas but displays your layout in an ordered - list instead of a rendered preview.
    - -
    Palette
    - -
    On the left side of the editor is the palette. It provides a set of widgets that - you can drag onto the canvas. The palette shows rendered previews of the - widgets for easy lookup of desired UI widgets.
    - -
    Configuration Chooser
    - -
    At the top of the editor is the configuration chooser. - It provides options to change a layout's rendering mode or screen type.
    -
    - - graphical layout editor screenshot - -

    Figure 1. Graphical layout editor

    - -

    Canvas and outline view

    - - - -

    The canvas is the area where you can drag and drop UI widgets from the palette to design your - layout. The canvas offers a rendered preview of your layout depending on factors such as the - selected platform version, screen orientation, and currently selected theme that you specify in - the configuration chooser. You can also drag and drop - items into the outline view, which displays your layout in a hierarchical list. The outline view - exposes much of the same functionality as the canvas but offers another method of organization - that is beneficial for ordering and quickly selecting items. When you right-click a specific item - in the canvas or outline view, you can access a context-sensitive menu that lets you modify the - following attributes of the layout or view:

    - -
    -
    View and layout properties
    - -
    - When you right-click a view or layout in the canvas or outline view, it brings up a - context-sensitive menu that lets you set things such as: - -
      -
    • ID of the view or layout
    • - -
    • Text of the view
    • - -
    • Layout width
    • - -
    • Layout height
    • - -
    • Properties such as alpha or clickable
    • -
    -
    - -
    Animation preview and creation
    - -
    - If your layout or view is animated, you can preview the animation directly in the canvas - (when you select Android 3.0 or later as the platform version in the configuration chooser). - Right-click an item in the canvas and select Play Animation. If - animation is not associated with item, an option is available in the menu to create one. - -

    View the segment on the animation features for more - information.

    -
    - -
    Extract as Include
    - -
    You can extract parts of a current layout into its own layout file, - which you can then include in any layout with a single line of XML. See Layout Refactoring Support for more information.
    -
    - -

    Other canvas features

    - -

    The canvas has additional features not available in the outline view:

    - -
      - -
    • Edit views with the layout actions bar: The context-sensitive layout actions bar allows you to - edit how a view is laid out in your UI. The available actions depend on the currently - selected view and its parent layout. Some common actions include - toggling the fill mode of the view and specifying margins. For instance, if you select a - {@link android.widget.Button} - in a {@link android.widget.LinearLayout}, you see actions related to the {@link -android.widget.LinearLayout}, such as a toggle to switch - between horizontal and vertical layout, and a toggle to control whether its children are - aligned along their text baseline. You will also see toolbar actions to control the individual - layout attributes of the child, such as whether the child should stretch out to match its - parent's width and height, a dropdown action to set the child's layout gravity, a button to open - a margin editor, and a layout weight editor.
    • - -
    • Edit a nested layout in its current context: If you are editing a layout - that includes another layout, you can edit the included layout in the layout that included - it.
    • - -
    • Preview drag and drop location: When you drag and drop a UI widget onto the canvas, ruler - markers appear showing you the approximate location of the UI widget depending on the - type of layout, such as {@link android.widget.RelativeLayout} or {@link - android.widget.LinearLayout}.
    • - -
    • Preview animations: You can preview view and layout animations when you select Android 2.1 - or later for the platform version in the configuration bar.
    • - -
    • Render layouts in real-time: Layouts are rendered as accurately as possible according to - the platform version, including the appropriate system and action bars.
    • - -
    • Support for fragments: Fragments can be rendered in the same screen as the layout that - includes the fragments.
    • - -
    - - screenshot of the canvas - -

    Figure 2. Canvas portion of the layout editor showing - a rendered preview of an application

    - - screenshot of the outline view - -

    Figure 3. Outline view showing current layout's structure

    - -

    Palette

    - - - -

    The palette contains the UI widgets that you can drag and drop onto the canvas and add to your - layout. The pallete categorizes the widgets and shows rendered previews - for easier lookup. The main features of the palette include:

    - -
      -
    • Different modes of rendered previews include: icons only, icons and text, tiny previews, - small previews, and previews (rendered in real size). Previews are only available for layouts - rendered with the latest revisions of Android 2.1 (API Level 7) or later.
    • - -
    • Custom views in your project or library projects are added under custom views - category.
    • - -
    • Arrange UI widgets alphabetically or by category.
    • -
    - palette screenshot - -

    Figure 4. Palette showing available UI widgets

    - -

    Configuration chooser

    - - - - -

    The configuration chooser allows you to create and configure different configurations of - a layout for different situations, such as one for landscape and one for portrait mode. You can - set the following options for each configuration of a layout: -

    -
      -
    • Screen type combo box: Predefined screen settings for common device configurations. You - can also create your own by selecting Custom....
    • - -
    • Screen orientation combo box: Portrait or Landscape screen orientation.
    • - -
    • Theme combo box: Predefined themes or a custom theme that you have created.
    • - -
    • Platform combo box: Platform version used to render the canvas and palette as well as - displaying appropriate themes.
    • - -
    • Custom layout combo boxes: The locale, dock, and time of day combo boxes let you select - different versions of the same layout depending on the device's current state. You can - create a new version of a layout with the Create button.
    • -
    - - - - -

    Figure 5. Configuration chooser

    - -

    Layout Refactoring Support

    - - - -

    In both the graphical and XML layout editor, there are many features that help you quickly - refactor your layouts. The following list describes the major refactoring support:

    - -
    - -
    Change layout
    -
    This lets you change the layout on the fly and re-renders the canvas for you. - You can apply this refactoring to any layout and the layout is converted to the new type if - possible. In many cases, the opening and closing tags of the layout's XML element are changed - along with things such as ID attributes and their references. However, for some supported - types, ADT attempts to preserve the layout, such as changing a {@link - android.widget.LinearLayout} to a {@link android.widget.RelativeLayout}.
    - -
    Change widget
    -
    This lets you select one or more widgets and converts them to a new widget type. In - addition to changing the element name, it also removes any - attributes that are not supported by the new widget type and adds in any mandatory attributes - required by the new widget type. If the current ID of a widget includes the - current widget type in its ID (such as a <Button> widget named - "button1"), then the ID is changed to match the new widget type and all - references are updated.
    - -
    Extract as include
    -
    This lets you extract views inside of an existing layout into their own separate layout - file. An include tag that points to the newly created layout file is inserted - into the existing layout file. Right-click the view or layout and select Extract as - Include....
    - -
    Extract string
    -
    Extract strings from either XML or Java files into their own separate resource file.
    - -
    Extract style
    -
    Extract style-related attributes from a layout and define them in a new - styles.xml file. You can select multiple views and this refactoring extracts all - of the same styles into one style and assigns that style to all the views that use it.
    - -
    Wrap-in container
    -
    This lets you select one or more sibling elements and wrap them in a new container. This - can be applied to the root element as well, in which case the namespace declaration attributes - will be transferred to the new root. This refactoring also transfers layout_ - attribute references to the new root, For example, suppose you have a {@link android.widget.RelativeLayout}. - If other widgets have layout constraints pointing to your widget, wrapping the widget causes - these constraints to point to the parent instead.
    - -
    Quick Assistant
    -
    Provides refactoring suggestions depending on the current context. Press - Ctrl-1 (or Cmd-1 on - Mac) in an editor, and Eclipse provides a list of possible refactorings depending on the - context. The Quick Assistant provides fast access to all of the above refactorings, where applicable. - For example, if you are editing an XML value and decide you want to extract it out - as a string, place the text cursor in the string and press Ctrl-1 to see the refactoring context - menu.
    -
    diff --git a/docs/html/guide/developing/tools/aidl.jd b/docs/html/guide/developing/tools/aidl.jd deleted file mode 100644 index 731aef7e7751..000000000000 --- a/docs/html/guide/developing/tools/aidl.jd +++ /dev/null @@ -1,465 +0,0 @@ -page.title=Android Interface Definition Language (AIDL) -@jd:body - - - - - -

    AIDL (Android Interface Definition Language) is similar to other IDLs you might have -worked with. It allows you to define the programming interface that both -the client and service agree upon in order to communicate with each other using -interprocess communication (IPC). On Android, one process cannot normally access the -memory of another process. So to talk, they need to decompose their objects into primitives that the -operating system can understand, and marshall the objects across that boundary for you. The code to -do that marshalling is tedious to write, so Android handles it for you with AIDL.

    - -

    Note: Using AIDL is necessary only if you allow clients from -different applications to access your service for IPC and want to handle multithreading in your -service. If you do not need to perform concurrent IPC across -different applications, you should create your interface by implementing a -Binder or, if you want to perform IPC, but do not need to handle multithreading, -implement your interface using a Messenger. -Regardless, be sure that you understand Bound Services before -implementing an AIDL.

    - -

    Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are -direct function calls. You should not make assumptions about the thread in which the call -occurs. What happens is different depending on whether the call is from a thread in the -local process or a remote process. Specifically:

    - -
      -
    • Calls made from the local process are executed in the same thread that is making the call. If -this is your main UI thread, that thread continues to execute in the AIDL interface. If it is -another thread, that is the one that executes your code in the service. Thus, if only local -threads are accessing the service, you can completely control which threads are executing in it (but -if that is the case, then you shouldn't be using AIDL at all, but should instead create the -interface by implementing a -Binder).
    • - -
    • Calls from a remote process are dispatched from a thread pool the platform maintains inside of -your own process. You must be prepared for incoming calls from unknown threads, with multiple calls -happening at the same time. In other words, an implementation of an AIDL interface must be -completely thread-safe.
    • - -
    • The {@code oneway} keyword modifies the behavior of remote calls. When used, a remote call does -not block; it simply sends the transaction data and immediately returns. -The implementation of the interface eventually receives this as a regular call from the {@link -android.os.Binder} thread pool as a normal remote call. If {@code oneway} is used with a local call, -there is no impact and the call is still synchronous.
    • -
    - - -

    Defining an AIDL Interface

    - -

    You must define your AIDL interface in an {@code .aidl} file using the Java -programming language syntax, then save it in the source code (in the {@code src/} directory) of both -the application hosting the service and any other application that binds to the service.

    - -

    When you build each application that contains the {@code .aidl} file, the Android SDK tools -generate an {@link android.os.IBinder} interface based on the {@code .aidl} file and save it in -the project's {@code gen/} directory. The service must implement the {@link android.os.IBinder} -interface as appropriate. The client applications can then bind to the service and call methods from -the {@link android.os.IBinder} to perform IPC.

    - -

    To create a bounded service using AIDL, follow these steps:

    -
      -
    1. Create the .aidl file -

      This file defines the programming interface with method signatures.

      -
    2. -
    3. Implement the interface -

      The Android SDK tools generate an interface in the Java programming language, based on your -{@code .aidl} file. This interface has an inner abstract class named {@code Stub} that extends -{@link android.os.Binder} and implements methods from your AIDL interface. You must extend the -{@code Stub} class and implement the methods.

      -
    4. -
    5. Expose the interface to clients -

      Implement a {@link android.app.Service Service} and override {@link -android.app.Service#onBind onBind()} to return your implementation of the {@code Stub} -class.

      -
    6. -
    - -

    Caution: Any changes that you make to your AIDL interface after -your first release must remain backward compatible in order to avoid breaking other applications -that use your service. That is, because your {@code .aidl} file must be copied to other applications -in order for them to access your service's interface, you must maintain support for the original -interface.

    - - -

    1. Create the .aidl file

    - -

    AIDL uses a simple syntax that lets you declare an interface with one or more methods that can -take parameters and return values. The parameters and return values can be of any type, even other -AIDL-generated interfaces.

    - -

    You must construct the {@code .aidl} file using the Java programming language. Each {@code .aidl} -file must define a single interface and requires only the interface declaration and method -signatures.

    - -

    By default, AIDL supports the following data types:

    - -
      -
    • All primitive types in the Java programming language (such as {@code int}, {@code long}, -{@code char}, {@code boolean}, and so on)
    • -
    • {@link java.lang.String}
    • -
    • {@link java.lang.CharSequence}
    • -
    • {@link java.util.List} -

      All elements in the {@link java.util.List} must be one of the supported data types in this -list or one of the other AIDL-generated interfaces or parcelables you've declared. A {@link -java.util.List} may optionally be used as a "generic" class (for example, -List<String>). -The actual concrete class that the other side receives is always an {@link -java.util.ArrayList}, although the method is generated to use the {@link -java.util.List} interface.

      -
    • -
    • {@link java.util.Map} -

      All elements in the {@link java.util.Map} must be one of the supported data types in this -list or one of the other AIDL-generated interfaces or parcelables you've declared. Generic maps, -(such as those of the form -{@code Map<String,Integer>} are not supported. The actual concrete class that the other side -receives is always a {@link java.util.HashMap}, although the method is generated to -use the {@link java.util.Map} interface.

      -
    • -
    - -

    You must include an {@code import} statement for each additional type not listed above, even if -they are defined in the same package as your interface.

    - -

    When defining your service interface, be aware that:

    -
      -
    • Methods can take zero or more parameters, and return a value or void.
    • -
    • All non-primitive parameters require a directional tag indicating which way the data goes. -Either in, out, or inout (see the example below). -

      Primitives are in by default, and cannot be otherwise.

      -

      Caution: You should limit the direction to what is truly -needed, because marshalling parameters is expensive.

    • -
    • All code comments included in the {@code .aidl} file are included in the generated {@link -android.os.IBinder} interface (except for comments before the import and package -statements).
    • -
    • Only methods are supported; you cannot expose static fields in AIDL.
    • -
    - -

    Here is an example {@code .aidl} file:

    - -
    -// IRemoteService.aidl
    -package com.example.android;
    -
    -// Declare any non-default types here with import statements
    -
    -/** Example service interface */
    -interface IRemoteService {
    -    /** Request the process ID of this service, to do evil things with it. */
    -    int getPid();
    -
    -    /** Demonstrates some basic types that you can use as parameters
    -     * and return values in AIDL.
    -     */
    -    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
    -            double aDouble, String aString);
    -}
    -
    - -

    Simply save your {@code .aidl} file in your project's {@code src/} directory and when you -build your application, the SDK tools generate the {@link android.os.IBinder} interface file in your -project's {@code gen/} directory. The generated file name matches the {@code .aidl} file name, but -with a {@code .java} extension (for example, {@code IRemoteService.aidl} results in {@code -IRemoteService.java}).

    - -

    If you use Eclipse, the incremental build generates the binder class almost immediately. If you -do not use Eclipse, then the Ant tool generates the binder class next time you build your -application—you should build your project with ant debug (or ant -release) as soon as you're finished writing the {@code .aidl} file, so that your code can -link against the generated class.

    - - -

    2. Implement the interface

    - -

    When you build your application, the Android SDK tools generate a {@code .java} interface file -named after your {@code .aidl} file. The generated interface includes a subclass named {@code Stub} -that is an abstract implementation of its parent interface (for example, {@code -YourInterface.Stub}) and declares all the methods from the {@code .aidl} file.

    - -

    Note: {@code Stub} also -defines a few helper methods, most notably {@code asInterface()}, which takes an {@link -android.os.IBinder} (usually the one passed to a client's {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method) and -returns an instance of the stub interface. See the section Calling an IPC -Method for more details on how to make this cast.

    - -

    To implement the interface generated from the {@code .aidl}, extend the generated {@link -android.os.Binder} interface (for example, {@code YourInterface.Stub}) and implement the methods -inherited from the {@code .aidl} file.

    - -

    Here is an example implementation of an interface called {@code IRemoteService} (defined by the -{@code IRemoteService.aidl} example, above) using an anonymous instance:

    - -
    -private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    -    public int getPid(){
    -        return Process.myPid();
    -    }
    -    public void basicTypes(int anInt, long aLong, boolean aBoolean,
    -        float aFloat, double aDouble, String aString) {
    -        // Does nothing
    -    }
    -};
    -
    - -

    Now the {@code mBinder} is an instance of the {@code Stub} class (a {@link android.os.Binder}), -which defines the RPC interface for the service. In the next step, this instance is exposed to -clients so they can interact with the service.

    - -

    There are a few rules you should be aware of when implementing your AIDL interface:

    -
      -
    • Incoming calls are not guaranteed to be executed on the main thread, so you need to think -about multithreading from the start and properly build your service to be thread-safe.
    • -
    • By default, RPC calls are synchronous. If you know that the service takes more than a few -milliseconds to complete a request, you should not call it from the activity's main thread, because -it might hang the application (Android might display an "Application is Not Responding" -dialog)—you should usually call them from a separate thread in the client.
    • -
    • No exceptions that you throw are sent back to the caller.
    • -
    - - -

    3. Expose the interface to clients

    - -

    Once you've implemented the interface for your service, you need to expose it to -clients so they can bind to it. To expose the interface -for your service, extend {@link android.app.Service Service} and implement {@link -android.app.Service#onBind onBind()} to return an instance of your class that implements -the generated {@code Stub} (as discussed in the previous section). Here's an example -service that exposes the {@code IRemoteService} example interface to clients.

    - -
    -public class RemoteService extends Service {
    -    @Override
    -    public void onCreate() {
    -        super.onCreate();
    -    }
    -
    -    @Override
    -    public IBinder onBind(Intent intent) {
    -        // Return the interface
    -        return mBinder;
    -    }
    -
    -    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    -        public int getPid(){
    -            return Process.myPid();
    -        }
    -        public void basicTypes(int anInt, long aLong, boolean aBoolean,
    -            float aFloat, double aDouble, String aString) {
    -            // Does nothing
    -        }
    -    };
    -}
    -
    - -

    Now, when a client (such as an activity) calls {@link android.content.Context#bindService -bindService()} to connect to this service, the client's {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback receives the -{@code mBinder} instance returned by the service's {@link android.app.Service#onBind onBind()} -method.

    - -

    The client must also have access to the interface class, so if the client and service are in -separate applications, then the client's application must have a copy of the {@code .aidl} file -in its {@code src/} directory (which generates the {@code android.os.Binder} -interface—providing the client access to the AIDL methods).

    - -

    When the client receives the {@link android.os.IBinder} in the {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback, it must call -YourServiceInterface.Stub.asInterface(service) to cast the returned -parameter to YourServiceInterface type. For example:

    - -
    -IRemoteService mIRemoteService;
    -private ServiceConnection mConnection = new ServiceConnection() {
    -    // Called when the connection with the service is established
    -    public void onServiceConnected(ComponentName className, IBinder service) {
    -        // Following the example above for an AIDL interface,
    -        // this gets an instance of the IRemoteInterface, which we can use to call on the service
    -        mIRemoteService = IRemoteService.Stub.asInterface(service);
    -    }
    -
    -    // Called when the connection with the service disconnects unexpectedly
    -    public void onServiceDisconnected(ComponentName className) {
    -        Log.e(TAG, "Service has unexpectedly disconnected");
    -        mIRemoteService = null;
    -    }
    -};
    -
    - -

    For more sample code, see the {@code -RemoteService.java} class in ApiDemos.

    - - - - - - - - -

    Passing Objects over IPC

    - -

    If you have a class that you would like to send from one process to another through -an IPC interface, you can do that. However, you must ensure that the code for your class is -available to the other side of the IPC channel and your class must support the {@link -android.os.Parcelable} interface. Supporting the {@link android.os.Parcelable} interface is -important because it allows the Android system to decompose objects into primitives that can be -marshalled across processes.

    - -

    To create a class that supports the {@link android.os.Parcelable} protocol, you must do the -following: -

      -
    1. Make your class implement the {@link android.os.Parcelable} interface.
    2. -
    3. Implement {@link android.os.Parcelable#writeToParcel writeToParcel}, which takes the -current state of the object and writes it to a {@link android.os.Parcel}.
    4. -
    5. Add a static field called CREATOR to your class which is an object implementing -the {@link android.os.Parcelable.Creator Parcelable.Creator} interface.
    6. -
    7. Finally, create an {@code .aidl} file that declares your parcelable class (as shown for the -{@code Rect.aidl} file, below). -

      If you are using a custom build process, do not add the {@code .aidl} file to your -build. Similar to a header file in the C language, this {@code .aidl} file isn't compiled.

    8. -
    - -

    AIDL uses these methods and fields in the code it generates to marshall and unmarshall -your objects.

    - -

    For example, here is a {@code Rect.aidl} file to create a {@code Rect} class that's -parcelable:

    - -
    -package android.graphics;
    -
    -// Declare Rect so AIDL can find it and knows that it implements
    -// the parcelable protocol.
    -parcelable Rect;
    -
    - -

    And here is an example of how the {@link android.graphics.Rect} class implements the -{@link android.os.Parcelable} protocol.

    - -
    -import android.os.Parcel;
    -import android.os.Parcelable;
    -
    -public final class Rect implements Parcelable {
    -    public int left;
    -    public int top;
    -    public int right;
    -    public int bottom;
    -
    -    public static final Parcelable.Creator<Rect> CREATOR = new
    -Parcelable.Creator<Rect>() {
    -        public Rect createFromParcel(Parcel in) {
    -            return new Rect(in);
    -        }
    -
    -        public Rect[] newArray(int size) {
    -            return new Rect[size];
    -        }
    -    };
    -
    -    public Rect() {
    -    }
    -
    -    private Rect(Parcel in) {
    -        readFromParcel(in);
    -    }
    -
    -    public void writeToParcel(Parcel out) {
    -        out.writeInt(left);
    -        out.writeInt(top);
    -        out.writeInt(right);
    -        out.writeInt(bottom);
    -    }
    -
    -    public void readFromParcel(Parcel in) {
    -        left = in.readInt();
    -        top = in.readInt();
    -        right = in.readInt();
    -        bottom = in.readInt();
    -    }
    -}
    -
    - -

    The marshalling in the {@code Rect} class is pretty simple. Take a look at the other -methods on {@link android.os.Parcel} to see the other kinds of values you can write -to a Parcel.

    - -

    Warning: Don't forget the security implications of receiving -data from other processes. In this case, the {@code Rect} reads four numbers from the {@link -android.os.Parcel}, but it is up to you to ensure that these are within the acceptable range of -values for whatever the caller is trying to do. See Security and Permissions for more -information about how to keep your application secure from malware.

    - - - -

    Calling an IPC Method

    - -

    Here are the steps a calling class must take to call a remote interface defined with AIDL:

    -
      -
    1. Include the {@code .aidl} file in the project {@code src/} directory.
    2. -
    3. Declare an instance of the {@link android.os.IBinder} interface (generated based on the -AIDL).
    4. -
    5. Implement {@link android.content.ServiceConnection ServiceConnection}.
    6. -
    7. Call {@link -android.content.Context#bindService(android.content.Intent,android.content.ServiceConnection,int) - Context.bindService()}, passing in your {@link -android.content.ServiceConnection} implementation.
    8. -
    9. In your implementation of {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()}, -you will receive an {@link android.os.IBinder} instance (called service). Call -YourInterfaceName.Stub.asInterface((IBinder)service) to - cast the returned parameter to YourInterface type.
    10. -
    11. Call the methods that you defined on your interface. You should always trap - {@link android.os.DeadObjectException} exceptions, which are thrown when - the connection has broken; this will be the only exception thrown by remote - methods.
    12. -
    13. To disconnect, call {@link -android.content.Context#unbindService(android.content.ServiceConnection) - Context.unbindService()} with the instance of your interface.
    14. -
    -

    A few comments on calling an IPC service:

    -
      -
    • Objects are reference counted across processes.
    • -
    • You can send anonymous objects - as method arguments.
    • -
    - -

    For more information about binding to a service, read the Bound Services -document.

    - -

    Here is some sample code demonstrating calling an AIDL-created service, taken - from the Remote Service sample in the ApiDemos project.

    -

    {@sample development/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java - calling_a_service}

    diff --git a/docs/html/guide/developing/tools/android.jd b/docs/html/guide/developing/tools/android.jd deleted file mode 100644 index 295a720b36f3..000000000000 --- a/docs/html/guide/developing/tools/android.jd +++ /dev/null @@ -1,393 +0,0 @@ -page.title=android -parent.title=Tools -parent.link=index.html -@jd:body - -

    {@code android} is an important development tool that lets you:

    - - If you are using Eclipse, the android tool's features are integrated - into ADT, so you should not need to use this tool directly. - -

    Note: The documentation of options below is not exhaustive -and may be out of date. For the most current list of options, execute android ---help.

    - - - - -

    Syntax

    -
    android [global options] action [action options]
    - -

    Global Options

    - -
    -
    -s
    - -
    Silent mode: only errors are printed out
    - -
    -h
    - -
    Usage help
    - -
    -v
    - -
    Verbose mode: errors, warnings and informational messages are printed.
    -
    - -

    AVD actions and options

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ActionOptionDescriptionComments
    avdNoneLaunch the AVD Manager
    sdkNoneLaunch the Android SDK Manager
    create avd-n <name>The name for the AVD.Required
    -t <targetID>Target ID of the system image to use with the new AVD. To obtain a list of available - targets, use android list targetsRequired
    -c <path>|<size>[K|M]The path to the SD card image to use with this AVD or the size of a new SD card image to - create for this AVD. For example, -c path/to/sdcard or -c - 1000M.
    -fForce creation of the AVD
    -p <path>Path to the location at which to create the directory for this AVD's files.
    -s <name>|<width>-<height>The skin to use for this AVD, identified by name or dimensions. The android - tool scans for a matching skin by name or dimension in the skins/ directory of - the target referenced in the -t <targetID> argument. For example, -s - HVGA-L
    delete avd-n <name>The name of the AVD to deleteRequired
    move avd-n <name>The name of the AVD to moveRequired
    -p <path>Path to the location at which to create the directory for this AVD's files.
    -r <new-name>New name of the AVD if you want to rename it
    update avd-n <name>The name of the AVD to moveRequired
    - -

    Project actions and options

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ActionOptionDescriptionComments
    create project-n <name>The name for the projectRequired
    -t <targetID>Target ID of the system image to use with the new AVD. To obtain a list of available - targets, use android list targetsRequired
    -k <path>|<size>[K|M]Package namespaceRequired
    -aName for the default Activity classRequired
    -p <path>Location of your project directoryRequired
    update project-n <name>The name of the project to update
    -p <path>Location path of the projectRequired
    -l <library path>Location path of an Android Library to add, relative to the main project
    -s <subprojects>Update any projects in subfolders such as test projects
    -t <targetID>Target id to set for the project
    create-test-project-n <name>The name of the project
    -p <path>Location path of the projectRequired
    -m <main>The name of the projectRequired
    update-test-project-p <path>Location path of the project to test, relative to the new projectRequired
    -m <main>The main class of the project to testRequired
    create-lib-project-k <packageName>(Required) Package name of the library projectRequired
    -p <path>Location path of the projectRequired
    -t <targetID>Target ID of the library projectRequired
    -n <name>The name of the projectRequired
    update-lib-project-p <path>Location path of the projectRequired
    -l <libraryPath>Location path of an Android Library to add, relative to the main project
    -t <name>Target ID of the library project
    - -

    Update actions

    -
    -
    update adb
    -
    Updates adb to support the USB devices declared in the SDK add-ons.
    - -
    update sdk
    -
    Updates the SDK by suggesting new platforms to install if available.
    diff --git a/docs/html/guide/developing/tools/avd.html b/docs/html/guide/developing/tools/avd.html deleted file mode 100644 index c8455db1bcb3..000000000000 --- a/docs/html/guide/developing/tools/avd.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/bmgr.jd b/docs/html/guide/developing/tools/bmgr.jd deleted file mode 100644 index d63dcf291b4f..000000000000 --- a/docs/html/guide/developing/tools/bmgr.jd +++ /dev/null @@ -1,193 +0,0 @@ -page.title=bmgr -parent.title=Tools -parent.link=index.html -@jd:body - - - -
    -
    -

    bmgr quickview

    -

    bmgr lets you control the backup/restore system on an Android device. - -

    In this document

    -
      -
    1. Forcing a Backup Operation
    2. -
    3. Forcing a Restore Operation
    4. -
    5. Other Commands
    6. -
    - -

    See also

    -
      -
    1. Data Backup
    2. -
    - -
    -
    - - - -

    bmgr is a shell tool you can use to interact with the Backup Manager -on Android devices supporting API Level 8 or greater. It provides commands to induce backup -and restore operations so that you don't need to repeatedly wipe data or take similar -intrusive steps in order to test your application's backup agent. These commands are -accessed via the adb shell. - -

    For information about adding support for backup in your application, read Data Backup, which includes a guide to testing -your application using {@code bmgr}.

    - - -

    Forcing a Backup Operation

    - -

    Normally, your application must notify the Backup Manager when its data has changed, via {@link -android.app.backup.BackupManager#dataChanged()}. The Backup Manager will then invoke your -backup agent's {@link -android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor) -onBackup()} implementation at some time in the future. However, instead of calling {@link -android.app.backup.BackupManager#dataChanged()}, you can invoke a backup request from the command -line by running the bmgr backup command: - -

    adb shell bmgr backup <package>
    - -

    <package> is the formal package name of the application you wish to -schedule for -backup. When you execute this backup command, your application's backup agent will be invoked to -perform a backup operation at some time in the future (via your {@link -android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor) -onBackup()} method), though there is no guarantee when it will occur. However, you can force all -pending backup operations to run immediately by using the bmgr run command: - -

    adb shell bmgr run
    - -

    This causes a backup pass to execute immediately, invoking the backup agents of all applications -that had previously called {@link android.app.backup.BackupManager#dataChanged()} since the -last backup operation, plus any applications which had been manually scheduled for -backup via bmgr backup. - - - -

    Forcing a Restore Operation

    - -

    Unlike backup operations, which are batched together and run on an occasional basis, restore -operations execute immediately. The Backup Manager currently provides two kinds of restore -operations. The first kind restores an entire device with the data that has been backed up. This -is typically performed only when a device is first provisioned (to replicate settings and other -saved state from the user's previous device) and is an operation that only the system can -perform. The second kind of restore operation restores -a single application to its "active" data set; that is, the application will abandon its current -data and revert to the last-known-good data that is held in the current backup image. You can -invoke this second restore operation with the {@link -android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method. The -Backup Manager will then invoke your backup agent's {@link -android.app.backup.BackupAgent#onRestore(BackupDataInput,int,ParcelFileDescriptor) -onRestore()} implementation. - -

    While testing your application, you can immediately invoke the restore operation (bypassing the -{@link android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method) -for your application by using the bmgr restore command: - -

    adb shell bmgr restore <package>
    - -

    <package> is the formal Java-style package name of the application -participating in the backup/restore mechanism, which you would like to restore. The Backup -Manager will immediately instantiate the application's backup agent and invoke it for restore. This -will happen even if your application is not currently running. - - - - - -

    Other Commands

    - -

    Wiping data

    - -

    The data for a single application can be erased from the active data set on demand. This is -very useful while you're developing a backup agent, in case bugs lead you to write corrupt data -or saved state information. You can wipe an application's data with the bmgr wipe -command: - -

    adb shell bmgr wipe <package>
    - -

    <package> is the formal package name of the application whose data -you wish to -erase. The next backup operation that the application's agent processes will look as -though the application had never backed anything up before. - - -

    Enabling and disabling backup

    - -

    You can see whether the Backup Manager is operational at all with the bmgr -enabled command: - -

    adb shell bmgr enabled
    - -

    This might be useful if your application's backup agent is never being invoked for backup, to -verify whether the operating system thinks it should be performing such operations at all.

    - -

    You can also directly disable or enable the Backup Manager with this command: - -

    adb shell bmgr enable <boolean>
    - -

    <boolean> is either true or false. -This is equivalent to disabling or enabling backup in the device's main Settings UI.

    - -

    Warning! When backup is disabled, the current backup transport -will explicitly wipe -the entire active data set from its backend storage. This is so that when a user says -they do not want their data backed up, the Backup Manager respects that wish. No further -data will be saved from the device, and no restore operations will be possible, unless the Backup -Manager is re-enabled (either through Settings or through the above bmgr command). - - - - - diff --git a/docs/html/guide/developing/tools/ddms.html b/docs/html/guide/developing/tools/ddms.html deleted file mode 100644 index 052ccc958593..000000000000 --- a/docs/html/guide/developing/tools/ddms.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/dmtracedump.jd b/docs/html/guide/developing/tools/dmtracedump.jd deleted file mode 100644 index cb9ad262a671..000000000000 --- a/docs/html/guide/developing/tools/dmtracedump.jd +++ /dev/null @@ -1,66 +0,0 @@ -page.title=dmtracedump -parent.title=Tools -parent.link=index.html -@jd:body - - -

    dmtracedump is a tool that gives you an alternate way of generating - graphical call-stack diagrams from trace log files (instead of using Traceview).

    - -

    This document is a reference to the available command line options. For more information on generating trace - logs, see Profiling with - Traceview and dmtracedump.

    - -

    The usage for dmtracedump is:

    -
    -dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
    -
    - -

    The tool then loads trace log data from <trace-base-name>.data and - <trace-base-name>.key. The table below lists the options for dmtracedump.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    OptionDescription
    -d <trace-base-name>Diff with this trace name
    -g <outfile>Generate output to <outfile>
    -hTurn on HTML output
    -oDump the trace file instead of profiling
    -d <trace-base-name>URL base to the location of the sortable javascript file
    -t <percent>Minimum threshold for including child nodes in the graph (child's inclusive time as a - percentage of parent inclusive time). If this option is not used, the default threshold is - 20%.
    \ No newline at end of file diff --git a/docs/html/guide/developing/tools/draw9patch.jd b/docs/html/guide/developing/tools/draw9patch.jd deleted file mode 100644 index 7cf0e4b1d861..000000000000 --- a/docs/html/guide/developing/tools/draw9patch.jd +++ /dev/null @@ -1,59 +0,0 @@ -page.title=Draw 9-patch -parent.title=Tools -parent.link=index.html -@jd:body - -

    The Draw 9-patch tool allows you to easily create a - {@link android.graphics.NinePatch} graphic using a WYSIWYG editor.

    -

    For an introduction to Nine-patch graphics and how they work, please read -the section about Nine-patch in the -2D Graphics -document.

    - - - -

    Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool. -You'll need the PNG image with which you'd like to create a NinePatch.

    - -
      -
    1. From a terminal, launch the draw9patch application from your SDK - /tools directory. -
    2. -
    3. Drag your PNG image into the Draw 9-patch window - (or File > Open 9-patch... to locate the file). - Your workspace will now open. -

      The left pane is your drawing area, in which you can edit the lines for the - stretchable patches and content area. The right - pane is the preview area, where you can preview your graphic when stretched.

      -
    4. -
    5. Click within the 1-pixel perimeter to draw the lines that define the stretchable - patches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase - previously drawn lines. -
    6. -
    7. When done, select File > Save 9-patch... -

      Your image will be saved with the .9.png file name.

      -
    8. -
    -

    Note: A normal PNG file (*.png) will be - loaded with an empty one-pixel border added around the image, in which you can draw - the stretchable patches and content area. - A previously saved 9-patch file (*.9.png) will be loaded as-is, - with no drawing area added, because it already exists.

    - - - -

    Optional controls include:

    -
      -
    • Zoom: Adjust the zoom level of the graphic in the drawing area.
    • -
    • Patch scale: Adjust the scale of the images in the preview area.
    • -
    • Show lock: Visualize the non-drawable area of the graphic on mouse-over.
    • -
    • Show patches: Preview the stretchable patches in the drawing area (pink is a - stretchable patch).
    • -
    • Show content: Highlight the content area in the preview images - (purple is the area in which content is allowed).
    • -
    • Show bad patches: Adds a red border around patch areas that may - produce artifacts in the graphic when stretched. Visual coherence of your stretched - image will be maintained if you eliminate all bad patches.
    • -
        diff --git a/docs/html/guide/developing/tools/emulator.jd b/docs/html/guide/developing/tools/emulator.jd deleted file mode 100644 index 21d4263a9e12..000000000000 --- a/docs/html/guide/developing/tools/emulator.jd +++ /dev/null @@ -1,581 +0,0 @@ -page.title=Android Emulator -parent.title=Tools -parent.link=index.html -@jd:body - -
        - -
        - - -

        The Android SDK includes a mobile device emulator — a virtual mobile device -that runs on your computer. The emulator lets you develop and test -Android applications without using a physical device.

        - -

        This document is a reference to the available command line options and the keyboard mapping to -device keys. -For a complete guide to using the Android Emulator, see -Using the Android Emulator. - - -

        Keyboard Commands

        - -

        Table 1 summarizes the mappings between the emulator keys and the keys of your keyboard.

        - -

        Table 1. Emulator keyboard mapping

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        Emulated Device Key Keyboard Key
        HomeHOME
        Menu (left softkey)F2 or Page-up button
        Star (right softkey)Shift-F2 or Page Down
        BackESC
        Call/dial button F3
        Hangup/end call buttonF4
        SearchF5
        Power buttonF7
        Audio volume up buttonKEYPAD_PLUS, Ctrl-F5
        Audio volume down buttonKEYPAD_MINUS, Ctrl-F6
        Camera buttonCtrl-KEYPAD_5, Ctrl-F3
        Switch to previous layout orientation (for example, portrait, landscape)KEYPAD_7, Ctrl-F11
        Switch to next layout orientation (for example, portrait, landscape)KEYPAD_9, Ctrl-F12
        Toggle cell networking on/offF8
        Toggle code profilingF9 (only with -trace startup option)
        Toggle fullscreen modeAlt-Enter
        Toggle trackball modeF6
        Enter trackball mode temporarily (while key is pressed)Delete
        DPad left/up/right/downKEYPAD_4/8/6/2
        DPad center clickKEYPAD_5
        Onion alpha increase/decreaseKEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)
        - - -

        Command Line Parameters

        - -

        The emulator supports a variety of options that you can specify -when launching the emulator, to control its appearance or behavior. -Here's the command-line syntax of the options available to the {@code emulator} program:

        - -
        emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]
        - -

        Table 2. Emulator command line parameters

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - s - - - - - - - - - - - - - - - -
        CategoryOptionDescriptionComments
        AVD-avd <avd_name> or
        - @<avd_name>
        Required. Specifies the AVD to load for this emulator - instance.You must create an AVD configuration before launching the emulator. For - information, see Managing - AVDs with AVD Manager.
        Disk Images-cache <filepath>Use <filepath> as the working cache partition image. An absolute or relative path to the current working directory. - If no cache file is specified, the emulator's default behavior is to use a temporary file instead. -

        For more information on disk images, use -help-disk-images.

        -
        -data <filepath>Use {@code <filepath>} as the working user-data disk image. Optionally, you can specify a path relative to the current working directory. - If -data is not used, the emulator looks for a file named {@code userdata-qemu.img} - in the storage area of the AVD being used (see -avd). -
        -initdata <filepath>When resetting the user-data image (through -wipe-data), copy the contents - of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img.Optionally, you can specify a path relative to the current working directory. See also -wipe-data. -

        For more information on disk images, use -help-disk-images.

        -nocacheStart the emulator without a cache partition.See also -cache <file>.
        -ramdisk <filepath>Use <filepath> as the ramdisk image.Default value is <system>/ramdisk.img. -

        Optionally, you can specify a path relative to the current working directory. - For more information on disk images, use -help-disk-images.

        -
        -sdcard <filepath>Use <file> as the SD card image.Default value is <system>/sdcard.img. -

        Optionally, you can specify a path relative to the current working directory. For more information on disk images, use -help-disk-images.

        -
        -wipe-dataReset the current user-data disk image (that is, the file specified by -datadir and - -data, or the default file). The emulator deletes all data from the user data image file, - then copies the contents of the file at -inidata data to the image file before starting. - See also -initdata. -

        For more information on disk images, use -help-disk-images.

        -
        Debug-debug <tags>Enable/disable debug messages for the specified debug tags.<tags> is a space/comma/column-separated list of debug component names. - Use -help-debug-tags to print a list of debug component names that you can use.
        -debug-<tag>Enable/disable debug messages for the specified debug tag.Use -help-debug-tags to print a list of debug component names that you can use in <tag>.
        -debug-no-<tag>Disable debug messages for the specified debug tag.
        -logcat <logtags>Enable logcat output with given tags.If the environment variable ANDROID_LOG_TAGS is defined and not - empty, its value will be used to enable logcat output by default.
        -shellCreate a root shell console on the current terminal.You can use this command even if the adb daemon in the emulated system is broken. - Pressing Ctrl-c from the shell stops the emulator instead of the shell.
        -shell-serial <device>Enable the root shell (as in -shell and specify the QEMU character - device to use for communication with the shell.<device> must be a QEMU device type. See the documentation for '-serial dev' at - http://wiki.qemu.org/download/qemu-doc.html - for a list of device types. - -

        Here are some examples:

        -
          -
        • -shell-serial stdio is identical to -shell
        • -
        • -shell-serial tcp::4444,server,nowait lets you communicate with the shell over TCP port 4444
        • -
        • -shell-serial fdpair:3:6 lets a parent process communicate with the shell using fds 3 (in) and 6 (out)
        • -
        • -shell-serial fdpair:0:1 uses the normal stdin and stdout fds, except that QEMU won't tty-cook the data.
        • -
        -
        -show-kernel <name>Display kernel messages. 
        -trace <name>Enable code profiling (press F9 to start), written to a specified file. 
        -verboseEnable verbose output.Equivalent to -debug-init. -

        You can define the default verbose output options used by emulator instances in the Android environment variable -ANDROID_VERBOSE. Define the options you want to use in a comma-delimited list, specifying only the stem of each option: --debug-<tags>.

        -

        Here's an example showing ANDROID_VERBOSE defined with the -debug-init and -debug-modem options: -

        ANDROID_VERBOSE=init,modem

        -

        For more information about debug tags, use <-help-debug-tags>.

        -
        Media-audio <backend>Use the specified audio backend. 
        -audio-in <backend>Use the specified audio-input backend. 
        -audio-out <backend>Use the specified audio-output backend. 
        -noaudioDisable audio support in the current emulator instance. 
        -radio <device>Redirect radio modem interface to a host character device. 
        -useaudioEnable audio support in the current emulator instance.Enabled by default.
        Network-dns-server <servers>Use the specified DNS server(s). The value of <servers> must be a comma-separated list of up to 4 DNS server names or - IP addresses.
        -http-proxy <proxy>Make all TCP connections through a specified HTTP/HTTPS proxyThe value of <proxy> can be one of the following:
        - http://<server>:<port>
        - http://<username>:<password>@<server>:<port> -

        The http:// prefix can be omitted. If the -http-proxy <proxy> command is not supplied, - the emulator looks up the http_proxy environment variable and automatically uses any value matching - the <proxy> format described above.

        -netdelay <delay>Set network latency emulation to <delay>.Default value is none. See the table in - Network Delay Emulation - for supported <delay> values.
        -netfastShortcut for -netspeed full -netdelay none 
        -netspeed <speed>Set network speed emulation to <speed>.Default value is full. See the table in - Network Speed Emulation for - supported <speed> values.
        -port <port>Set the console port number for this emulator instance to <port>.The console port number must be an even integer between 5554 and 5584, inclusive. <port>+1 - must also be free and will be reserved for ADB.
        -report-console <socket>Report the assigned console port for this emulator instance to a remote third party - before starting the emulation. <socket> must use one of these formats: - -

        tcp:<port>[,server][,max=<seconds>]
        -unix:<port>[,server][,max=<seconds>]

        - -

        Use -help-report-console

        to view more information about this topic.
        System-cpu-delay <delay>Slow down emulated CPU speed by <delay> Supported values for <delay> are integers between 0 and 1000. - -

        Note that the <delay> does not correlate to clock speed or other absolute metrics -— it simply represents an abstract, relative delay factor applied non-deterministically -in the emulator. Effective performance does not always -scale in direct relationship with <delay> values.

        -
        -gps <device>Redirect NMEA GPS to character device.Use this command to emulate an NMEA-compatible GPS unit connected to - an external character device or socket. The format of <device> must be QEMU-specific - serial device specification. See the documentation for 'serial -dev' at - http://wiki.qemu.org/download/qemu-doc.html. -
        -nojniDisable JNI checks in the Dalvik runtime. 
        -qemuPass arguments to the qemu emulator software.

        Important: When using this option, make sure it is the - last option specified, since all options after it are interpretted as qemu-specific - options.

        -qemu -enable-kvmEnable KVM acceleration of the emulator virtual machine.This option is only effective when your system is set up to use - KVM-based VM acceleration. - You can optionally specify a memory size ({@code -m <size>}) for the VM, which should match - your emulator's memory size:

        - {@code -qemu -m 512 -enable-kvm}
        - {@code -qemu -m 1024 -enable-kvm} -
        -qemu -hDisplay qemu help.
        -gpu onTurn on graphics acceleration for the emulator.This option is only available for emulators using a system image with API Level 15, revision 3 - and higher. For more information, see - Using the Android - Emulator.
        -radio <device>Redirect radio mode to the specified character device.The format of <device> must be QEMU-specific - serial device specification. See the documentation for 'serial -dev' at -http://wiki.qemu.org/download/qemu-doc.html. -
        -timezone <timezone>Set the timezone for the emulated device to <timezone>, instead of the host's timezone.<timezone> must be specified in zoneinfo format. For example: -

        "America/Los_Angeles"
        -"Europe/Paris"

        -
        -versionDisplay the emulator's version number. 
        UI-dpi-device <dpi>Scale the resolution of the emulator to match the screen size - of a physical device.The default value is 165. See also -scale.
        -no-boot-animDisable the boot animation during emulator startup.Disabling the boot animation can speed the startup time for the emulator.
        -no-windowDisable the emulator's graphical window display. 
        -scale <scale>Scale the emulator window. <scale> is a number between 0.1 and 3 that represents the desired scaling factor. You can - also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" - tells the emulator to select the best window size.
        -raw-keysDisable Unicode keyboard reverse-mapping. 
        -noskinDon't use any emulator skin. 
        -keyset <file>Use the specified keyset file instead of the default.The keyset file defines the list of key bindings between the emulator and the host keyboard. - For more information, use -help-keyset to print information about this topic. -
        -onion <image>Use overlay image over screen.No support for JPEG. Only PNG is supported.
        -onion-alpha <percent>Specify onion skin translucency value (as percent). - Default is 50.
        -onion-rotation <position>Specify onion skin rotation. - <position> must be one of the values 0, 1, 2, 3.
        -skin <skinID>This emulator option is deprecated. Please set skin options using AVDs, rather than by using this emulator -option. Using this option may yield unexpected and in some cases misleading -results, since the density with which to render the skin may not be defined. -AVDs let you associate each skin with a default density and override the default -as needed. For more information, see Managing Virtual Devices -with AVD Manager. -
        -skindir <dir>This emulator option is deprecated. See comments for -skin, above.
        Help-helpPrint a list of all emulator options. 
        -help-allPrint help for all startup options. 
        -help-<option>Print help for a specific startup option. 
        -help-debug-tagsPrint a list of all tags for -debug <tags>. 
        -help-disk-imagesPrint help for using emulator disk images. 
        -help-environmentPrint help for emulator environment variables. 
        -help-keysPrint the current mapping of keys. 
        -help-keyset-filePrint help for defining a custom key mappings file. 
        -help-virtual-devicePrint help for Android Virtual Device usage. 
        diff --git a/docs/html/guide/developing/tools/etc1tool.jd b/docs/html/guide/developing/tools/etc1tool.jd deleted file mode 100644 index a7f76f5cadb6..000000000000 --- a/docs/html/guide/developing/tools/etc1tool.jd +++ /dev/null @@ -1,68 +0,0 @@ -page.title=etc1tool -parent.title=Tools -parent.link=index.html -@jd:body - - -

        etc1tool is a command line utility that lets you encode PNG - images to the ETC1 compression standard and decode ETC1 compressed images back to PNG.

        - -

        The usage for etc1tool is:

        -
        etc1tool infile [--help | --encode | --encodeNoHeader | --decode] [--showDifference
        -diff-file] [-o outfile]
        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        OptionDescription
        infileThe input file to compress
        --helpPrint usage information
        --encodeCreate an ETC1 file from a PNG file. - This is the default mode for the tool if nothing is specified.
        --encodeNoHeaderCreate a raw ETC1 data file (without a header) from a PNG file.
        --decodeCreate a PNG file from an ETC1 file
        --showDifference diff-fileWrite the difference between the original and encoded image to - diff-file (only valid when encoding).
        -o outfileSpecify the name of the output file. - If outfile is not specified, the output file is constructed - from the input filename with the appropriate suffix (.pkm or .png). -
        \ No newline at end of file diff --git a/docs/html/guide/developing/tools/hierarchy-viewer.jd b/docs/html/guide/developing/tools/hierarchy-viewer.jd deleted file mode 100644 index 3d3191b76d7a..000000000000 --- a/docs/html/guide/developing/tools/hierarchy-viewer.jd +++ /dev/null @@ -1,18 +0,0 @@ -page.title=Hierarchy Viewer -parent.title=Tools -parent.link=index.html -@jd:body - -

        Hierarchy Viewer allows you to debug and optimize your user -interface. It provides a visual representation of the layout's View hierarchy -(the Layout View) and a magnified inspector of the display (the Pixel Perfect View). -

        - -

        To start Hierarchy Viewer, enter the following command from the SDK tools/ directory:

        -
        hierarchyviewer
        - - -

        For more information on how to use Hierarchy Viewer, see -Debugging and Profiling UIs -

        - diff --git a/docs/html/guide/developing/tools/hprof-conv.jd b/docs/html/guide/developing/tools/hprof-conv.jd deleted file mode 100644 index f96def205fb1..000000000000 --- a/docs/html/guide/developing/tools/hprof-conv.jd +++ /dev/null @@ -1,16 +0,0 @@ -page.title=HPROF Converter -parent.title=Tools -parent.link=index.html -@jd:body - -

        -The hprof-conv tool converts the HPROF file that is -generated by the Android SDK tools to a standard format so you -can view the file in a profiling tool of your choice.

        - -
         hprof-conv <infile> <outfile>
        - -

        -You can use "-" for <infile> or <outfile> -to specify stdin or stdout. -

        diff --git a/docs/html/guide/developing/tools/index.jd b/docs/html/guide/developing/tools/index.jd deleted file mode 100644 index 5e9f68624146..000000000000 --- a/docs/html/guide/developing/tools/index.jd +++ /dev/null @@ -1,85 +0,0 @@ -page.title=Tools -@jd:body - - - -

        The Android SDK includes a variety of tools that help you develop mobile -applications for the Android platform. The tools are classified into two groups: SDK tools -and platform tools. SDK tools are platform independent and are required no matter which -Android platform you are developing on. Platform tools are customized to support the features of the -latest Android platform.

        - -

        SDK Tools

        -

        The SDK tools are installed with the SDK starter package and are periodically updated. -The SDK tools are required if you are developing Android applications. The most important SDK tools -include the Android SDK Manager (android sdk), the AVD Manager (android -avd) the emulator (emulator), and the Dalvik Debug Monitor Server -(ddms). A short summary of some frequently-used SDK tools is provided below.

        - -
        -
        android
        -
        Lets you manage AVDs, projects, and the installed components of the SDK.
        -
        Dalvik Debug Monitor -Server (ddms)
        -
        Lets you debug Android applications.
        -
        dmtracedump
        -
        Generates graphical call-stack diagrams from trace log files. The tool uses the -Graphviz Dot utility to create the graphical output, so you need to install Graphviz before -running dmtracedump. For more information on using dmtracedump, see Profiling -with Traceview and dmtracedump
        -
        Draw 9-patch
        -
        Allows you to easily create a {@link android.graphics.NinePatch} graphic using a -WYSIWYG editor. It also previews stretched versions of the image, and highlights the area in which -content is allowed.
        -
        Android Emulator (emulator)
        -
        A QEMU-based device-emulation tool that you can use to design, debug, and test -your applications in an actual Android run-time environment.
        -
        Hierarchy Viewer (hierarchyviewer)
        -
        Lets you debug and optimize an Android application's user interface.
        -
        hprof-conv
        -
        Converts the HPROF file that is generated by the Android SDK tools to a standard format so -you can view the file in a profiling tool of your choice.
        -
        layoutopt
        -
        Lets you quickly analyze your application's layouts in order to optimize them for -efficiency.
        -
        mksdcard
        -
        Helps you create a disk image that you can use with the emulator, to simulate the presence -of an external storage card (such as an SD card).
        -
        Monkey
        -
        Runs on your emulator or device and generates pseudo-random streams of user events such -as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey -to stress-test applications that you are developing, in a random yet repeatable manner.
        -
        monkeyrunner
        -
        Provides an API for writing programs that control an Android device or emulator from -outside of Android code.
        -
        ProGuard
        -
        Shrinks, optimizes, and obfuscates your code by removing unused code and renaming -classes, fields, and methods with semantically obscure names.
        -
        sqlite3
        -
        Lets you access the SQLite data files created and used by Android applications.
        -
        traceview
        -
        Provides a graphical viewer for execution logs saved by your application.
        -
        zipalign
        -
        Optimizes .apk files by ensuring that all uncompressed data starts with a -particular alignment relative to the start of the file. This should always be used to align .apk -files after they have been signed.
        -
        - -

        Platform Tools

        - -

        The platform tools are typically updated every time you install a new SDK platform. Each update -of the platform tools is backward compatible with older platforms. Usually, you directly use only -one of the platform tools—the Android Debug Bridge (adb). -Android Debug Bridge is a versatile tool that lets you manage the state of an emulator instance or -Android-powered device. You can also use it to install an Android application (.apk) file on a -device.

        - -

        The other platform tools, such as aidl, -aapt, dexdump, and dx, are typically called by the Android -build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. -As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.

        - -

        Note: The Android SDK provides additional shell tools that can -be accessed through adb, such as bmgr and -logcat.

        \ No newline at end of file diff --git a/docs/html/guide/developing/tools/layoutopt.jd b/docs/html/guide/developing/tools/layoutopt.jd deleted file mode 100644 index cb0b50595278..000000000000 --- a/docs/html/guide/developing/tools/layoutopt.jd +++ /dev/null @@ -1,24 +0,0 @@ -page.title=layoutopt -parent.title=Tools -parent.link=index.html -@jd:body - -

        layoutopt is a command-line tool that helps you optimize the -layouts and layout hierarchies of your applications.

        - -

        This document is a reference to the available command line options. For more information and sample -output of the tool, see Optimizing layouts with -layoutopt.

        - -

        Usage

        - -

        To run layoutopt against a given list of layout resources:

        - -
        layoutopt <file_or_directory> ...
        - -

        For example:

        - -
        $ layoutopt res/layout-land
        -
        $ layoutopt res/layout/main.xml res/layout-land/main.xml
        - diff --git a/docs/html/guide/developing/tools/logcat.jd b/docs/html/guide/developing/tools/logcat.jd deleted file mode 100644 index 546e3eacd2ae..000000000000 --- a/docs/html/guide/developing/tools/logcat.jd +++ /dev/null @@ -1,106 +0,0 @@ -page.title=logcat -parent.title=Tools -parent.link=index.html -@jd:body - -

        The Android logging system provides a mechanism for collecting and viewing system debug - output. Logs from various applications and portions of the system are collected in a series of - circular buffers, which then can be viewed and filtered by the logcat command. You can use - logcat from an ADB shell to view the log messages.

        - -

        This document is a reference to the available command line options. For more information on logcat, see - Reading and Writing Logs. -For more - information on accessing logcat from DDMS, instead of the command line, see the documentation for the - Dalvik Debug Monitor Server. -

        - -

        Syntax

        -
        -[adb] logcat [<option>] ... [<filter-spec>] ...
        -
        - -

        You can run logcat as an adb command or directly in a shell prompt - of your emulator or connected device. To view log output using adb, navigate to your SDK - platform-tools/ directory and execute:

        -
        -$ adb logcat
        -
        - -

        You can create a shell connection to a device and execute:

        -
        -$ adb shell
        -# logcat
        -
        - -

        Options

        -

        The following table describes the command line options of logcat.

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        OptionDescription
        -b <buffer>Loads an alternate log buffer for viewing, such as event or - radio. The main buffer is used by default. See Viewing Alternative Log Buffers.
        -cClears (flushes) the entire log and exits.
        -dDumps the log to the screen and exits.
        -f <filename>Writes log message output to <filename>. The default is - stdout.
        -gPrints the size of the specified log buffer and exits.
        -n <count>Sets the maximum number of rotated logs to <count>. The default value - is 4. Requires the -r option.
        -r <kbytes>Rotates the log file every <kbytes> of output. The default value is - 16. Requires the -f option.
        -sSets the default filter spec to silent.
        -v <format>Sets the output format for log messages. The default is brief format. For a - list of supported formats, see Controlling Log Output - Format.
        diff --git a/docs/html/guide/developing/tools/mksdcard.jd b/docs/html/guide/developing/tools/mksdcard.jd deleted file mode 100644 index 0a8045487829..000000000000 --- a/docs/html/guide/developing/tools/mksdcard.jd +++ /dev/null @@ -1,55 +0,0 @@ -page.title=mksdcard -parent.title=Tools -parent.link=index.html -@jd:body - -

        The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the - emulator, to simulate the presence of an SD card in the device. Because you can specify an SD - card while creating an AVD in the AVD Manager, you usually use that feature to create an SD card. - This tool creates an SD card that is not bundled with an AVD, so it is useful for situations - where you need to share a virtual SD card between multiple emulators.

        - -

        Usage

        -
        -mksdcard -l <label> <size> <file>
        -
        - -

        Options

        -

        The following table describes the command-line options of mksdcard

        - - - - - - - - - - - - - - - - - - - - - - - - -
        OptionDescription
        -lA volume label for the disk image to create.
        sizeAn integer that specifies the size (in bytes) of disk image to create. You can also - specify size in kilobytes or megabytes, by appending a "K" or "M" to <size>. For - example, 1048576K, 1024M.
        fileThe path/filename of the disk image to create.
        - -

        Once you have created the disk image file, you can load it in the emulator at startup using - the emulator's -sdcard option. For more information, see Android Emulator.

        - -

        The usage for the -sdcard option is as follows:

        -
        emulator -sdcard <file>
        - -

        Example

        -
        mksdcard -l mySdCard 1024M mySdCardFile.img
        \ No newline at end of file diff --git a/docs/html/guide/developing/tools/monkey.jd b/docs/html/guide/developing/tools/monkey.jd deleted file mode 100644 index a7e539c15655..000000000000 --- a/docs/html/guide/developing/tools/monkey.jd +++ /dev/null @@ -1,242 +0,0 @@ -page.title=UI/Application Exerciser Monkey -parent.title=Tools -parent.link=index.html -@jd:body - -

        The Monkey is a program that runs on your -emulator or device and generates pseudo-random -streams of user events such as clicks, touches, or gestures, as well as a number of system-level -events. You can use the Monkey to stress-test applications that you are developing, in a random -yet repeatable manner.

        - - -

        Overview

        - -

        The Monkey is a command-line tool that that you can run on any emulator -instance or on a device. It sends a pseudo-random stream of -user events into the system, which acts as a stress test on the application software you are -developing.

        - -

        The Monkey includes a number of options, but they break down into four primary -categories:

        - -
          -
        • Basic configuration options, such as setting the number of events to attempt.
        • -
        • Operational constraints, such as restricting the test to a single package.
        • -
        • Event types and frequencies.
        • -
        • Debugging options.
        • -
        - -

        When the Monkey runs, it generates events and sends them to the system. It also watches -the system under test and looks for three conditions, which it treats specially:

        - -
          -
        • If you have constrained the Monkey to run in one or more specific packages, it - watches for attempts to navigate to any other packages, and blocks them.
        • -
        • If your application crashes or receives any sort of unhandled exception, the Monkey - will stop and report the error.
        • -
        • If your application generates an application not responding error, the Monkey - will stop and report the error.
        • -
        - -

        Depending on the verbosity level you have selected, you will also see reports on the progress -of the Monkey and the events being generated.

        - - -

        Basic Use of the Monkey

        - -

        You can launch the Monkey using a command line on your development machine or from a script. -Because the Monkey runs in the emulator/device environment, you must launch it from a shell in -that environment. You can do this by prefacing adb shell to each command, -or by entering the shell and entering Monkey commands directly.

        -

        The basic syntax is:

        - -
        $ adb shell monkey [options] <event-count>
        - -

        With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send -events to any (and all) packages installed on your target. Here is a more typical command line, -which will launch your application and send 500 pseudo-random events to it:

        - -
        $ adb shell monkey -p your.package.name -v 500
        - - -

        Command Options Reference

        - -

        The table below lists all options you can include on the Monkey command line.

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        CategoryOptionDescription
        General--helpPrints a simple usage guide.
        -vEach -v on the command line will increment the verbosity level. -Level 0 (the default) provides little information beyond startup notification, test completion, and -final results. -Level 1 provides more details about the test as it runs, such as individual events being sent to -your activities. -Level 2 provides more detailed setup information such as activities selected or not selected for -testing.
        Events-s <seed>Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed -value, it will generate the same sequence of events.
        --throttle <milliseconds>Inserts a fixed delay between events. You can use this option to slow down the Monkey. -If not specified, there is no delay and the events are generated as rapidly as possible.
        --pct-touch <percent>Adjust percentage of touch events. -(Touch events are a down-up event in a single place on the screen.)
        --pct-motion <percent>Adjust percentage of motion events. -(Motion events consist of a down event somewhere on the screen, a series of pseudo-random -movements, and an up event.)
        --pct-trackball <percent>Adjust percentage of trackball events. -(Trackball events consist of one or more random movements, sometimes followed by a click.)
        --pct-nav <percent>Adjust percentage of "basic" navigation events. -(Navigation events consist of up/down/left/right, as input from a directional input device.)
        --pct-majornav <percent>Adjust percentage of "major" navigation events. -(These are navigation events that will typically cause actions within your UI, such as -the center button in a 5-way pad, the back key, or the menu key.)
        --pct-syskeys <percent>Adjust percentage of "system" key events. -(These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, -End Call, or Volume controls.)
        --pct-appswitch <percent>Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing -coverage of all activities within your package.
        --pct-anyevent <percent>Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used -buttons on the device, and so forth.
        Constraints-p <allowed-package-name>If you specify one or more packages this way, the Monkey will only allow the system -to visit activities within those packages. If your application requires access to activities in -other packages (e.g. to select a contact) you'll need to specify those packages as well. -If you don't specify any packages, the Monkey will allow the system to launch activities -in all packages. To specify multiple packages, use the -p option multiple times — one -p -option per package.
        -c <main-category>If you specify one or more categories this way, the Monkey will only allow the -system to visit activities that are listed with one of the specified categories. -If you don't specify any categories, the Monkey will select activities listed with the category -Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c -option multiple times — one -c option per category.
        Debugging--dbg-no-eventsWhen specified, the Monkey will perform the initial launch into a test activity, but -will not generate any further events. -For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey -running for 30 seconds or more. This provides an environment in which you can monitor package -transitions invoked by your application.
        --hprofIf set, this option will generate profiling reports immediately before and after -the Monkey event sequence. -This will generate large (~5Mb) files in data/misc, so use with care. See -Traceview for more information -on trace files.
        --ignore-crashesNormally, the Monkey will stop when the application crashes or experiences any type of -unhandled exception. If you specify this option, the Monkey will continue to send events to -the system, until the count is completed.
        --ignore-timeoutsNormally, the Monkey will stop when the application experiences any type of timeout error such -as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to -send events to the system, until the count is completed.
        --ignore-security-exceptionsNormally, the Monkey will stop when the application experiences any type of permissions error, -for example if it attempts to launch an activity that requires certain permissions. If you specify -this option, the Monkey will continue to send events to the system, until the count is -completed.
        --kill-process-after-errorNormally, when the Monkey stops due to an error, the application that failed will be left -running. When this option is set, it will signal the system to stop the process in which the error -occurred. -Note, under a normal (successful) completion, the launched process(es) are not stopped, and -the device is simply left in the last state after the final event.
        --monitor-native-crashesWatches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop.
        --wait-dbgStops the Monkey from executing until a debugger is attached to it.
        - - - - - diff --git a/docs/html/guide/developing/tools/monkeyrunner_concepts.jd b/docs/html/guide/developing/tools/monkeyrunner_concepts.jd deleted file mode 100644 index 346a0c648cd5..000000000000 --- a/docs/html/guide/developing/tools/monkeyrunner_concepts.jd +++ /dev/null @@ -1,319 +0,0 @@ -page.title=monkeyrunner -parent.title=Tools -parent.link=index.html -@jd:body - - -

        - The monkeyrunner tool provides an API for writing programs that control an Android device - or emulator from outside of Android code. With monkeyrunner, you can write a Python program - that installs an Android application or test package, runs it, sends keystrokes to it, - takes screenshots of its user interface, and stores screenshots on the workstation. The - monkeyrunner tool is primarily designed to test applications and devices at the - functional/framework level and for running unit test suites, but you are free to use it for - other purposes. -

        -

        - The monkeyrunner tool is not related to the - UI/Application Exerciser Monkey, - also known as the monkey tool. The monkey tool runs in an - adb shell directly on the - device or emulator and generates pseudo-random streams of user and system events. In comparison, - the monkeyrunner tool controls devices and emulators from a workstation by sending specific - commands and events from an API. -

        -

        - The monkeyrunner tool provides these unique features for Android testing: -

        -
          -
        • - Multiple device control: The monkeyrunner API can apply one or more - test suites across multiple devices or emulators. You can physically attach all the devices - or start up all the emulators (or both) at once, connect to each one in turn - programmatically, and then run one or more tests. You can also start up an emulator - configuration programmatically, run one or more tests, and then shut down the emulator. -
        • -
        • - Functional testing: monkeyrunner can run an automated start-to-finish test of an Android - application. You provide input values with keystrokes or touch events, and view the results - as screenshots. -
        • -
        • - Regression testing - monkeyrunner can test application stability by running an application - and comparing its output screenshots to a set of screenshots that are known to be correct. -
        • -
        • - Extensible automation - Since monkeyrunner is an API toolkit, you can develop an entire - system of Python-based modules and programs for controlling Android devices. Besides using - the monkeyrunner API itself, you can use the standard Python - os and - subprocess - modules to call Android tools such as - Android Debug Bridge. -

          - You can also add your own classes to the monkeyrunner API. This is described - in more detail in the section - Extending monkeyrunner with plugins. -

          -
        • -
        -

        - The monkeyrunner tool uses Jython, a - implementation of Python that uses the Java programming language. Jython allows the - monkeyrunner API to interact easily with the Android framework. With Jython you can - use Python syntax to access the constants, classes, and methods of the API. -

        - -

        A Simple monkeyrunner Program

        -

        - Here is a simple monkeyrunner program that connects to a device, creating a - MonkeyDevice - object. Using the MonkeyDevice object, the program installs an Android application - package, runs one of its activities, and sends key events to the activity. - The program then takes a screenshot of the result, creating a - MonkeyImage object. - From this object, the program writes out a .png file containing the screenshot. -

        -
        -# Imports the monkeyrunner modules used by this program
        -from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
        -
        -# Connects to the current device, returning a MonkeyDevice object
        -device = MonkeyRunner.waitForConnection()
        -
        -# Installs the Android package. Notice that this method returns a boolean, so you can test
        -# to see if the installation worked.
        -device.installPackage('myproject/bin/MyApplication.apk')
        -
        -# sets a variable with the package's internal name
        -package = 'com.example.android.myapplication'
        -
        -# sets a variable with the name of an Activity in the package
        -activity = 'com.example.android.myapplication.MainActivity'
        -
        -# sets the name of the component to start
        -runComponent = package + '/' + activity
        -
        -# Runs the component
        -device.startActivity(component=runComponent)
        -
        -# Presses the Menu button
        -device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
        -
        -# Takes a screenshot
        -result = device.takeSnapshot()
        -
        -# Writes the screenshot to a file
        -result.writeToFile('myproject/shot1.png','png')
        -
        - -

        The monkeyrunner API

        -

        - The monkeyrunner API is contained in three modules in the package - com.android.monkeyrunner: -

        -
          -
        • - MonkeyRunner: - A class of utility methods for monkeyrunner programs. This class provides a method for - connecting monkeyrunner to a device or emulator. It also provides methods for - creating UIs for a monkeyrunner program and for displaying the built-in help. -
        • -
        • - MonkeyDevice: - Represents a device or emulator. This class provides methods for installing and - uninstalling packages, starting an Activity, and sending keyboard or touch events to an - application. You also use this class to run test packages. -
        • -
        • - MonkeyImage: - Represents a screen capture image. This class provides methods for capturing screens, - converting bitmap images to various formats, comparing two MonkeyImage objects, and - writing an image to a file. -
        • -
        -

        - In a Python program, you access each class as a Python module. The monkeyrunner tool - does not import these modules automatically. To import a module, use the - Python from statement: -

        -
        -from com.android.monkeyrunner import <module>
        -
        -

        - where <module> is the class name you want to import. You can import more - than one module in the same from statement by separating the module names with - commas. -

        -

        Running monkeyrunner

        -

        - You can either run monkeyrunner programs from a file, or enter monkeyrunner statements in - an interactive session. You do both by invoking the monkeyrunner command - which is found in the tools/ subdirectory of your SDK directory. - If you provide a filename as an argument, the monkeyrunner command - runs the file's contents as a Python program; otherwise, it starts an interactive session. -

        -

        - The syntax of the monkeyrunner command is -

        -
        -monkeyrunner -plugin <plugin_jar> <program_filename> <program_options>
        -
        -

        -Table 1 explains the flags and arguments. -

        -

        - Table 1. monkeyrunner flags and arguments.

        - - - - - - - - - - - - - - - - - - -
        ArgumentDescription
        - - -plugin <plugin_jar> - - - (Optional) Specifies a .jar file containing a plugin for monkeyrunner. - To learn more about monkeyrunner plugins, see - Extending monkeyrunner with plugins. To specify more than one - file, include the argument multiple times. -
        - - <program_filename> - - - If you provide this argument, the monkeyrunner command runs the contents - of the file as a Python program. If the argument is not provided, the command starts an - interactive session. -
        - <program_options> - - (Optional) Flags and arguments for the program in <program_file>. -
        -

        monkeyrunner Built-in Help

        -

        - You can generate an API reference for monkeyrunner by running: -

        -
        -monkeyrunner help.py <format> <outfile>
        -
        -

        -The arguments are: -

        -
          -
        • - <format> is either text for plain text output - or html for HTML output. -
        • -
        • - <outfile> is a path-qualified name for the output file. -
        • -
        -

        Extending monkeyrunner with Plugins

        -

        - You can extend the monkeyrunner API with classes you write in the Java programming language - and build into one or more .jar files. You can use this feature to extend the - monkeyrunner API with your own classes or to extend the existing classes. You can also use this - feature to initialize the monkeyrunner environment. -

        -

        - To provide a plugin to monkeyrunner, invoke the monkeyrunner command with the - -plugin <plugin_jar> argument described in - table 1. -

        -

        - In your plugin code, you can import and extend the the main monkeyrunner classes - MonkeyDevice, MonkeyImage, and MonkeyRunner in - com.android.monkeyrunner (see The monkeyrunner API). -

        -

        - Note that plugins do not give you access to the Android SDK. You can't import packages - such as com.android.app. This is because monkeyrunner interacts with the - device or emulator below the level of the framework APIs. -

        -

        The plugin startup class

        -

        - The .jar file for a plugin can specify a class that is instantiated before - script processing starts. To specify this class, add the key - MonkeyRunnerStartupRunner to the .jar file's - manifest. The value should be the name of the class to run at startup. The following - snippet shows how you would do this within an ant build script: -

        -
        -<jar jarfile="myplugin" basedir="${build.dir}">
        -<manifest>
        -<attribute name="MonkeyRunnerStartupRunner" value="com.myapp.myplugin"/>
        -</manifest>
        -</jar>
        -
        -
        -
        -

        - To get access to monkeyrunner's runtime environment, the startup class can implement - com.google.common.base.Predicate<PythonInterpreter>. For example, this - class sets up some variables in the default namespace: -

        -
        -package com.android.example;
        -
        -import com.google.common.base.Predicate;
        -import org.python.util.PythonInterpreter;
        -
        -public class Main implements Predicate<PythonInterpreter> {
        -    @Override
        -    public boolean apply(PythonInterpreter anInterpreter) {
        -
        -        /*
        -        * Examples of creating and initializing variables in the monkeyrunner environment's
        -        * namespace. During execution, the monkeyrunner program can refer to the variables "newtest"
        -        * and "use_emulator"
        -        *
        -        */
        -        anInterpreter.set("newtest", "enabled");
        -        anInterpreter.set("use_emulator", 1);
        -
        -        return true;
        -    }
        -}
        -
        diff --git a/docs/html/guide/developing/tools/othertools.html b/docs/html/guide/developing/tools/othertools.html deleted file mode 100644 index a074f3350fda..000000000000 --- a/docs/html/guide/developing/tools/othertools.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

        You should be redirected. Please click here.

        - - \ No newline at end of file diff --git a/docs/html/guide/developing/tools/proguard.jd b/docs/html/guide/developing/tools/proguard.jd deleted file mode 100644 index ea8a1eabafda..000000000000 --- a/docs/html/guide/developing/tools/proguard.jd +++ /dev/null @@ -1,189 +0,0 @@ -page.title=ProGuard -parent.title=Tools -parent.link=index.html -@jd:body - - - -

        The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and - renaming classes, fields, and methods with semantically obscure names. The result is a smaller - sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your - application harder to reverse engineer, it is important that you use it - when your application utilizes features that are sensitive to security like when you are - Licensing Your Applications.

        - -

        ProGuard is integrated into the Android build system, so you do not have to invoke it - manually. ProGuard runs only when you build your application in release mode, so you do not - have to deal with obfuscated code when you build your application in debug mode. - Having ProGuard run is completely optional, but highly recommended.

        - -

        This document describes how to enable and configure ProGuard as well as use the - retrace tool to decode obfuscated stack traces.

        - -

        Enabling ProGuard

        - -

        When you create an Android project, a proguard.cfg file is automatically - generated in the root directory of the project. This file defines how ProGuard optimizes and - obfuscates your code, so it is very important that you understand how to customize it for your - needs. The default configuration file only covers general cases, so you most likely have to edit - it for your own needs. See the following section about Configuring ProGuard for information on - customizing the ProGuard configuration file.

        - -

        To enable ProGuard so that it runs as part of an Ant or Eclipse build, set the - proguard.config property in the <project_root>/project.properties - file. The path can be an absolute path or a path relative to the project's root.

        -

        If you left the proguard.cfg file in its default location (the project's root directory), -you can specify its location like this:

        -
        -proguard.config=proguard.cfg
        -
        -

        -You can also move the the file to anywhere you want, and specify the absolute path to it: -

        -
        -proguard.config=/path/to/proguard.cfg
        -
        - - -

        When you build your application in release mode, either by running ant release or - by using the Export Wizard in Eclipse, the build system automatically checks to see if - the proguard.config property is set. If it is, ProGuard automatically processes - the application's bytecode before packaging everything into an .apk file. Building in debug mode - does not invoke ProGuard, because it makes debugging more cumbersome.

        - -

        ProGuard outputs the following files after it runs:

        - -
        -
        dump.txt
        -
        Describes the internal structure of all the class files in the .apk file
        - -
        mapping.txt
        -
        Lists the mapping between the original and obfuscated class, method, and field names. - This file is important when you receive a bug report from a release build, because it - translates the obfuscated stack trace back to the original class, method, and member names. - See Decoding Obfuscated Stack Traces for more information.
        - -
        seeds.txt
        -
        Lists the classes and members that are not obfuscated
        - -
        usage.txt
        -
        Lists the code that was stripped from the .apk
        -
      - -

      These files are located in the following directories:

      - -
        -
      • <project_root>/bin/proguard if you are using Ant.
      • - -
      • <project_root>/proguard if you are using Eclipse.
      • -
      - - -

      Caution: Every time you run a build in release mode, these files are - overwritten with the latest files generated by ProGuard. Save a copy of them each time you release your - application in order to de-obfuscate bug reports from your release builds. - For more information on why saving these files is important, see - Debugging considerations for published applications. -

      - -

      Configuring ProGuard

      - -

      For some situations, the default configurations in the proguard.cfg file will - suffice. However, many situations are hard for ProGuard to analyze correctly and it might remove code - that it thinks is not used, but your application actually needs. Some examples include:

      - -
        -
      • a class that is referenced only in the AndroidManifest.xml file
      • - -
      • a method called from JNI
      • - -
      • dynamically referenced fields and methods
      • -
      - -

      The default proguard.cfg file tries to cover general cases, but you might - encounter exceptions such as ClassNotFoundException, which happens when ProGuard - strips away an entire class that your application calls.

      - -

      You can fix errors when ProGuard strips away your code by adding a -keep line in - the proguard.cfg file. For example:

      -
      --keep public class <MyClass>
      -
      - -

      There are many options and considerations when using the -keep option, so it is - highly recommended that you read the ProGuard - Manual for more information about customizing your configuration file. The Overview of Keep options and - Examples section - are particularly helpful. The Troubleshooting section of the - ProGuard Manual outlines other common problems you might encounter when your code gets stripped - away.

      - -

      Decoding Obfuscated Stack Traces

      - -

      When your obfuscated code outputs a stack trace, the method names are obfuscated, which makes - debugging hard, if not impossible. Fortunately, whenever ProGuard runs, it outputs a - <project_root>/bin/proguard/mapping.txt file, which shows you the original - class, method, and field names mapped to their obfuscated names.

      - -

      The retrace.bat script on Windows or the retrace.sh script on Linux - or Mac OS X can convert an obfuscated stack trace to a readable one. It is located in the - <sdk_root>/tools/proguard/ directory. The syntax for executing the - retrace tool is:

      -
      retrace.bat|retrace.sh [-verbose] mapping.txt [<stacktrace_file>]
      -

      For example:

      - -
      retrace.bat -verbose mapping.txt obfuscated_trace.txt
      - -

      If you do not specify a value for <stacktrace_file>, the retrace tool reads - from standard input.

      - -

      Debugging considerations for published applications

      - -

      Save the mapping.txt file for every release that you publish to your users. - By retaining a copy of the mapping.txt file for each release build, - you ensure that you can debug a problem if a user encounters a bug and submits an obfuscated stack trace. - A project's mapping.txt file is overwritten every time you do a release build, so you must be - careful about saving the versions that you need.

      - -

      For example, say you publish an application and continue developing new features of - the application for a new version. You then do a release build using ProGuard soon after. The - build overwrites the previous mapping.txt file. A user submits a bug report - containing a stack trace from the application that is currently published. You no longer have a way - of debugging the user's stack trace, because the mapping.txt file associated with the version - on the user's device is gone. There are other situations where your mapping.txt file can be overwritten, so - ensure that you save a copy for every release that you anticipate you have to debug.

      - -

      How you save the mapping.txt file is your decision. For example, you can rename them to - include a version or build number, or you can version control them along with your source - code.

      \ No newline at end of file diff --git a/docs/html/guide/developing/tools/sqlite3.jd b/docs/html/guide/developing/tools/sqlite3.jd deleted file mode 100644 index 9cc7e9831a5b..000000000000 --- a/docs/html/guide/developing/tools/sqlite3.jd +++ /dev/null @@ -1,59 +0,0 @@ -page.title=sqlite3 -parent.title=Tools -parent.link=index.html -@jd:body - -

      From a remote shell to your device or from your host machine, you can use the sqlite3 command-line program to manage SQLite databases - created by Android applications. The sqlite3 tool includes many useful commands, - such as .dump to print out the contents of a table and .schema to print - the SQL CREATE statement for an existing table. The tool also gives you the ability to execute - SQLite commands on the fly.

      - -

      To use sqlite3 from a remote shell:

      - -
        -
      1. Enter a remote shell by entering the following command: -
        adb [-d|-e|-s {<serialNumber>}] shell
        -
      2. - -
      3. From a remote shell, start the sqlite3 tool by entering the following command: -
        sqlite3
        - -

        You can also optionally specify a full path to a database that you want to explore. - Emulator/device instances store SQLite3 databases in the directory - /data/data/<package_name>/databases/.

        -
      4. - -
      5. Once you invoke sqlite3, you can issue sqlite3 commands in the - shell. To exit and return to the adb remote shell, enter exit or press - CTRL+D.
      6. -
      - - -

      Here's an example:

      -
      $ adb -s emulator-5554 shell
      -# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db
      -SQLite version 3.3.12
      -Enter ".help" for instructions
      -.... enter commands, then quit...
      -# sqlite> .exit 
      -
      - -

      To use sqlite3 locally, instead of within a shell, - pull the database file from the device and start {@code sqlite3}:

      - -
        -
      1. Copy a database file from your device to your host machine: -
        -adb pull <database-file-on-device>
        -
        -
      2. - -
      3. Start the sqlite3 tool from the /tools directory, specifying the database - file: -
        -sqlite3 <database-file-on-host>
        -
        -
      4. -
      \ No newline at end of file diff --git a/docs/html/guide/developing/tools/traceview.jd b/docs/html/guide/developing/tools/traceview.jd deleted file mode 100644 index aa3748182765..000000000000 --- a/docs/html/guide/developing/tools/traceview.jd +++ /dev/null @@ -1,16 +0,0 @@ -page.title=Traceview -parent.title=Tools -parent.link=index.html -@jd:body - -

      Traceview is a graphical viewer for execution logs saved by your application. -Traceview can help you debug your application and profile its performance.

      - -

      To start Traceview, enter the following command from the SDK tools/ directory:

      -
      traceview
      - - -

      For more information on how to use Traceview, see -Profiling with Traceview and dmtracedump -

      - diff --git a/docs/html/guide/developing/tools/zipalign.jd b/docs/html/guide/developing/tools/zipalign.jd deleted file mode 100644 index 321608058937..000000000000 --- a/docs/html/guide/developing/tools/zipalign.jd +++ /dev/null @@ -1,67 +0,0 @@ -page.title=zipalign -parent.title=Tools -parent.link=index.html -@jd:body - -

      zipalign is an archive alignment tool that provides important -optimization to Android application (.apk) files. -The purpose is to ensure that all uncompressed data starts -with a particular alignment relative to the start of the file. Specifically, -it causes all uncompressed data within the .apk, such as images or raw files, -to be aligned on 4-byte boundaries. This -allows all portions to be accessed directly with {@code mmap()} even if they -contain binary data with alignment restrictions. -The benefit is a reduction in the amount of RAM consumed -when running the application.

      - -

      This tool should always be used to align your .apk file before -distributing it to end-users. The Android build tools can handle -this for you. When using Eclipse with the ADT plugin, the Export Wizard -will automatically zipalign your .apk after it signs it with your private key. -The build scripts used -when compiling your application with Ant will also zipalign your .apk, -as long as you have provided the path to your keystore and the key alias in -your project {@code ant.properties} file, so that the build tools -can sign the package first.

      - -

      Caution: zipalign must only be performed -after the .apk file has been signed with your private key. -If you perform zipalign before signing, then the signing procedure will undo -the alignment. Also, do not make alterations to the aligned package. -Alterations to the archive, such as renaming or deleting entries, will -potentially disrupt the alignment of the modified entry and all later -entries. And any files added to an "aligned" archive will not be aligned.

      - -

      The adjustment is made by altering the size of -the "extra" field in the zip Local File Header sections. Existing data -in the "extra" fields may be altered by this process.

      - -

      For more information about how to use zipalign when building your -application, please read Signing -Your Application.

      - - -

      Usage

      - -

      To align {@code infile.apk} and save it as {@code outfile.apk}:

      - -
      zipalign [-f] [-v] <alignment> infile.apk outfile.apk
      - -

      To confirm the alignment of {@code existing.apk}:

      - -
      zipalign -c -v <alignment> existing.apk
      - -

      The {@code <alignment>} is an integer that defines the byte-alignment boundaries. -This must always be 4 (which provides 32-bit alignment) or else it effectively -does nothing.

      - -

      Flags:

      - -
        -
      • {@code -f} : overwrite existing outfile.zip
      • -
      • {@code -v} : verbose output
      • -
      • {@code -c} : confirm the alignment of the given file
      • -
      - - - diff --git a/docs/html/guide/google/index.jd b/docs/html/guide/google/index.jd new file mode 100644 index 000000000000..95c2816b416e --- /dev/null +++ b/docs/html/guide/google/index.jd @@ -0,0 +1,97 @@ +page.title=Google Services +footer.hide=1 +@jd:body + + +

      Google offers a variety of services that help you build new revenue streams, enhance your app's capabilities, manage distribution and payloads, and track usage and installs. Many of the services use static libraries that you download through the Android SDK Manager and build into your app. Others are configurable directly from Google Play Android Developer Console.

      + +

      The sections below highlight some of the Google Services and link you to more information about how to use them in your Android app.

      + + +

      Monetize Your App

      + +
       
      +
      + +
      +

      In-App Billing

      +

      Keep your users engaged by offering in-app purchases and subscriptions directly in your app. +

      + Learn more » +
      + +
      +

      Google AdMob Ads

      +

      Generate more revenue from your app by + displaying ads from multiple ad networks.

      + Learn more » +
      + +
      +

      Application Licensing

      +

      Protect your revenue streams and integrate policies for usage into your app.

      + Learn more » +
      + +
      + +

      Manage App Distribution

      + +
       
      + +
      + +
      + +

      Google Play Filters

      +

      Make sure your app gets to the right users by +declaring the hardware and software features needed by your app.

      +Learn more » +
      + +
      +

      Multiple APK Support

      +

      Distribute different APKs based on a variety of properties such as platform version, screen size, and GLES texture compression support.

      +Learn more » +
      + +
      + +

      APK Expansion files

      +

      Take load off of your servers and utilize APK expansion files +to deliver up to 4 GB of assets for your Android app, free.

      + +Learn more » +
      + +
      + +

      Enhance Your App's Capabilities

      + +
       
      + +
      + +
      +

      Android Cloud-to-Device Messaging

      +

      Notify your apps of events with push messages that are lightweight + and battery-saving.

      + Learn more » +
      + +
      +

      Google Maps

      +

      The Google Maps library for Android lets you add powerful mapping and geo-location capabilities to your app.

      + Learn more » +
      +
      + + +

      Track Performance with Analytics

      +

      Google Analytics gives you powerful insights into how users find your apps + and how they use them.
      Start integrating analytics to measure + your app's success.

      + + + + \ No newline at end of file diff --git a/docs/html/guide/google/play/billing/billing_about.html b/docs/html/guide/google/play/billing/billing_about.html new file mode 100644 index 000000000000..9f41fa62e344 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_about.html @@ -0,0 +1,12 @@ + + + +Redirecting... + + +

      You should be redirected. Please click +here.

      + + \ No newline at end of file diff --git a/docs/html/guide/google/play/billing/billing_admin.jd b/docs/html/guide/google/play/billing/billing_admin.jd new file mode 100755 index 000000000000..cb288a5381d5 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_admin.jd @@ -0,0 +1,530 @@ +page.title=Administering In-app Billing +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

      In-app billing frees you from processing financial transactions, but you still need to perform a +few administrative tasks, including setting up and maintaining your product list on the publisher +site, registering test accounts, and handling refunds when necessary.

      + +

      You must have a Google Play publisher account to register test accounts. And you must have a +Google Wallet merchant account to create a product list and issue refunds to your users. If you +already have a publisher account on Google Play, you can use your existing account. You do not +need to register for a new account to support in-app billing. If you do not have a publisher +account, you can register as a Google Play developer and set up a publisher account at the +Google Play publisher site. If you do not have a +Google Wallet merchant account, you can register for one at the Google Wallet site.

      + +

      Creating a Product List

      + +

      The Google Play publisher site provides a product list for each of your published +applications. You can sell an item using Google Play's in-app billing feature only if the item is +listed on an application's product list. Each application has its own product list; you cannot sell +items that are listed in another application's product list.

      + +

      You can access an application's product list by clicking the In-App Products +link that appears under each of the applications that are listed for your publisher account (see +figure 1). The In-App Products link appears only if you have a Google Wallet +merchant account and an application's manifest includes the com.android.vending.BILLING +permission.

      + + +

      + Figure 1. You can access an application's product list by clicking the + In-App Products link. +

      + +

      A product list specifies items you are selling in an application — in-app products, +subscriptions, or a combination of both. For each item, the product list contains information such as a product id, +product description, and price (see figure 2). The product list stores only metadata about the items +you are selling in your application. It does not store any digital content. You are responsible for +storing and delivering the digital content that you sell in your applications.

      + + +

      + Figure 2. An application's product list. +

      + +

      You can create a product list for any published application or any draft application that's been +uploaded and saved to the Google Play site. However, you must have a Google Wallet merchant +account and the application's manifest must include the com.android.vending.BILLING +permission. If an application's manifest does not include this permission, you will be able to edit +existing items in the product list but you will not be able to add new items to the list. For more +information about this permission, see +Updating Your +Application's Manifest.

      + +

      In addition, an application package can have only one product list. If you create a product +list for an application, and you use the multiple APK feature to distribute +more than one APK for that application, the product list applies to all APK versions that are +associated with the application listing. You cannot create individual product lists for each APK if +you are using the multiple APK feature.

      + +

      You can add items to a product list two ways: you can add items one at a time by using the In-app +Products UI (see figure 3), or you can add a batch of items by importing the items from a +comma-separated values (CSV) file (see figure 2). Adding items one at a time is useful if your +application has only a few in-app items or you are adding only a few items to a +product list for testing purposes. The CSV file method is useful if your application has a large +number of in-app items.

      + +

      Note: Batch upload of product lists containing subscriptions is not yet supported.

      + +

      Adding items one at a time to a product list

      + +

      To add an item to a product list using the In-app Products UI, follow these steps:

      + +
        +
      1. Log in to your publisher account.
      2. +
      3. In the All Google Play listings panel, under the application name, click + In-app Products.
      4. +
      5. On the In-app Products List page, click Add in-app product.
      6. +
      7. On the Create New In-app Product page (see figure 3), provide details about the item you are + selling and then click Save or Publish.
      8. +
      + + +

      + Figure 3. The Create New In-app Product page lets you add items to an + application's product list. +

      + +

      You must enter the following information for each item in a product list:

      +
        +
      • In-app Product ID +

        Product IDs are unique across an application's namespace. A product ID must start with a + lowercase letter or a number, and must be composed using only lowercase letters (a-z), numbers + (0-9), underlines (_), and dots (.). The product ID "android.test" is reserved, as are all + product IDs that start with "android.test."

        +

        In addition, you cannot modify an item's product ID after it is created, and you cannot reuse + a product ID.

        +
      • +
      • Purchase Type +

        The purchase type can be Managed per user account, Unmanaged, + or Subscription. You can never change an item's purchase type after you set it. For more + information, see Choosing a purchase type later in this + document.

        +
      • +
      • Publishing State +

        An item's publishing state can be Published or Unpublished + . To be visible to a user during checkout, an item's publishing state must be set to + Published and the item's application must be published on Google Play.

        +

        Note: This is not true for test accounts. An item is visible to + a test account if the application is not published and the item is published. See Testing In-app + Billing for more information.

        +
      • +
      • Language +

        The language setting determines which languages are used to display the item title and + item description during checkout. A product list inherits its default language from the + parent application. You can add more languages by clicking add language. You + can also choose to have the title and description automatically translated from the default + language by selecting the Fill fields with auto translation checkbox (see + figure 4). If you do not use the auto translation feature, you must provide the translated + versions of the title and description.

        +
      • +
      • Title +

        The title is a short descriptor for the item. For example, "Sleeping potion." Titles must be + unique across an application's namespace. Every item must have a title. The title is visible to + users during checkout. For optimum appearance, titles should be no longer than 25 characters; + however, titles can be up to 55 characters in length.

        +
      • +
      • Description +

        The description is a long descriptor for the item. For example, "Instantly puts creatures to + sleep. Does not work on angry elves." Every item must have a description. The description is + visible to users during checkout. Descriptions can be up to 80 characters in length.

        +
      • +
      • Price +

        You must provide a default price in your home currency. You can also provide prices in other + currencies, but you can do this only if a currency's corresponding country is listed as a + target country for your application. You can specify target countries on the Edit Application + page in the Google Play developer console.

        +

        To specify prices in other currencies, you can manually enter the price for each + currency or you can click Auto Fill and let Google Play do a one-time + conversion from your home currency to the currencies you are targeting (see figure 4).

        +

        For subscription items, note that you can not change the item's price once you have published it.

        +
      • +
      + +

      + Figure 4. Specifying additional currencies and additional languages for the + item title and description. +

      + +

      For more information about product IDs and product lists, see Creating In-App Product +IDs. For more information about pricing, see In-App Billing +Pricing.

      + +

      Note: Be sure to plan your product ID namespace. You cannot reuse +or modify product IDs after you save them.

      + +

      Adding a batch of items to a product list

      + +

      To add a batch of items to a product list using a CSV file, you first need to create your CSV +file. The data values that you specify in the CSV file represent the same data values you specify +manually through the In-app Products UI (see Adding items one at a time +to a product list). + +

      If you are importing and exporting CSV files with in-app products, please +keep tax-inclusive pricing in mind. If you use auto-fill, you can provide a +tax-exclusive default price and tax-inclusive prices will be auto-filled. If you +do not use auto-fill, prices you provide must include tax.

      + +

      Note: Batch upload of product lists containing subscriptions is not yet supported.

      + +The CSV file uses commas (,) and semi-colons (;) to separate data values. +Commas are used to separate primary data values, and semi-colons are used to separate subvalues. For +example, the syntax for the CSV file is as follows:

      + +

      "product_id","publish_state","purchase_type","autotranslate +","locale; title; description","autofill","country; +price" +

      + +

      Descriptions and usage details are provided below.

      + +
        +
      • product_id +

        This is equivalent to the In-app Product ID setting in the In-app Products UI. If you specify + a product_id that already exists in a product list, and you choose to overwrite + the product list while importing the CSV file, the data for the existing item is overwritten with + the values specified in the CSV file. The overwrite feature does not delete items that are on a + product list but not present in the CSV file.

        +
      • +
      • publish_state +

        This is equivalent to the Publishing State setting in the In-app Products UI. Can be + published or unpublished.

        +
      • +
      • purchase_type +

        This is equivalent to the Purchase Type setting in the In-app Products UI. Can be + managed_by_android, which is equivalent to Managed per user account + in the In-app Products UI, or managed_by_publisher, which is equivalent + to Unmanaged in the In-app Products UI.

        +
      • +
      • autotranslate +

        This is equivalent to selecting the Fill fields with auto translation + checkbox in the In-app Products UI. Can be true or false.

        +
      • +
      • locale +

        This is equivalent to the Language setting in the In-app Products UI. You must have an entry + for the default locale. The default locale must be the first entry in the list of + locales, and it must include a title and description. If you want to provide + translated versions of the title and description in addition to the default, + you must use the following syntax rules:

        +

        If autotranslate is true, you must specify the default locale, + default title, default description, and other locales using the following format:

        +

        "true,"default_locale; default_locale_title; + default_locale_description; locale_2; locale_3, ..."

        +

        If autotranslate is false, you must specify the default locale, + default title, and default description as well as the translated titles and descriptions using + the following format:

        +

        "false,"default_locale; default_locale_title; + default_locale_description; locale_2; locale_2_title; + local_2_description; locale_3; locale_3_title; + locale_3_description; ..."

        +

        See table 1 for a list of the language codes you can use with the locale field.

        +
      • +
      • title +

        This is equivalent to the Title setting in the In-app Products UI. If the title + contains a semicolon, it must be escaped with a backslash (for example, "\;"). A backslash + should also be escaped with a backslash (for example, "\\">.

        +
      • +
      • description +

        This is equivalent to the Description in the In-app Products UI. If the description + contains a semicolon, it must be escaped with a backslash (for example, "\;"). A backslash + should also be escaped with a backslash (for example, "\\">.

        +
      • +
      • autofill +

        This is equivalent to clicking Auto Fill in the In-app Products UI. Can be + true or false. The syntax for specifying the country + and price varies depending on which autofill setting you use.

        +

        If autofill is set to true, you need to specify only the default + price in your home currency and you must use this syntax:

        +

        "true","default_price_in_home_currency" +

        If autofill is set to false, you need to specify a country + and a price for each currency and you must use the following syntax:

        +

        "false", "home_country; default_price_in_home_currency; country_2; + country_2_price; country_3; country_3_price; ..."

        +
      • +
      • country +

        The country for which you are specifying a price. You can only list countries that your + application is targeting. The country codes are two-letter uppercase + ISO country codes (such as "US") as defined by + ISO 3166-2.

        +
      • +
      • price +

        This is equivalent to the Price in the In-app Products UI. The price must be specified in + micro-units. To convert a currency value to micro-units, you multiply the real value by 1,000,000. + For example, if you want to sell an in-app item for $1.99 you specify 1990000 in the + price field.

        +
      • +
      + +

      Table 1. Language codes you can use +with the locale field.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      LanguageCodeLanguageCode
      Chinesezh_TWItalianit_IT
      Czechcs_CZJapaneseja_JP
      Danishda_DKKoreanko_KR
      Dutchnl_NLNorwegianno_NO
      Englishen_USPolishpl_PL
      Frenchfr_FRPortuguesept_PT
      Finnishfi_FIRussianru_RU
      Germande_DESpanishes_ES
      Hebrewiw_ILSwedishsv_SE
      Hindihi_IN----
      + +

      To import the items that are specified in your CSV file, do the following:

      + +
        +
      1. Log in to your publisher account.
      2. +
      3. In the All Google Play listings panel, under the application name, click + In-app Products.
      4. +
      5. On the In-app Products List page, click Choose File and select your CSV +file. +

        The CSV file must be on your local computer or on a local disk that is connected to your + computer.

        +
      6. +
      7. Select the Overwrite checkbox if you want to overwrite existing items in + your product list. +

        This option overwrites values of existing items only if the value of the product_id + in the CSV file matches the In-app Product ID for an existing item in the product list. + Overwriting does not delete items that are on a product list but not present in the CSV + file.

        +
      8. +
      9. On the In-app Products List page, click Import from CSV.
      10. +
      + +

      You can also export an existing product list to a CSV file by clicking Export to CSV + on the In-app Product List page. This is useful if you have manually added items to +a product list and you want to start managing the product list through a CSV file.

      + +

      Choosing a Purchase Type

      + +

      An item's purchase type controls how Google Play manages the purchase of the item. There are +two purchase types: "managed per user account" and "unmanaged."

      + +

      Items that are managed per user account can be purchased only once per user account. When an item +is managed per user account, Google Play permanently stores the transaction information for each +item on a per-user basis. This enables you to query Google Play with the +RESTORE_TRANSACTIONS request and restore the state of the items a specific user has +purchased.

      + +

      If a user attempts to purchase a managed item that has already been purchased, Google Play +displays an "Item already purchased" error. This occurs during checkout, when Google Play +displays the price and description information on the checkout page. When the user dismisses the +error message, the checkout page disappears and the user returns to your user interface. As a best +practice, your application should prevent the user from seeing this error. The sample application +demonstrates how you can do this by keeping track of items that are managed and already purchased +and not allowing users to select those items from the list. Your application should do something +similar—either graying out the item or hiding it so that it cannot be selected.

      + +

      The "manage by user account" purchase type is useful if you are selling items such as game levels +or application features. These items are not transient and usually need to be restored whenever a +user reinstalls your application, wipes the data on their device, or installs your application on a +new device.

      + +

      Items that are unmanaged do not have their transaction information stored on Google Play, +which means you cannot query Google Play to retrieve transaction information for items whose +purchase type is listed as unmanaged. You are responsible for managing the transaction information +of unmanaged items. Also, unmanaged items can be purchased multiple times as far as Google Play +is concerned, so it's also up to you to control how many times an unmanaged item can be +purchased.

      + +

      The "unmanaged" purchase type is useful if you are selling consumable items, such as fuel or +magic spells. These items are consumed within your application and are usually purchased multiple +times.

      + +

      Handling Refunds

      + +

      In-app billing does not allow users to send a refund request to Google Play. Refunds for +in-app purchases must be directed to you (the application developer). You can then process the +refund through your Google Wallet merchant account. When you do this, Google Play receives a +refund notification from Google Wallet, and Google Play sends a refund message to your +application. For more information, see Handling +IN_APP_NOTIFY messages and In-app Billing +Pricing.

      + +

      Important: You cannot use the Google Wallet API to issue +refunds or cancel in-app billing transactions. You must do this manually through your Google +Wallet merchant account. However, you can use the Google Wallet API to retrieve order +information.

      + +

      Setting Up Test Accounts

      + +

      The Google Play publisher site lets you set up one or more test accounts. A test account is a +regular Google account that you register on the publisher site as a test account. Test accounts are +authorized to make in-app purchases from applications that you have uploaded to the Google Play +site but have not yet published.

      + +

      You can use any Google account as a test account. Test accounts are useful if you want to let +multiple people test in-app billing on applications without giving them access to your publisher +account's sign-in credentials. If you want to own and control the test accounts, you can create the +accounts yourself and distribute the credentials to your developers or testers.

      + +

      Test accounts have three limitations:

      + +
        +
      • Test account users can make purchase requests only within applications that are already + uploaded to your publisher account (although the application doesn't need to be published).
      • +
      • Test accounts can only be used to purchase items that are listed (and published) in an + application's product list.
      • +
      • Test account users do not have access to your publisher account and cannot upload applications + to your publisher account.
      • +
      + +

      To add test accounts to your publisher account, follow these steps:

      + +
        +
      1. Log in to your publisher account.
      2. +
      3. On the upper left part of the page, under your name, click Edit profile.
      4. +
      5. On the Edit Profile page, scroll down to the Licensing & In-app Billing panel (see figure + 5).
      6. +
      7. In Test Accounts, add the email addresses for the test accounts you want to register, + separating each account with a comma.
      8. +
      9. Click Save to save your profile changes.
      10. +
      + + +

      + Figure 5. The Licensing and In-app Billing panel of your account's Edit Profile + page lets you register test accounts. +

      + +

      Where to Get Support

      + +

      If you have questions or encounter problems while implementing in-app billing, contact the +support resources listed in the following table (see table 2). By directing your queries to the +correct forum, you can get the support you need more quickly.

      + +

      Table 2. Developer support resources +for Google Play in-app billing.

      + + + + + + + + + + + + + + + + + + + + + +
      Support TypeResourceRange of Topics
      Development and testing issuesGoogle Groups: android-developers In-app billing integration questions, user experience ideas, handling of responses, +obfuscating code, IPC, test environment setup.
      Stack Overflow: http://stackoverflow.com/questions/tagged/ +android
      Billing issue trackerBilling +project issue trackerBug and issue reports related specifically to in-app billing sample code.
      + +

      For general information about how to post to the groups listed above, see Developer Forums document in the Resources +tab.

      + + + diff --git a/docs/html/guide/google/play/billing/billing_best_practices.jd b/docs/html/guide/google/play/billing/billing_best_practices.jd new file mode 100755 index 000000000000..49d2a299f5da --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_best_practices.jd @@ -0,0 +1,111 @@ +page.title=Security and Design +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

      As you design your in-app billing implementation, be sure to follow the security and design +guidelines that are discussed in this document. These guidelines are recommended best practices for +anyone who is using Google Play's in-app billing service.

      + +

      Security Best Practices

      + +

      Perform signature verification tasks on a server

      +

      If practical, you should perform signature verification on a remote server and not on a device. +Implementing the verification process on a server makes it difficult for attackers to break the +verification process by reverse engineering your .apk file. If you do offload security processing to +a remote server, be sure that the device-server handshake is secure.

      + +

      Protect your unlocked content

      +

      To prevent malicious users from redistributing your unlocked content, do not bundle it in your +.apk file. Instead, do one of the following:

      +
        +
      • Use a real-time service to deliver your content, such as a content feed. Delivering content + through a real-time service allows you to keep your content fresh.
      • +
      • Use a remote server to deliver your content.
      • +
      +

      When you deliver content from a remote server or a real-time service, you can store the unlocked +content in device memory or store it on the device's SD card. If you store content on an SD card, be +sure to encrypt the content and use a device-specific encryption key.

      + +

      Obfuscate your code

      +

      You should obfuscate your in-app billing code so it is difficult for an attacker to reverse +engineer security protocols and other application components. At a minimum, we recommend that you +run an obfuscation tool like Proguard on your +code.

      +

      In addition to running an obfuscation program, we recommend that you use the following techniques +to obfuscate your in-app billing code.

      +
        +
      • Inline methods into other methods.
      • +
      • Construct strings on the fly instead of defining them as constants.
      • +
      • Use Java reflection to call methods.
      • +
      +

      Using these techniques can help reduce the attack surface of your application and help minimize +attacks that can compromise your in-app billing implementation.

      +
      +

      Note: If you use Proguard to obfuscate your code, you must add the following + line to your Proguard configuration file:

      +

      -keep class com.android.vending.billing.**

      +
      + +

      Modify all sample application code

      +

      The in-app billing sample application is publicly distributed and can be downloaded by anyone, +which means it is relatively easy for an attacker to reverse engineer your application if you use +the sample code exactly as it is published. The sample application is intended to be used only as an +example. If you use any part of the sample application, you must modify it before you publish it or +release it as part of a production application.

      +

      In particular, attackers look for known entry points and exit points in an application, so it is +important that you modify these parts of your code that are identical to the sample application.

      + +

      Use secure random nonces

      +

      Nonces must not be predictable or reused. Always use a cryptographically secure random number +generator (like {@link java.security.SecureRandom}) when you generate nonces. This can help reduce +replay attacks.

      +

      Also, if you are performing nonce verification on a server, make sure that you generate the +nonces on the server.

      + +

      Take action against trademark and copyright infringement

      +

      If you see your content being redistributed on Google Play, act quickly and decisively. File a +trademark notice +of infringement or a copyright notice of +infringement.

      + +

      Implement a revocability scheme for unlocked content

      +

      If you are using a remote server to deliver or manage content, have your application verify the +purchase state of the unlocked content whenever a user accesses the content. This allows you to +revoke use when necessary and minimize piracy.

      + +

      Protect your Google Play public key

      +

      To keep your public key safe from malicious users and hackers, do not embed it in any code as a +literal string. Instead, construct the string at runtime from pieces or use bit manipulation (for +example, XOR with some other string) to hide the actual key. The key itself is not secret +information, but you do not want to make it easy for a hacker or malicious user to replace the +public key with another key.

      + diff --git a/docs/html/guide/google/play/billing/billing_integrate.jd b/docs/html/guide/google/play/billing/billing_integrate.jd new file mode 100755 index 000000000000..2d1582eebb34 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_integrate.jd @@ -0,0 +1,1100 @@ +page.title=Implementing In-app Billing +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

      In-app Billing on Google Play provides a straightforward, simple interface for sending in-app +billing requests and managing in-app billing transactions using Google Play. This document helps +you implement in-app billing by stepping through the primary implementation tasks, using the in-app +billing sample application as an example.

      + +

      Before you implement in-app billing in your own application, be sure that you read Overview of In-app Billing and Security and Design. These +documents provide background information that will make it easier for you to implement in-app +billing.

      + +

      To implement in-app billing in your application, you need to do the following:

      +
        +
      1. Download the in-app billing sample application.
      2. +
      3. Add the IMarketBillingService.aidl file to your project.
      4. +
      5. Update your AndroidManifest.xml file.
      6. +
      7. Create a Service and bind it to the + MarketBillingService so your application can send billing requests and receive + billing responses from Google Play.
      8. +
      9. Create a BroadcastReceiver to handle broadcast + intents from Google Play.
      10. +
      11. Create a security processing component to verify the + integrity of the transaction messages that are sent by Google Play.
      12. +
      13. Modify your application code to support in-app billing.
      14. +
      + +

      Downloading the Sample Application

      + +

      The in-app billing sample application shows you how to perform several tasks that are common to +all in-app billing implementations, including:

      + +
        +
      • Sending in-app billing requests to Google Play.
      • +
      • Handling synchronous responses from Google Play.
      • +
      • Handling broadcast intents (asynchronous responses) from Google Play.
      • +
      • Using in-app billing security mechanisms to verify the integrity of billing responses.
      • +
      • Creating a user interface that lets users select items for purchase.
      • +
      + +

      The sample application includes an application file (Dungeons.java), the AIDL file +for the MarketBillingService (IMarketBillingService.aidl), and several +classes that demonstrate in-app billing messaging. It also includes a class that demonstrates basic +security tasks, such as signature verification.

      + +

      Table 1 lists the source files that are included with the sample application.

      +

      Table 1. In-app billing sample +application source files.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileDescription
      IMarketBillingService.aidlAndroid Interface Definition Library (AIDL) file that defines the IPC interface to Google +Play's in-app billing service (MarketBillingService).
      Dungeons.javaSample application file that provides a UI for making purchases and displaying purchase +history.
      PurchaseDatabase.javaA local database for storing purchase information.
      BillingReceiver.javaA {@link android.content.BroadcastReceiver} that receives asynchronous response messages + (broadcast intents) from Google Play. Forwards all messages to the + BillingService.
      BillingService.javaA {@link android.app.Service} that sends messages to Google Play on behalf of the + application by connecting (binding) to the MarketBillingService.
      ResponseHandler.javaA {@link android.os.Handler} that contains methods for updating the purchases database and the + UI.
      PurchaseObserver.javaAn abstract class for observing changes related to purchases.
      Security.javaProvides various security-related methods.
      Consts.javaDefines various Google Play constants and sample application constants. All constants that +are defined by Google Play must be defined the same way in your application.
      Base64.java and Base64DecoderException.javaProvides conversion services from binary to Base64 encoding. The Security class +relies on these utility classes.
      + +

      The in-app billing sample application is available as a downloadable component of the Android +SDK. To download the sample application component, launch the Android SDK Manager and then +select the Google Market Billing package component (see figure 1), and click Install +Selected to begin the download.

      + + + +

      + Figure 1. The Google Market Billing package contains the sample application and + the AIDL file. +

      + +

      When the download is complete, the Android SDK Manager saves the component into the +following directory:

      + +

      <sdk>/extras/google/market_billing/

      + +

      If you want to see an end-to-end demonstration of in-app billing before you integrate in-app +billing into your own application, you can build and run the sample application. Building and +running the sample application involves three tasks:

      + +
        +
      • Configuring and building the sample application.
      • +
      • Uploading the sample application to Google Play.
      • +
      • Setting up test accounts and running the sample application.
      • +
      + +

      Note: Building and running the sample application is necessary only +if you want to see a demonstration of in-app billing. If you do not want to run the sample +application, you can skip to the next section, Adding the AIDL file to +your project.

      + +

      Configuring and building the sample application

      + +

      Before you can run the sample application, you need to configure it and build it by doing the +following:

      + +
        +
      1. Add your Google Play public key to the sample application code. +

        This enables the application to verify the signature of the transaction information that is + returned from Google Play. To add your public key to the sample application code, do the + following:

        +
          +
        1. Log in to your Google Play publisher + account.
        2. +
        3. On the upper left part of the page, under your name, click Edit + Profile.
        4. +
        5. On the Edit Profile page, scroll down to the Licensing & In-app + Billing panel.
        6. +
        7. Copy your public key.
        8. +
        9. Open src/com/example/dungeons/Security.java in the editor of your choice. +

          You can find this file in the sample application's project folder.

          +
        10. +
        11. Add your public key to the following line of code: +

          String base64EncodedPublicKey = "your public key here";

          +
        12. +
        13. Save the file.
        14. +
        +
      2. +
      3. Change the package name of the sample application. +

        The current package name is com.example.dungeons. Google Play does not let + you upload applications with package names that contain com.example, so you must + change the package name to something else.

        +
      4. +
      5. Build the sample application in release mode and sign it. +

        To learn how to build and sign applications, see Building and Running.

        +
      6. +
      + +

      Uploading the sample application

      + +

      After you build a release version of the sample application and sign it, you need to upload it as +a draft to the Google Play publisher site. You also need to create a product list for the in-app +items that are available for purchase in the sample application. The following instructions show you +how to do this.

      +
        +
      1. Upload the release version of the sample application to Google Play. +

        Do not publish the sample application; leave it as an unpublished draft application. The + sample application is for demonstration purposes only and should not be made publicly available + on Google Play. To learn how to upload an application to Google Play, see Uploading + applications.

        +
      2. +
      3. Create a product list for the sample application. +

        The sample application lets you purchase two items: a two-handed sword + (sword_001) and a potion (potion_001). We recommend that you set up + your product list so that sword_001 has a purchase type of "Managed per user + account" and potion_001 has a purchase type of "Unmanaged" so you can see how these + two purchase types behave. To learn how to set up a product list, see Creating a Product + List.

        +

        Note: You must publish the items in your product + list (sword_001 and potion_001) even though you are not publishing the + sample application. Also, you must have a Google Wallet Merchant account to add items to the + sample application's product list.

        +
      4. +
      + +

      Running the sample application

      + +

      You cannot run the sample application in the emulator. You must install the sample application +onto a device to run it. To run the sample application, do the following:

      + +
        +
      1. Make sure you have at least one test account registered under your Google Play + publisher account. +

        You cannot purchase items from yourself (Google Wallet prohibits this), so you need to + create at least one test account that you can use to purchase items in the sample application. + To learn how to set up a test account, see Setting up Test + Accounts.

        +
      2. +
      3. Verify that your device is running a supported version of the Google Play + application or the MyApps application. +

        If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of + the MyApps application. If your device is running any other version of Android, in-app billing + requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the + version of the Google Play application, see Updating Google + Play.

        +
      4. +
      5. Install the application onto your device. +

        Even though you uploaded the application to Google Play, the application is not published, + so you cannot download it from Google Play to a device. Instead, you must install the + application onto your device. To learn how to install an application onto a device, see Running on a + device.

        +
      6. +
      7. Make one of your test accounts the primary account on your device. +

        The primary account on your device must be one of the test accounts + that you registered on the Google Play publisher site. If the primary account on your device is not a + test account, you must do a factory reset of the device and then sign in with one of your test + accounts. To perform a factory reset, do the following:

        +
          +
        1. Open Settings on your device.
        2. +
        3. Touch Privacy.
        4. +
        5. Touch Factory data reset.
        6. +
        7. Touch Reset phone.
        8. +
        9. After the phone resets, be sure to sign in with one of your test accounts during the + device setup process.
        10. +
        +
      8. +
      9. Run the application and purchase the sword or the potion. +

        When you use a test account to purchase items, the test account is billed through Google + Wallet and your Google Wallet Merchant account receives a payout for the purchase. + Therefore, you may want to refund purchases that are made with test accounts, otherwise the + purchases will show up as actual payouts to your merchant account.

        +
      + +

      Note: Debug log messages are turned off by default in the +sample application. You can turn them on by setting the variable DEBUG +to true in the Consts.java file.

      + +

      Adding the AIDL file to your project

      + +

      The sample application contains an Android Interface Definition Language (AIDL) file, which +defines the interface to Google Play's in-app billing service +(MarketBillingService). When you add this file to your project, the Android build +environment creates an interface file (IMarketBillingService.java). You can then use +this interface to make billing requests by invoking IPC method calls.

      + +

      If you are using the ADT plug-in with Eclipse, you can just add this file to your +/src directory. Eclipse will automatically generate the interface file when you build +your project (which should happen immediately). If you are not using the ADT plug-in, you can put +the AIDL file into your project and use the Ant tool to build your project so that the +IMarketBillingService.java file gets generated.

      + +

      To add the IMarketBillingService.aidl file to your project, do the following:

      + +
        +
      1. Create the following directory in your application's /src directory: +

        com/android/vending/billing/

        +
      2. +
      3. Copy the IMarketBillingService.aidl file into the + sample/src/com/android/vending/billing/ directory.
      4. +
      5. Build your application.
      6. +
      + +

      You should now find a generated interface file named IMarketBillingService.java in +the gen folder of your project.

      + +

      Updating Your Application's Manifest

      + +

      In-app billing relies on the Google Play application, which handles all communication between +your application and the Google Play server. To use the Google Play application, your +application must request the proper permission. You can do this by adding the +com.android.vending.BILLING permission to your AndroidManifest.xml file. If your +application does not declare the in-app billing permission, but attempts to send billing requests, +Google Play will refuse the requests and respond with a RESULT_DEVELOPER_ERROR +response code.

      + +

      In addition to the billing permission, you need to declare the {@link +android.content.BroadcastReceiver} that you will use to receive asynchronous response messages +(broadcast intents) from Google Play, and you need to declare the {@link android.app.Service} +that you will use to bind with the IMarketBillingService and send messages to Google +Play. You must also declare intent filters for the {@link +android.content.BroadcastReceiver} so that the Android system knows how to handle the broadcast +intents that are sent from the Google Play application.

      + +

      For example, here is how the in-app billing sample application declares the billing permission, +the {@link android.content.BroadcastReceiver}, the {@link android.app.Service}, and the intent +filters. In the sample application, BillingReceiver is the {@link +android.content.BroadcastReceiver} that handles broadcast intents from the Google Play +application and BillingService is the {@link android.app.Service} that sends requests +to the Google Play application.

      + +
      +<?xml version="1.0" encoding="utf-8"?>
      +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      +  package="com.example.dungeons"
      +  android:versionCode="1"
      +  android:versionName="1.0">
      +
      +  <uses-permission android:name="com.android.vending.BILLING" />
      +
      +  <application android:icon="@drawable/icon" android:label="@string/app_name">
      +    <activity android:name=".Dungeons" android:label="@string/app_name">
      +      <intent-filter>
      +        <action android:name="android.intent.action.MAIN" />
      +        <category android:name="android.intent.category.LAUNCHER" />
      +      </intent-filter>
      +    </activity>
      +
      +    <service android:name="BillingService" />
      +
      +    <receiver android:name="BillingReceiver">
      +      <intent-filter>
      +        <action android:name="com.android.vending.billing.IN_APP_NOTIFY" />
      +        <action android:name="com.android.vending.billing.RESPONSE_CODE" />
      +        <action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" />
      +      </intent-filter>
      +    </receiver>
      +
      +  </application>
      +</manifest>
      +
      + +

      Creating a Local Service

      + +

      Your application must have a local {@link android.app.Service} to facilitate messaging between +your application and Google Play. At a minimum, this service must do the following:

      + +
        +
      • Bind to the MarketBillingService. +
      • Send billing requests (as IPC method calls) to the Google Play application. The five types + of billing requests include: +
          +
        • CHECK_BILLING_SUPPORTED requests
        • +
        • REQUEST_PURCHASE requests
        • +
        • GET_PURCHASE_INFORMATION requests
        • +
        • CONFIRM_NOTIFICATIONS requests
        • +
        • RESTORE_TRANSACTIONS requests
        • +
        +
      • +
      • Handle the synchronous response messages that are returned with each billing request.
      • +
      + +

      Binding to the MarketBillingService

      + +

      Binding to the MarketBillingService is relatively easy if you've already added the +IMarketBillingService.aidl file to your project. The following code sample shows how to +use the {@link android.content.Context#bindService bindService()} method to bind a service to the +MarketBillingService. You could put this code in your service's {@link +android.app.Activity#onCreate onCreate()} method.

      + +
      +try {
      +  boolean bindResult = mContext.bindService(
      +    new Intent("com.android.vending.billing.MarketBillingService.BIND"), this,
      +    Context.BIND_AUTO_CREATE);
      +  if (bindResult) {
      +    Log.i(TAG, "Service bind successful.");
      +  } else {
      +    Log.e(TAG, "Could not bind to the MarketBillingService.");
      +  }
      +} catch (SecurityException e) {
      +  Log.e(TAG, "Security exception: " + e);
      +}
      +
      + +

      After you bind to the service, you need to create a reference to the +IMarketBillingService interface so you can make billing requests via IPC method calls. +The following code shows you how to do this using the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method.

      + +
      +/**
      +  * The Android system calls this when we are connected to the MarketBillingService.
      +  */
      +  public void onServiceConnected(ComponentName name, IBinder service) {
      +    Log.i(TAG, "MarketBillingService connected.");
      +    mService = IMarketBillingService.Stub.asInterface(service);
      +  }
      +
      + +

      You can now use the mService reference to invoke the +sendBillingRequest() method.

      + +

      For a complete implementation of a service that binds to the MarketBillingService, +see the BillingService class in the sample application.

      + +

      Sending billing requests to the MarketBillingService

      + +

      Now that your {@link android.app.Service} has a reference to the +IMarketBillingService interface, you can use that reference to send billing requests +(via IPC method calls) to the MarketBillingService. The +MarketBillingService IPC interface exposes a single public method +(sendBillingRequest()), which takes a single {@link android.os.Bundle} parameter. The +Bundle that you deliver with this method specifies the type of request you want to perform, using +various key-value pairs. For instance, one key indicates the type of request you are making, another +indicates the item being purchased, and another identifies your application. The +sendBillingRequest() method immediately returns a Bundle containing an initial response +code. However, this is not the complete purchase response; the complete response is delivered with +an asynchronous broadcast intent. For more information about the various Bundle keys that are +supported by the MarketBillingService, see In-app Billing +Service Interface.

      + +

      You can use the sendBillingRequest() method to send five types of billing requests. +The five request types are specified using the BILLING_REQUEST Bundle key. This Bundle +key can have the following five values:

      + +
        +
      • CHECK_BILLING_SUPPORTED—verifies that the Google Play application + supports in-app billing and the version of the In-app Billing API available.
      • +
      • REQUEST_PURCHASE—sends a purchase request for an in-app item.
      • +
      • GET_PURCHASE_INFORMATION—retrieves transaction information for a purchase + or refund.
      • +
      • CONFIRM_NOTIFICATIONS—acknowledges that you received the transaction + information for a purchase or refund.
      • +
      • RESTORE_TRANSACTIONS—retrieves a user's transaction history for managed + purchases.
      • +
      + +

      To make any of these billing requests, you first need to build an initial {@link +android.os.Bundle} that contains the three keys that are required for all requests: +BILLING_REQUEST, API_VERSION, and PACKAGE_NAME. The following +code sample shows you how to create a helper method named makeRequestBundle() that does +this.

      + +
      +protected Bundle makeRequestBundle(String method) {
      +  Bundle request = new Bundle();
      +  request.putString(BILLING_REQUEST, method);
      +  request.putInt(API_VERSION, 1);
      +  request.putString(PACKAGE_NAME, getPackageName());
      +  return request;
      +
      + +

      To use this helper method, you pass in a String that corresponds to one of the five +types of billing requests. The method returns a Bundle that has the three required keys defined. The +following sections show you how to use this helper method when you send a billing request.

      + +

      Important: You must make all in-app billing requests from your +application's main thread.

      + +

      Verifying that in-app billing is supported (CHECK_BILLING_SUPPPORTED)

      + +

      The following code sample shows how to verify whether the Google Play application supports +in-app billing and confirm what version of the API it supports. In the sample, mService +is an instance of the MarketBillingService interface.

      + +
      +/**
      +* Request type is CHECK_BILLING_SUPPORTED
      +*/
      +  Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
      +  Bundle response = mService.sendBillingRequest(request);
      +  // Do something with this response.
      +}
      +
      + +

      The makeRequestBundle() method constructs an initial Bundle, which contains the +three keys that are required for all requests: BILLING_REQUEST, +API_VERSION, and PACKAGE_NAME. If you are offering subscriptions in +your app, set the API_VERSION key to a value of "2", to confirm that In-app Billing v2 is +available. For an examnple, see +Subscriptions.

      + +

      The CHECK_BILLING_SUPPORTED request returns a synchronous {@link +android.os.Bundle} response, which contains only a single key: RESPONSE_CODE. The +RESPONSE_CODE key can have the following values:

      +
        +
      • RESULT_OK—the spedified version of in-app billing is supported.
      • +
      • RESULT_BILLING_UNAVAILABLE—in-app billing is not available because the API + version you specified is not recognized or the user is not eligible to make in-app purchases (for + example, the user resides in a country that prohibits in-app purchases).
      • +
      • RESULT_ERROR—there was an error connecting with the Google Play + application.
      • +
      • RESULT_DEVELOPER_ERROR—the application is trying to make an in-app billing + request but the application has not declared the com.android.vending.BILLING + permission in its manifest. Can also indicate that an application is not properly signed, or that + you sent a malformed request.
      • +
      + +

      The CHECK_BILLING_SUPPORTED request does not trigger any asynchronous responses +(broadcast intents).

      + +

      We recommend that you invoke the CHECK_BILLING_SUPPORTED request within a +RemoteException block. When your code throws a RemoteException it +indicates that the remote method call failed, which means that the Google Play application is out +of date and needs to be updated. In this case, you can provide users with an error message that +contains a link to the Updating Google Play +Help topic.

      + +

      The sample application demonstrates how you can handle this error condition (see +DIALOG_CANNOT_CONNECT_ID in Dungeons.java).

      + +

      Making a purchase request (REQUEST_PURCHASE)

      + +

      To make a purchase request you must do the following:

      + +
        +
      • Send the REQUEST_PURCHASE request.
      • +
      • Launch the {@link android.app.PendingIntent} that is returned from the Google Play + application.
      • +
      • Handle the broadcast intents that are sent by the Google Play application.
      • +
      + +
      Making the request
      + +

      You must specify four keys in the request {@link android.os.Bundle}. The following code sample +shows how to set these keys and make a purchase request for a single in-app item. In the sample, +mProductId is the Google Play product ID of an in-app item (which is listed in the +application's product +list), and mService is an instance of the MarketBillingService +interface.

      + +
      +/**
      +* Request type is REQUEST_PURCHASE
      +*/
      +  Bundle request = makeRequestBundle("REQUEST_PURCHASE");
      +  request.putString(ITEM_ID, mProductId);
      +  // Request is for a standard in-app product
      +  request.putString(ITEM_TYPE, "inapp");
      +  // Note that the developer payload is optional.
      +  if (mDeveloperPayload != null) {
      +    request.putString(DEVELOPER_PAYLOAD, mDeveloperPayload);
      +  }
      +  Bundle response = mService.sendBillingRequest(request);
      +  // Do something with this response.
      +
      +

      The makeRequestBundle() method constructs an initial Bundle, which contains the +three keys that are required for all requests: BILLING_REQUEST, +API_VERSION, and PACKAGE_NAME. The ITEM_ID key is then added +to the Bundle prior to invoking the sendBillingRequest() method.

      + +

      The request returns a synchronous {@link android.os.Bundle} response, which contains three keys: +RESPONSE_CODE, PURCHASE_INTENT, and REQUEST_ID. The +RESPONSE_CODE key provides you with the status of the request and the +REQUEST_ID key provides you with a unique request identifier for the request. The +PURCHASE_INTENT key provides you with a {@link android.app.PendingIntent}, which you +can use to launch the checkout UI.

      + +
      Using the pending intent
      + +

      How you use the pending intent depends on which version of Android a device is running. On +Android 1.6, you must use the pending intent to launch the checkout UI in its own separate task +instead of your application's activity stack. On Android 2.0 and higher, you can use the pending +intent to launch the checkout UI on your application's activity stack. The following code shows you +how to do this. You can find this code in the PurchaseObserver.java file in the sample +application.

      + +
      +void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) {
      +  if (mStartIntentSender != null) {
      +    // This is on Android 2.0 and beyond.  The in-app checkout page activity
      +    // will be on the activity stack of the application.
      +    try {
      +      // This implements the method call:
      +      // mActivity.startIntentSender(pendingIntent.getIntentSender(),
      +      //     intent, 0, 0, 0);
      +      mStartIntentSenderArgs[0] = pendingIntent.getIntentSender();
      +      mStartIntentSenderArgs[1] = intent;
      +      mStartIntentSenderArgs[2] = Integer.valueOf(0);
      +      mStartIntentSenderArgs[3] = Integer.valueOf(0);
      +      mStartIntentSenderArgs[4] = Integer.valueOf(0);
      +      mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs);
      +    } catch (Exception e) {
      +      Log.e(TAG, "error starting activity", e);
      +      }
      +  } else {
      +    // This is on Android 1.6. The in-app checkout page activity will be on its
      +    // own separate activity stack instead of on the activity stack of
      +    // the application.
      +    try {
      +      pendingIntent.send(mActivity, 0 /* code */, intent);
      +    } catch (CanceledException e) {
      +      Log.e(TAG, "error starting activity", e);
      +      }
      +  }
      +}
      +
      + +

      Important: You must launch the pending intent from an activity +context and not an application context. Also, you cannot use the singleTop launch mode to launch the +pending intent. If you do either of these, the Android system will not attach the pending intent to +your application process. Instead, it will bring Google Play to the foreground, disrupting your +application.

      + +
      Handling broadcast intents
      + +

      A REQUEST_PURCHASE request also triggers two asynchronous responses (broadcast +intents). First, the Google Play application sends a RESPONSE_CODE broadcast intent, +which provides error information about the request. If the request does not generate an +error, the RESPONSE_CODE broadcast intent returns RESULT_OK, which +indicates that the request was successfully sent. (To be clear, a RESULT_OK response +does not indicate that the requested purchase was successful; it indicates that the request was sent +successfully to Google Play.)

      + +

      Next, when the requested transaction changes state (for example, the purchase is successfully +charged to a credit card or the user cancels the purchase), the Google Play application sends an +IN_APP_NOTIFY broadcast intent. This message contains a notification ID, which you can +use to retrieve the transaction details for the REQUEST_PURCHASE request.

      + +

      Note: The Google Play application also sends +an IN_APP_NOTIFY for refunds. For more information, see Handling +IN_APP_NOTIFY messages.

      + +

      Because the purchase process is not instantaneous and can take several seconds (or more), you +must assume that a purchase request is pending from the time you receive a RESULT_OK +message until you receive an IN_APP_NOTIFY message for the transaction. While the +transaction is pending, the Google Play checkout UI displays an "Authorizing purchase..." +notification; however, this notification is dismissed after 60 seconds and you should not rely on +this notification as your primary means of conveying transaction status to users. Instead, we +recommend that you do the following:

      + +
        +
      • Add an {@link android.app.Activity} to your application that shows users the status of pending +and completed in-app purchases.
      • +
      • Use a status +bar notification to keep users informed about the progress of a purchase.
      • +
      + +

      To use these two UI elements, you could invoke a status bar notification with a ticker-text +message that says "Purchase pending" when your application receives a RESULT_OK +message. Then, when your application receives an IN_APP_NOTIFY message, you could +update the notification with a new message that says "Purchase succeeded" or "Purchase failed." When +a user touches the expanded status bar notification, you could launch the activity that shows the +status of pending and completed in-app purchases.

      + +

      If you use some other UI technique to inform users about the state of a pending transaction, +be sure that your pending status UI does not block your application. For example, you should avoid +using a hovering progress wheel to convey the status of a pending transaction because a pending +transaction could last a long time, particularly if a device loses network connectivity and cannot +receive transaction updates from Google Play.

      + +

      Important: If a user purchases a managed item, you must prevent +the user from purchasing the item again while the original transaction is pending. If a user +attempts to purchase a managed item twice, and the first transaction is still pending, Google +Play will display an error to the user; however, Google Play will not send an error to your +application notifying you that the second purchase request was canceled. This might cause your +application to get stuck in a pending state while it waits for an IN_APP_NOTIFY message +for the second purchase request.

      + +

      Retrieving transaction information for a purchase or refund (GET_PURCHASE_INFORMATION)

      + +

      You retrieve transaction information in response to an IN_APP_NOTIFY broadcast +intent. The IN_APP_NOTIFY message contains a notification ID, which you can use to +retrieve transaction information.

      + +

      To retrieve transaction information for a purchase or refund you must specify five keys in the +request {@link android.os.Bundle}. The following code sample shows how to set these keys and make +the request. In the sample, mService is an instance of the +MarketBillingService interface.

      + +
      +/**
      +* Request type is GET_PURCHASE_INFORMATION
      +*/
      +  Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION");
      +  request.putLong(REQUEST_NONCE, mNonce);
      +  request.putStringArray(NOTIFY_IDS, mNotifyIds);
      +  Bundle response = mService.sendBillingRequest(request);
      +  // Do something with this response.
      +}
      +
      +

      The makeRequestBundle() method constructs an initial Bundle, which contains the +three keys that are required for all requests: BILLING_REQUEST, +API_VERSION, and PACKAGE_NAME. The additional keys are then added to the +bundle prior to invoking the sendBillingRequest() method. The +REQUEST_NONCE key contains a cryptographically secure nonce (number used once) that you +must generate. The Google Play application returns this nonce with the +PURCHASE_STATE_CHANGED broadcast intent so you can verify the integrity of the +transaction information. The NOTIFY_IDS key contains an array of notification IDs, +which you received in the IN_APP_NOTIFY broadcast intent.

      + +

      The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: +RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides +you with the status of the request and the REQUEST_ID key provides you with a unique +request identifier for the request.

      + +

      A GET_PURCHASE_INFORMATION request also triggers two asynchronous responses +(broadcast intents). First, the Google Play application sends a RESPONSE_CODE +broadcast intent, which provides status and error information about the request. Next, if the +request was successful, the Google Play application sends a PURCHASE_STATE_CHANGED +broadcast intent. This message contains detailed transaction information. The transaction +information is contained in a signed JSON string (unencrypted). The message includes the signature +so you can verify the integrity of the signed string.

      + +

      Acknowledging transaction information (CONFIRM_NOTIFICATIONS)

      + +

      To acknowledge that you received transaction information you send a +CONFIRM_NOTIFICATIONS request. You must specify four keys in the request {@link +android.os.Bundle}. The following code sample shows how to set these keys and make the request. In +the sample, mService is an instance of the MarketBillingService +interface.

      + +
      +/**
      +* Request type is CONFIRM_NOTIFICATIONS
      +*/
      +  Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS");
      +  request.putStringArray(NOTIFY_IDS, mNotifyIds);
      +  Bundle response = mService.sendBillingRequest(request);
      +  // Do something with this response.
      +}
      +
      +

      The makeRequestBundle() method constructs an initial Bundle, which contains the +three keys that are required for all requests: BILLING_REQUEST, +API_VERSION, and PACKAGE_NAME. The additional NOTIFY_IDS key +is then added to the bundle prior to invoking the sendBillingRequest() method. The +NOTIFY_IDS key contains an array of notification IDs, which you received in an +IN_APP_NOTIFY broadcast intent and also used in a GET_PURCHASE_INFORMATION +request.

      + +

      The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: +RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides +you with the status of the request and the REQUEST_ID key provides you with a unique +request identifier for the request.

      + +

      A CONFIRM_NOTIFICATIONS request triggers a single asynchronous response—a +RESPONSE_CODE broadcast intent. This broadcast intent provides status and error +information about the request.

      + +

      You must send a confirmation when you receive transaction information from Google Play. If you +don't send a confirmation message, Google Play will continue sending +IN_APP_NOTIFY messages for the transactions you have not confirmed. Also, +your application must be able to handle IN_APP_NOTIFY messages that contain multiple +orders.

      + +

      In addition, as a best practice, you should not send a CONFIRM_NOTIFICATIONS request +for a purchased item until you have delivered the item to the user. This way, if your application +crashes or something else prevents your application from delivering the product, your application +will still receive an IN_APP_NOTIFY broadcast intent from Google Play indicating +that you need to deliver the product.

      + +

      Restoring transaction information (RESTORE_TRANSACTIONS)

      + +

      To restore a user's transaction information, you send a RESTORE_TRANSACTIONS +request. You must specify four keys in the request {@link android.os.Bundle}. The following code +sample shows how to set these keys and make the request. In the sample, mService is an +instance of the MarketBillingService interface.

      + +
      +/**
      +* Request type is RESTORE_TRANSACTIONS
      +*/
      +  Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS");
      +  request.putLong(REQUEST_NONCE, mNonce);
      +  Bundle response = mService.sendBillingRequest(request);
      +  // Do something with this response.
      +}
      +
      +

      The makeRequestBundle() method constructs an initial Bundle, which contains the +three keys that are required for all requests: BILLING_REQUEST, +API_VERSION, and PACKAGE_NAME. The additional REQUEST_NONCE +key is then added to the bundle prior to invoking the sendBillingRequest() method. The +REQUEST_NONCE key contains a cryptographically secure nonce (number used once) that you +must generate. The Google Play application returns this nonce with the transactions information +contained in the PURCHASE_STATE_CHANGED broadcast intent so you can verify the +integrity of the transaction information.

      + +

      The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: +RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides +you with the status of the request and the REQUEST_ID key provides you with a unique +request identifier for the request.

      + +

      A RESTORE_TRANSACTIONS request also triggers two asynchronous responses (broadcast +intents). First, the Google Play application sends a RESPONSE_CODE broadcast intent, +which provides status and error information about the request. Next, if the request was successful, +the Google Play application sends a PURCHASE_STATE_CHANGED broadcast intent. This +message contains the detailed transaction information. The transaction information is contained in a +signed JSON string (unencrypted). The message includes the signature so you can verify the integrity +of the signed string.

      + +

      Note: You should use the RESTORE_TRANSACTIONS +request type only when your application is installed for the first time on a device or when your +application has been removed from a device and reinstalled.

      + +

      Other service tasks

      + +

      You may also want your {@link android.app.Service} to receive intent messages from your {@link +android.content.BroadcastReceiver}. You can use these intent messages to convey the information that +was sent asynchronously from the Google Play application to your {@link +android.content.BroadcastReceiver}. To see an example of how you can send and receive these intent +messages, see the BillingReceiver.java and BillingService.java files in +the sample application. You can use these samples as a basis for your own implementation. However, +if you use any of the code from the sample application, be sure you follow the guidelines in Security and Design.

      + +

      Creating a BroadcastReceiver

      + +

      The Google Play application uses broadcast intents to send asynchronous billing responses to +your application. To receive these intent messages, you need to create a {@link +android.content.BroadcastReceiver} that can handle the following intents:

      + +
        +
      • com.android.vending.billing.RESPONSE_CODE +

        This broadcast intent contains a Google Play response code, and is sent after you make an + in-app billing request. For more information about the response codes that are sent with this + response, see Google Play Response + Codes for In-app Billing.

        +
      • +
      • com.android.vending.billing.IN_APP_NOTIFY +

        This response indicates that a purchase has changed state, which means a purchase succeeded, + was canceled, or was refunded. For more information about notification messages, see In-app Billing + Broadcast Intents

        +
      • +
      • com.android.vending.billing.PURCHASE_STATE_CHANGED +

        This broadcast intent contains detailed information about one or more transactions. For more + information about purchase state messages, see In-app Billing + Broadcast Intents

        +
      • +
      + +

      Each of these broadcast intents provide intent extras, which your {@link +android.content.BroadcastReceiver} must handle. The intent extras are listed in the following table +(see table 1).

      + +

      Table 1. Description of broadcast intent extras that are +sent in response to billing requests.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      IntentExtraDescription
      com.android.vending.billing.RESPONSE_CODErequest_idA long representing a request ID. A request ID identifies a specific billing + request and is returned by Google Play at the time a request is made.
      com.android.vending.billing.RESPONSE_CODEresponse_codeAn int representing the actual Google Play server response code.
      com.android.vending.billing.IN_APP_NOTIFYnotification_idA String representing the notification ID for a given purchase state change. + Google Play notifies you when there is a purchase state change and the notification includes a + unique notification ID. To get the details of the purchase state change, you send the notification + ID with the GET_PURCHASE_INFORMATION request.
      com.android.vending.billing.PURCHASE_STATE_CHANGEDinapp_signed_dataA String representing the signed JSON string. The JSON string contains + information about the billing transaction, such as order number, amount, and the item that was + purchased or refunded.
      com.android.vending.billing.PURCHASE_STATE_CHANGEDinapp_signatureA String representing the signature of the JSON string.
      + +

      The following code sample shows how to handle these broadcast intents and intent extras within a +{@link android.content.BroadcastReceiver}. The BroadcastReceiver in this case is named +BillingReceiver, just as it is in the sample application.

      + +
      +public class BillingReceiver extends BroadcastReceiver {
      +
      +  private static final String TAG = "BillingReceiver";
      +
      +  // Intent actions that we receive in the BillingReceiver from Google Play.
      +  // These are defined by Google Play and cannot be changed.
      +  // The sample application defines these in the Consts.java file.
      +  public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
      +  public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE";
      +  public static final String ACTION_PURCHASE_STATE_CHANGED =
      +    "com.android.vending.billing.PURCHASE_STATE_CHANGED";
      +
      +  // The intent extras that are passed in an intent from Google Play.
      +  // These are defined by Google Play and cannot be changed.
      +  // The sample application defines these in the Consts.java file.
      +  public static final String NOTIFICATION_ID = "notification_id";
      +  public static final String INAPP_SIGNED_DATA = "inapp_signed_data";
      +  public static final String INAPP_SIGNATURE = "inapp_signature";
      +  public static final String INAPP_REQUEST_ID = "request_id";
      +  public static final String INAPP_RESPONSE_CODE = "response_code";
      +
      +
      +  @Override
      +  public void onReceive(Context context, Intent intent) {
      +    String action = intent.getAction();
      +    if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
      +      String signedData = intent.getStringExtra(INAPP_SIGNED_DATA);
      +      String signature = intent.getStringExtra(INAPP_SIGNATURE);
      +      // Do something with the signedData and the signature.
      +    } else if (ACTION_NOTIFY.equals(action)) {
      +      String notifyId = intent.getStringExtra(NOTIFICATION_ID);
      +      // Do something with the notifyId.
      +    } else if (ACTION_RESPONSE_CODE.equals(action)) {
      +      long requestId = intent.getLongExtra(INAPP_REQUEST_ID, -1);
      +      int responseCodeIndex = intent.getIntExtra(INAPP_RESPONSE_CODE,
      +        ResponseCode.RESULT_ERROR.ordinal());
      +      // Do something with the requestId and the responseCodeIndex.
      +    } else {
      +      Log.w(TAG, "unexpected action: " + action);
      +    }
      +  }
      +  // Perform other processing here, such as forwarding intent messages to your local service.
      +}
      +
      + +

      In addition to receiving broadcast intents from the Google Play application, your {@link +android.content.BroadcastReceiver} must handle the information it received in the broadcast intents. +Usually, your {@link android.content.BroadcastReceiver} does this by sending the information to a +local service (discussed in the next section). The BillingReceiver.java file in the +sample application shows you how to do this. You can use this sample as a basis for your own {@link +android.content.BroadcastReceiver}. However, if you use any of the code from the sample application, +be sure you follow the guidelines that are discussed in Security and Design .

      + +

      Verifying Signatures and Nonces

      + +

      Google Play's in-app billing service uses two mechanisms to help verify the integrity of the +transaction information you receive from Google Play: nonces and signatures. A nonce (number used +once) is a cryptographically secure number that your application generates and sends with every +GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS request. The nonce is +returned with the PURCHASE_STATE_CHANGED broadcast intent, enabling you to verify that +any given PURCHASE_STATE_CHANGED response corresponds to an actual request that you +made. Every PURCHASE_STATE_CHANGED broadcast intent also includes a signed JSON string +and a signature, which you can use to verify the integrity of the response.

      + +

      Your application must provide a way to generate, manage, and verify nonces. The following sample +code shows some simple methods you can use to do this.

      + +
      +  private static final SecureRandom RANDOM = new SecureRandom();
      +  private static HashSet<Long> sKnownNonces = new HashSet<Long>();
      +
      +  public static long generateNonce() {
      +    long nonce = RANDOM.nextLong();
      +    sKnownNonces.add(nonce);
      +    return nonce;
      +  }
      +
      +  public static void removeNonce(long nonce) {
      +    sKnownNonces.remove(nonce);
      +  }
      +
      +  public static boolean isNonceKnown(long nonce) {
      +    return sKnownNonces.contains(nonce);
      +  }
      +
      + +

      Your application must also provide a way to verify the signatures that accompany every +PURCHASE_STATE_CHANGED broadcast intent. The Security.java file in the +sample application shows you how to do this. If you use this file as a basis for your own security +implementation, be sure to follow the guidelines in Security and Design and +obfuscate your code.

      + +

      You will need to use your Google Play public key to perform the signature verification. The +following procedure shows you how to retrieve Base64-encoded public key from the Google Play +publisher site.

      + +
        +
      1. Log in to your publisher account.
      2. +
      3. On the upper left part of the page, under your name, click Edit profile.
      4. +
      5. On the Edit Profile page, scroll down to the Licensing & In-app Billing panel (see figure + 2).
      6. +
      7. Copy your public key.
      8. +
      + +

      Important: To keep your public key safe from malicious users and +hackers, do not embed your public key as an entire literal string. Instead, construct the string at +runtime from pieces or use bit manipulation (for example, XOR with some other string) to hide the +actual key. The key itself is not secret information, but you do not want to make it easy for a +hacker or malicious user to replace the public key with another key.

      + + +

      + Figure 2. The Licensing and In-app Billing panel of your account's Edit Profile + page lets you see your public key. +

      + +

      Modifying Your Application Code

      + +

      After you finish adding in-app billing components to your project, you are ready to modify your +application's code. For a typical implementation, like the one that is demonstrated in the sample +application, this means you need to write code to do the following:

      + +
        +
      • Create a storage mechanism for storing users' purchase information.
      • +
      • Create a user interface that lets users select items for purchase.
      • +
      + +

      The sample code in Dungeons.java shows you how to do both of these tasks.

      + +

      Creating a storage mechanism for storing purchase information

      + +

      You must set up a database or some other mechanism for storing users' purchase information. The +sample application provides an example database (PurchaseDatabase.java); however, the example +database has been simplified for clarity and does not exhibit the security best practices that we +recommend. If you have a remote server, we recommend that you store purchase information on your +server instead of in a local database on a device. For more information about security best +practices, see Security and +Design.

      + +

      Note: If you store any purchase information on a device, be sure to +encrypt the data and use a device-specific encryption key. Also, if the purchase type for any of +your items is "unmanaged," we recommend that you back up the purchase information for these items to +a remote server or use Android's data +backup framework to back up the purchase information. Backing up purchase information for +unmanaged items is important because unmanaged items cannot be restored by using the +RESTORE_TRANSACTIONS request type.

      + +

      Creating a user interface for selecting items

      + +

      You must provide users with a means for selecting items that they want to purchase. Google +Play provides the checkout user interface (which is where the user provides a form of payment and +approves the purchase), but your application must provide a control (widget) that invokes the +sendBillingRequest() method when a user selects an item for purchase.

      + +

      You can render the control and trigger the sendBillingRequest() method any way you +want. The sample application uses a spinner widget and a button to present items to a user and +trigger a billing request (see Dungeons.java). The user interface also shows a list of +recently purchased items.

      + diff --git a/docs/html/guide/google/play/billing/billing_overview.jd b/docs/html/guide/google/play/billing/billing_overview.jd new file mode 100755 index 000000000000..280b3cf3143e --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_overview.jd @@ -0,0 +1,507 @@ +page.title=In-app Billing Overview +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

      In-app Billing is a Google Play service that provides checkout processing for +in-app purchases. To use the service, your application sends a billing request for a specific in-app +product. The service then handles all of the checkout details for the transaction, including +requesting and validating the form of payment and processing the financial transaction. When the +checkout process is complete, the service sends your application the purchase details, such as the +order number, the order date and time, and the price paid. At no point does your application have to +handle any financial transactions; that role is provided by Google Play's in-app billing +service.

      + +

      Product and Purchase Types

      + +

      In-app Billing supports different product types and purchase types to give you flexibility in how you monetize your app. In all cases, you define your products using the Google Play Developer Console, including product type, purchase type, SKU, price, description, and so on. For more information, see Administering In-app Billing.

      + +

      Product Types

      + +

      With In-app Billing, you can sell two types of products — in-app products and subscriptions. The billing characteristics of the two types are very different, but the In-app Billing API lets you handle the two product types in your app using the same communication model, data structures, and user interactions, as described later in this document.

      + +
        +
      • In-app products — Items that a user would purchase one-at-a-time. For example, typical in-app products would let users purchase digital content, unlock functionality in an app, pay for one-time charges, or add almost anything to the application experience. Unlike with priced applications, once the user has purchased an in-app product there is no refund window. Users desiring refunds must contact the developer directly. + +

        In-app products can be sold using either the "managed per user account" or "unmanaged" purchase type. In-app products are always explicitly associated with one and only one app. That is, one app cannot purchase an in-app product published for another app, even if they are from the same developer. In-app products are supported in all versions of In-app Billing.

      • + +
      • Subscriptions — Items that are sold with a developer-specified, recurring billing interval. When a user purchases a subscription, Google Play and its payment processor automatically bill the user's account at the specified interval and price, charging the amount to the original payment method. Once the user purchases a subscription, Google Play continues billing the account indefinitely, without requiring approval or action from the user. The user can cancel the subscription at any time. + +

        Subscriptions can only be sold using the "managed per user account" purchase type. As with in-app products, once the user has purchased an in-app product there is no refund window. Users desiring refunds must contact the developer directly. For more information about subscriptions and how to sell them in your apps, see the Subscriptions document.

      • +
      + +

      Purchase Types

      + +

      In-app Billing offers two purchase types that you can use when selling in-app products, "managed per user account" and "unmanaged". The purchase type controls how Google Play handles and tracks purchases for the products.

      + +
        +
      • Managed per user account — Items that can be purchased only once per user account on Google Play. When a user purchases an item that uses the "managed per user account" purchase type, Google Play permanently stores the transaction information for each item on a per-user basis. This enables you to later query Google Play to restore the state of the items a specific user has purchased. If a user attempts to purchase a managed item that has already been purchased, Google Play prevents the user from purchasing the item again and displays an "Item already purchased" error. + +

        The "managed per user account" purchase type is useful if you are selling items such as game levels or application features. These items are not transient and usually need to be restored whenever a user reinstalls your application, wipes the data on their device, or installs your application on a new device.

        + +
      • Unmanaged — Items that do not have their transaction information stored on Google Play. This means that you cannot later query Google Play to retrieve transaction information for those items. For "unmanaged" purchases, you are responsible for managing the transaction information. Also, Google Play does not attempt to prevent the user from purchasing an item multiple times if it uses the "unmanaged" purchase type. It's up to you to control how many times an unmanaged item can be purchased.

        + +

        The "unmanaged" purchase type is useful if you are selling consumable items, such as fuel or magic spells. These items are consumed within your application and are usually purchased multiple times.

      • +
      + +

      In-app Billing Architecture

      + +

      Your app accesses the In-app Billing service using an API that is exposed by +the Google Play app installed on the device. The Google Play app then uses an +asynchronous message loop to convey billing requests and responses between your +application and the Google Play server. In practice, your application never +directly communicates with the Google Play server (see figure 1). Instead, your +application sends billing requests to the Google Play application over +interprocess communication (IPC) and receives purchase responses from the Google +Play application in the form of asynchronous broadcast intents. Your application +does not manage any network connections between itself and the Google Play +server or use any special APIs from the Android platform.

      + +
      + +

      + Figure 1. Your application sends and receives billing messages through the + Google Play application, which handles all communication with the Google Play server.

      +
      + +

      Some in-app billing implementations may also use a private remote server to deliver content or +validate transactions, but a remote server is not required to implement in-app billing. A remote +server can be useful if you are selling digital content that needs to be delivered to a user's +device, such as media files or photos. You might also use a remote server to store users' +transaction history or perform various in-app billing security tasks, such as signature +verification. Although you can handle all security-related tasks in your application, performing +those tasks on a remote server is recommended because it helps make your application less vulnerable +to security attacks.

      + +

      A typical in-app billing implementation relies on three components:

      +
        +
      • A {@link android.app.Service} (named BillingService in the sample application), + which processes purchase messages from the application and sends billing requests to the Google + Play in-app billing service.
      • +
      • A {@link android.content.BroadcastReceiver} (named BillingReceiver in the sample + application), which receives all asynchronous billing responses from the Google Play + application.
      • +
      • A security component (named Security in the sample application), which performs + security-related tasks, such as signature verification and nonce generation. For more information + about in-app billing security, see Security controls later in this + document.
      • +
      + +

      You may also want to incorporate two other components to support in-app billing:

      +
        +
      • A response {@link android.os.Handler} (named ResponseHandler in the sample + application), which provides application-specific processing of purchase notifications, errors, + and other status messages.
      • +
      • An observer (named PurchaseObserver in the sample application), which is + responsible for sending callbacks to your application so you can update your user interface with + purchase information and status.
      • +
      + +

      In addition to these components, your application must provide a way to store information about +users' purchases and some sort of user interface that lets users select items to purchase. You do +not need to provide a checkout user interface. When a user initiates an in-app purchase, the Google +Play application presents the checkout user interface to your user. When the user completes the +checkout process, your application resumes.

      + +

      In-app Billing Messages

      + +

      When the user initiates a purchase, your application sends billing messages to Google Play's +in-app billing service (named MarketBillingService) using simple IPC method calls. The +Google Play application responds to all billing requests synchronously, providing your +application with status notifications and other information. The Google Play application also +responds to some billing requests asynchronously, providing your application with error messages and +detailed transaction information. The following section describes the basic request-response +messaging that takes place between your application and the Google Play application.

      + +

      In-app billing requests

      + +

      Your application sends in-app billing requests by invoking a single IPC method +(sendBillingRequest()), which is exposed by the MarketBillingService +interface. This interface is defined in an Android Interface Definition Language file +(IMarketBillingService.aidl). You can download this AIDL +file with the in-app billing sample application.

      + +

      The sendBillingRequest() method has a single {@link android.os.Bundle} parameter. +The Bundle that you deliver must include several key-value pairs that specify various parameters for +the request, such as the type of billing request you are making, the item that is being purchased and +its type, and the application that is making the request. For more information about the Bundle keys +that are sent with a request, see In-app Billing +Service Interface. + +

      One of the most important keys that every request Bundle must have is the +BILLING_REQUEST key. This key lets you specify the type of billing request you are +making. Google Play's in-app billing service supports the following five types of billing +requests:

      + +
        +
      • CHECK_BILLING_SUPPORTED +

        This request verifies that the Google Play application supports in-app billing. You + usually send this request when your application first starts up. This request is useful if you + want to enable or disable certain UI features that are relevant only to in-app billing.

        +
      • +
      • REQUEST_PURCHASE +

        This request sends a purchase message to the Google Play application and is the foundation + of in-app billing. You send this request when a user indicates that he or she wants to purchase + an item in your application. Google Play then handles the financial transaction by displaying + the checkout user interface.

        +
      • +
      • GET_PURCHASE_INFORMATION +

        This request retrieves the details of a purchase state change. A purchase changes state when + a requested purchase is billed successfully or when a user cancels a transaction during + checkout. It can also occur when a previous purchase is refunded. Google Play notifies your + application when a purchase changes state, so you only need to send this request when there is + transaction information to retrieve.

        +
      • +
      • CONFIRM_NOTIFICATIONS +

        This request acknowledges that your application received the details of a purchase state + change. Google Play sends purchase state change notifications to your application until you + confirm that you received them.

        +
      • +
      • RESTORE_TRANSACTIONS +

        This request retrieves a user's transaction status for managed + purchases and subscriptions. + You should send this request only when you need to retrieve a user's transaction + status, which is usually only when your application is reinstalled or installed for the first + time on a device.

        +
      • +
      + +

      In-app Billing Responses

      + +

      The Google Play application responds to in-app billing requests with both synchronous and +asynchronous responses. The synchronous response is a {@link android.os.Bundle} with the following +three keys:

      + +
        +
      • RESPONSE_CODE +

        This key provides status information and error information about a request.

        +
      • +
      • PURCHASE_INTENT +

        This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout + activity.

        +
      • +
      • REQUEST_ID +

        This key provides you with a request identifier, which you can use to match asynchronous + responses with requests.

        +
      • +
      +

      Some of these keys are not relevant to every request. For more information, see Messaging sequence later in this document.

      + +

      The asynchronous response messages are sent in the form of individual broadcast intents and +include the following:

      + +
        +
      • com.android.vending.billing.RESPONSE_CODE +

        This response contains a Google Play server response code, and is sent after you make an + in-app billing request. A server response code can indicate that a billing request was + successfully sent to Google Play or it can indicate that some error occurred during a billing + request. This response is not used to report any purchase state changes (such as refund + or purchase information). For more information about the response codes that are sent with this + response, see Server Response Codes + for In-app Billing.

        +
      • +
      • com.android.vending.billing.IN_APP_NOTIFY +

        This response indicates that a purchase has changed state, which means a purchase succeeded, + was canceled, or was refunded. This response contains one or more notification IDs. Each + notification ID corresponds to a specific server-side message, and each messages contains + information about one or more transactions. After your application receives an + IN_APP_NOTIFY broadcast intent, you send a GET_PURCHASE_INFORMATION + request with the notification IDs to retrieve message details.

        +
      • +
      • com.android.vending.billing.PURCHASE_STATE_CHANGED +

        This response contains detailed information about one or more transactions. The transaction + information is contained in a JSON string. The JSON string is signed and the signature is sent + to your application along with the JSON string (unencrypted). To help ensure the security of + your in-app billing messages, your application can verify the signature of this JSON string.

        +
      • +
      + +

      The JSON string that is returned with the PURCHASE_STATE_CHANGED intent provides +your application with the details of one or more billing transactions. An example of this JSON +string for a subscription item is shown below:

      +
      { "nonce" : 1836535032137741465,
      +  "orders" :
      +    [{ "notificationId" : "android.test.purchased",
      +       "orderId" : "transactionId.android.test.purchased",
      +       "packageName" : "com.example.dungeons",
      +       "productId" : "android.test.purchased",
      +       "developerPayload" : "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
      +       "purchaseTime" : 1290114783411,
      +       "purchaseState" : 0,
      +       "purchaseToken" : "rojeslcdyyiapnqcynkjyyjh" }]
      +}
      +
      + +

      For more information about the fields in this JSON string, see In-app Billing +Broadcast Intents.

      + +

      Messaging sequence

      + +

      The messaging sequence for a typical purchase request is shown in figure 2. Request types for +each sendBillingRequest() method are shown in bold, broadcast intents +are shown in italic. For clarity, figure 2 does not show the RESPONSE_CODE +broadcast intents that are sent for every request.

      + +

      The basic message sequence for an in-app purchase request is as follows:

      + +
        +
      1. Your application sends a purchase request (REQUEST_PURCHASE type), specifying a + product ID and other parameters.
      2. +
      3. The Google Play application sends your application a Bundle with the following keys: + RESPONSE_CODE, PURCHASE_INTENT, and REQUEST_ID. The + PURCHASE_INTENT key provides a {@link android.app.PendingIntent}, which your + application uses to start the checkout UI for the given product ID.
      4. +
      5. Your application launches the pending intent, which launches the checkout UI. +

        Note: You must launch the pending intent from an activity + context and not an application context.

        +
      6. +
      7. When the checkout flow finishes (that is, the user successfully purchases the item or cancels + the purchase), Google Play sends your application a notification message (an + IN_APP_NOTIFY broadcast intent). The notification message includes a notification ID, + which references the transaction.
      8. +
      9. Your application requests the transaction information by sending a + GET_PURCHASE_STATE_CHANGED request, specifying the notification ID for the + transaction.
      10. +
      11. The Google Play application sends a Bundle with a RESPONSE_CODE key and a + REQUEST_ID key. +
      12. Google Play sends the transaction information to your application in a + PURCHASE_STATE_CHANGED broadcast intent.
      13. +
      14. Your application confirms that you received the transaction information for the given + notification ID by sending a confirmation message (CONFIRM_NOTIFICATIONS type), + specifying the notification ID for which you received transaction information.
      15. +
      16. The Google Play application sends your application a Bundle with a + RESPONSE_CODE key and a REQUEST_ID key.
      17. +
      + + +

      + Figure 2. Message sequence for a purchase request. +

      + +

      Keep in mind, you must send a confirmation when you receive transaction information from Google +Play (step 8 in figure 2). If you don't send a confirmation message, Google Play will +continue sending IN_APP_NOTIFY messages for the transactions you have not +confirmed. As a best practice, you should not send a CONFIRM_NOTIFICATIONS request for +a purchased item until you have delivered the item to the user. This way, if your application +crashes or something else prevents your application from delivering the product, your application +will still receive an IN_APP_NOTIFY broadcast intent from Google Play indicating +that you need to deliver the product. Also, as a best practice, your application must be able to +handle IN_APP_NOTIFY messages that contain multiple orders.

      + +

      The messaging sequence for a restore transaction request is shown in figure 3. Request types for +each sendBillingRequest() method are shown in bold, broadcast intents +are shown in italic. For clarity, figure 3 does not show the RESPONSE_CODE +broadcast intents that are sent for every request.

      + +
      + +

      + Figure 3. Message sequence for a restore transactions request. +

      +
      + +

      The request triggers three responses. The first is a {@link android.os.Bundle} with a +RESPONSE_CODE key and a REQUEST_ID key. Next, the Google Play +application sends a RESPONSE_CODE broadcast intent, which provides status information +or error information about the request. As always, the RESPONSE_CODE message references +a specific request ID, so you can determine which request a RESPONSE_CODE message +pertains to.

      + +

      The RESTORE_TRANSACTIONS request type also triggers a +PURCHASE_STATE_CHANGED broadcast intent, which contains the same type of transaction +information that is sent during a purchase request, although you do not need to respond to this +intent with a CONFIRM_NOTIFICATIONS message.

      + +

      Note: You should use the RESTORE_TRANSACTIONS request +type only when your application is installed for the first time on a device or when your +application has been removed from a device and reinstalled.

      + +

      The messaging sequence for checking whether in-app billing is supported is shown in figure 4. The +request type for the sendBillingRequest() method is shown in bold.

      + +
      + +

      + Figure 4. Message sequence for checking whether in-app billing is supported. +

      +
      + +

      The synchronous response for a CHECK_BILLING_SUPPORTED request provides a Bundle +with a server response code. A RESULT_OK response code indicates that in-app billing +is supported; a RESULT_BILLING_UNAVAILABLE response code indicates that in-app billing +is unavailable because the API version you specified is unrecognized or the user is not eligible to +make in-app purchases (for example, the user resides in a country that does not allow in-app +billing). A SERVER_ERROR can also be returned, indicating that there was a problem with +the Google Play server.

      + +

      Handling IN_APP_NOTIFY messages

      + +

      Usually, your application receives an IN_APP_NOTIFY broadcast intent from Google +Play in response to a REQUEST_PURCHASE message (see figure 2). The +IN_APP_NOTIFY broadcast intent informs your application that the state of a requested +purchase has changed. To retrieve the details of that purchase, your application sends a +GET_PURCHASE_INFORMATION request. Google Play responds with a +PURCHASE_STATE_CHANGED broadcast intent, which contains the details of the purchase +state change. Your application then sends a CONFIRM_NOTIFICATIONS message, informing +Google Play that you have received the purchase state change information.

      + +

      In some special cases, you may receive multiple IN_APP_NOTIFY messages even though +you have confirmed receipt of the purchase information, or you may receive +IN_APP_NOTIFY messages for a purchase change even though you never initiated the +purchase. Your application must handle both of these special cases.

      + +

      Handling multiple IN_APP_NOTIFY messages

      + +

      When Google Play receives a CONFIRM_NOTIFICATIONS message for a given +PURCHASE_STATE_CHANGED message, it usually stops sending IN_APP_NOTIFY +intents for that PURCHASE_STATE_CHANGED message. Sometimes, however, Google +Play may send repeated IN_APP_NOTIFY intents for a +PURCHASE_STATE_CHANGED message even though your application has sent a +CONFIRM_NOTIFICATIONS message. This can occur if a device loses network connectivity +while you are sending the CONFIRM_NOTIFICATIONS message. In this case, Google Play +might not receive your CONFIRM_NOTIFICATIONS message and it could send multiple +IN_APP_NOTIFY messages until it receives acknowledgement that you received the +transaction message. Therefore, your application must be able to recognize that the subsequent +IN_APP_NOTIFY messages are for a previously processed transaction. You can do this by +checking the orderID that's contained in the JSON string because every transaction has +a unique orderId.

      + +

      Handling refunds and other unsolicited IN_APP_NOTIFY messages

      + +

      There are two cases where your application may receive IN_APP_NOTIFY broadcast +intents even though your application has not sent a REQUEST_PURCHASE message. Figure 5 +shows the messaging sequence for both of these cases. Request types for each +sendBillingRequest() method are shown in bold, broadcast intents are +shown in italic. For clarity, figure 5 does not show the RESPONSE_CODE +broadcast intents that are sent for every request.

      + +
      + +

      + Figure 5. Message sequence for refunds and other unsolicited +IN_APP_NOTIFY messages.

      +
      + +

      In the first case, your application may receive an IN_APP_NOTIFY broadcast intent +when a user has your application installed on two (or more) devices and the user makes an in-app +purchase from one of the devices. In this case, Google Play sends an IN_APP_NOTIFY +message to the second device, informing the application that there is a purchase state change. Your +application can handle this message the same way it handles the response from an +application-initiated REQUEST_PURCHASE message, so that ultimately your application +receives a PURCHASE_STATE_CHANGED broadcast intent message that includes information +about the item that has been purchased. This applies only to items that have their purchase type set +to "managed per user account."

      + +

      In the second case, your application can receive an IN_APP_NOTIFY broadcast intent +when Google Play receives a refund notification from Google Wallet. In this case, Google +Play sends an IN_APP_NOTIFY message to your application. Your application can handle +this message the same way it handles responses from an application-initiated +REQUEST_PURCHASE message so that ultimately your application receives a +PURCHASE_STATE_CHANGED message that includes information about the item that has been +refunded. The refund information is included in the JSON string that accompanies the +PURCHASE_STATE_CHANGED broadcast intent. Also, the purchaseState field in +the JSON string is set to 2.

      + +

      Important: You cannot use the Google Wallet API to +issue refunds or cancel in-app billing transactions. You must do this manually through your +Google Wallet merchant account. However, you can use the Google Wallet API to retrieve order +information.

      + +

      Security Controls

      + +

      To help ensure the integrity of the transaction information that is sent to your application, +Google Play signs the JSON string that is contained in the PURCHASE_STATE_CHANGED +broadcast intent. Google Play uses the private key that is associated with your publisher account +to create this signature. The publisher site generates an RSA key pair for each publisher account. +You can find the public key portion of this key pair on your account's profile page. It is the same +public key that is used with Google Play licensing.

      + +

      When Google Play signs a billing response, it includes the signed JSON string (unencrypted) +and the signature. When your application receives this signed response you can use the public key +portion of your RSA key pair to verify the signature. By performing signature verification you can +help detect responses that have been tampered with or that have been spoofed. You can perform this +signature verification step in your application; however, if your application connects to a secure +remote server then we recommend that you perform the signature verification on that server.

      + +

      In-app billing also uses nonces (a random number used once) to help verify the integrity of the +purchase information that's returned from Google Play. Your application must generate a nonce and +send it with a GET_PURCHASE_INFORMATION request and a RESTORE_TRANSACTIONS +request. When Google Play receives the request, it adds the nonce to the JSON string that +contains the transaction information. The JSON string is then signed and returned to your +application. When your application receives the JSON string, you need to verify the nonce as well as +the signature of the JSON string.

      + +

      For more information about best practices for security and design, see Security and Design.

      + +

      In-app Billing Requirements and Limitations

      + +

      Before you get started with in-app billing, be sure to review the following requirements and +limitations.

      + +
        +
      • In-app billing can be implemented only in applications that you publish through Google + Play.
      • +
      • You must have a Google Wallet Merchant account to use Google Play In-app Billing.
      • +
      • In-app billing requires version 2.3.4 (or higher) of the Android Market application. + To support subscriptions, version 3.5 or higher of the Google Play app is required. On devices + running Android 3.0, version 5.0.12 (or higher) of the MyApps application is required.
      • +
      • An application can use in-app billing only if the device is running Android 1.6 (API level 4) + or higher.
      • +
      • You can use in-app billing to sell only digital content. You cannot use in-app billing to sell + physical goods, personal services, or anything that requires physical delivery.
      • +
      • Google Play does not provide any form of content delivery. You are responsible for + delivering the digital content that you sell in your applications.
      • +
      • You cannot implement in-app billing on a device that never connects to the network. To + complete in-app purchase requests, a device must be able to access the Google Play server over + the network.
      • +
      + +

      For more information about in-app billing requirements, see In-App +Billing Availability and Policies.

      diff --git a/docs/html/guide/google/play/billing/billing_reference.jd b/docs/html/guide/google/play/billing/billing_reference.jd new file mode 100755 index 000000000000..f8c69678bb50 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_reference.jd @@ -0,0 +1,491 @@ +page.title=In-app Billing Reference +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

      The following document provides technical reference information for the following:

      + + + +

      Server Response Codes for In-app Billing

      + +

      The following table lists all of the server response codes that are sent from Google Play to +your application. Google Play sends these response codes asynchronously as +response_code extras in the com.android.vending.billing.RESPONSE_CODE +broadcast intent. Your application must handle all of these response codes.

      + +

      Table 1. Summary of response +codes returned by Google Play.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Response CodeValueDescription
      RESULT_OK0Indicates that the request was sent to the server successfully. When this code is returned in + response to a CHECK_BILLING_SUPPORTED request, indicates that billing is + supported.
      RESULT_USER_CANCELED1Indicates that the user pressed the back button on the checkout page instead of buying the + item.
      RESULT_SERVICE_UNAVAILABLE2Indicates that the network connection is down.
      RESULT_BILLING_UNAVAILABLE3Indicates that in-app billing is not available because the API_VERSION that you + specified is not recognized by the Google Play application or the user is ineligible for in-app + billing (for example, the user resides in a country that prohibits in-app purchases).
      RESULT_ITEM_UNAVAILABLE4Indicates that Google Play cannot find the requested item in the application's product + list. This can happen if the product ID is misspelled in your REQUEST_PURCHASE + request or if an item is unpublished in the application's product list.
      RESULT_DEVELOPER_ERROR5Indicates that an application is trying to make an in-app billing request but the application + has not declared the com.android.vending.BILLING permission in its manifest. Can also indicate + that an application is not properly signed, or that you sent a malformed request, such as a + request with missing Bundle keys or a request that uses an unrecognized request type.
      RESULT_ERROR6Indicates an unexpected server error. For example, this error is triggered if you try to +purchase an item from yourself, which is not allowed by Google Wallet.
      + +

      In-app Billing Service Interface

      + +

      The following section describes the interface for Google Play's in-app billing service. The +interface is defined in the IMarketBillingService.aidl file, which is included with the +in-app billing sample +application.

      +

      The interface consists of a single request method sendBillingRequest(). This method +takes a single {@link android.os.Bundle} parameter. The Bundle parameter includes several key-value +pairs, which are summarized in table 2.

      + +

      Table 2. Description of Bundle keys passed in a +sendBillingRequest() request.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      KeyTypePossible ValuesRequired?Description
      BILLING_REQUESTStringCHECK_BILLING_SUPPORTED, REQUEST_PURCHASE, + GET_PURCHASE_INFORMATION, CONFIRM_NOTIFICATIONS, or + RESTORE_TRANSACTIONSYesThe type of billing request you are making with the sendBillingRequest() request. + The possible values are discussed more below this table.
      API_VERSIONint YesThe version of Google Play's in-app billing service you want to use. The current version is + 2.
      PACKAGE_NAMEStringA valid package name.YesThe name of the application that is making the request.
      ITEM_IDStringAny valid product identifier.Required for REQUEST_PURCHASE requests.The product ID of the item you are making a billing request for. Every in-app item that you + sell using Google Play's in-app billing service must have a unique product ID, which you + specify on the Google Play publisher site.
      NONCElongAny valid long value.Required for GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS + requests.A number used once. Your application must generate and send a nonce with each + GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS request. The nonce is + returned with the PURCHASE_STATE_CHANGED broadcast intent, so you can use this value + to verify the integrity of transaction responses form Google Play.
      NOTIFY_IDSArray of long valuesAny valid array of long valuesRequired for GET_PURCHASE_INFORMATION and CONFIRM_NOTIFICATIONS + requests.An array of notification identifiers. A notification ID is sent to your application in an + IN_APP_NOTIFY broadcast intent every time a purchase changes state. You use the + notification to retrieve the details of the purchase state change.
      DEVELOPER_PAYLOADStringAny valid String less than 256 characters long.NoA developer-specified string that can be specified when you make a + REQUEST_PURCHASE request. This field is returned in the JSON string that contains + transaction information for an order. You can use this key to send supplemental information with + an order. For example, you can use this key to send index keys with an order, which is useful if + you are using a database to store purchase information. We recommend that you do not use this key + to send data or content.
      + +

      The BILLING_REQUEST key can have the following values:

      + +
        +
      • CHECK_BILLING_SUPPORTED +

        This request verifies that the Google Play application supports in-app billing. You + usually send this request when your application first starts up. This request is useful if you + want to enable or disable certain UI features that are relevant only to in-app billing.

        +
      • +
      • REQUEST_PURCHASE +

        This request sends a purchase message to the Google Play application and is the foundation + of in-app billing. You send this request when a user indicates that he or she wants to purchase + an item in your application. Google Play then handles the financial transaction by displaying + the checkout user interface.

        +
      • +
      • GET_PURCHASE_INFORMATION +

        This request retrieves the details of a purchase state change. A purchase state change can + occur when a purchase request is billed successfully or when a user cancels a transaction during + checkout. It can also occur when a previous purchase is refunded. Google Play notifies your + application when a purchase changes state, so you only need to send this request when there is + transaction information to retrieve.

        +
      • +
      • CONFIRM_NOTIFICATIONS +

        This request acknowledges that your application received the details of a purchase state + change. That is, this message confirms that you sent a GET_PURCHASE_INFORMATION + request for a given notification and that you received the purchase information for the + notification.

        +
      • +
      • RESTORE_TRANSACTIONS +

        This request retrieves a user's transaction status for managed purchases (see Choosing a + Purchase Type for more information). You should send this message only when you need to + retrieve a user's transaction status, which is usually only when your application is reinstalled + or installed for the first time on a device.

        +
      • +
      + +

      Every in-app billing request generates a synchronous response. The response is a {@link +android.os.Bundle} and can include one or more of the following keys:

      + +
        +
      • RESPONSE_CODE +

        This key provides status information and error information about a request.

        +
      • +
      • PURCHASE_INTENT +

        This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout + activity.

        +
      • +
      • REQUEST_ID +

        This key provides you with a request identifier, which you can use to match asynchronous + responses with requests.

        +
      • +
      + +

      Some of these keys are not relevant to certain types of requests. Table 3 shows which keys are +returned for each request type.

      + +

      Table 3. Description of Bundle keys that are returned with +each in-app billing request type.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Request TypeKeys ReturnedPossible Response Codes
      CHECK_BILLING_SUPPORTEDRESPONSE_CODERESULT_OK, RESULT_BILLING_UNAVAILABLE, RESULT_ERROR, + RESULT_DEVELOPER_ERROR
      REQUEST_PURCHASERESPONSE_CODE, PURCHASE_INTENT, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
      GET_PURCHASE_INFORMATIONRESPONSE_CODE, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
      CONFIRM_NOTIFICATIONSRESPONSE_CODE, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
      RESTORE_TRANSACTIONSRESPONSE_CODE, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
      + +

      In-app Billing Broadcast Intents

      + +

      The following section describes the in-app billing broadcast intents that are sent by the Google +Play application. These broadcast intents inform your application about in-app billing actions +that have occurred. Your application must implement a {@link android.content.BroadcastReceiver} to +receive these broadcast intents, such as the BillingReceiver that's shown in the in-app +billing sample +application.

      + +

      com.android.vending.billing.RESPONSE_CODE

      + +

      This broadcast intent contains a Google Play response code, and is sent after you make an +in-app billing request. A server response code can indicate that a billing request was successfully +sent to Google Play or it can indicate that some error occurred during a billing request. This +intent is not used to report any purchase state changes (such as refund or purchase information). +For more information about the response codes that are sent with this response, see Google Play Response Codes for In-app Billing. The sample application +assigns this broadcast intent to a constant named ACTION_RESPONSE_CODE.

      + +
      Extras
      + +
        +
      • request_id—a long representing a request ID. A request ID + identifies a specific billing request and is returned by Google Play at the time a request is + made.
      • +
      • response_code—an int representing the Google Play server + response code.
      • +
      + +

      com.android.vending.billing.IN_APP_NOTIFY

      + +

      This response indicates that a purchase has changed state, which means a purchase succeeded, was +canceled, or was refunded. This response contains one or more notification IDs. Each notification ID +corresponds to a specific server-side message, and each messages contains information about one or +more transactions. After your application receives an IN_APP_NOTIFY broadcast intent, +you send a GET_PURCHASE_INFORMATION request with the notification IDs to retrieve the +message details. The sample application assigns this broadcast intent to a constant named +ACTION_NOTIFY.

      + +
      Extras
      + +
        +
      • notification_id—a String representing the notification ID for + a given purchase state change. Google Play notifies you when there is a purchase state change + and the notification includes a unique notification ID. To get the details of the purchase state + change, you send the notification ID with the GET_PURCHASE_INFORMATION request.
      • +
      + +

      com.android.vending.billing.PURCHASE_STATE_CHANGED

      + +

      This broadcast intent contains detailed information about one or more transactions. The +transaction information is contained in a JSON string. The JSON string is signed and the signature +is sent to your application along with the JSON string (unencrypted). To help ensure the security of +your in-app billing messages, your application can verify the signature of this JSON string. The +sample application assigns this broadcast intent to a constant named +ACTION_PURCHASE_STATE_CHANGED.

      + +
      Extras
      + +
        +
      • inapp_signed_data—a String representing the signed JSON + string.
      • +
      • inapp_signature—a String representing the signature.
      • +
      + +

      Note: Your application should map the broadcast intents and extras +to constants that are unique to your application. See the Consts.java file in the +sample application to see how this is done.

      + +

      The fields in the JSON string are described in the following table (see table 4):

      + +

      Table 4. Description of JSON fields that are returned with +a PURCHASE_STATE_CHANGED intent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldDescription
      nonceA number used once. Your application generates the nonce and sends it with the + GET_PURCHASE_INFORMATION request. Google Play sends the nonce back as part of the + JSON string so you can verify the integrity of the message.
      notificationIdA unique identifier that is sent with an IN_APP_NOTIFY broadcast intent. Each + notificationId corresponds to a specify message that is waiting to be retrieved on + the Google Play server. Your application sends back the notificationId with the + GET_PURCHASE_INFORMATION message so Google Play can determine which messages you + are retrieving.
      orderIdA unique order identifier for the transaction. This corresponds to the Google Wallet Order + ID.
      packageNameThe application package from which the purchase originated.
      productIdThe item's product identifier. Every item has a product ID, which you must specify in the + application's product list on the Google Play publisher site.
      purchaseTimeThe time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).
      purchaseStateThe purchase state of the order. Possible values are 0 (purchased), 1 (canceled), 2 + (refunded), or 3 (expired, for subscription purchases only).
      purchaseTokenA token that uniquely identifies a subscription purchase for a given item and user pair. + You can use the token to specify the subscription when querying for subscription validity. + +


      Supported only in In-app Billing API version 2 and higher.

      developerPayloadA developer-specified string that contains supplemental information about an order. You can + specify a value for this field when you make a REQUEST_PURCHASE request.
      + + + +

      HTTP API for verification and cancelation

      + +

      Google Play offers an HTTP-based API that you can use to remotely query the +validity of a specific subscription at any time or cancel a subscription. The +API is designed to be used from your backend servers as a way of securely +managing subscriptions, as well as extending and integrating subscriptions with +other services. See +Google Play Android Developer API for more information.

      + +

      In-app Billing API Versions

      + +

      The In-app Billing API is versioned, with each version offering +additional features to your app. At run time, your app can query the Google Play app to determine +what version of the API it supports and what features are available. Typically, the Google Play app +will be updated and will support the latest version of the API. For a summary of versions see +In-app Billing +API Versions.

      + +

      The sections below list the supported versions of the In-app Billing API. +Versions are specified in the API_VERSION key of the Bundle object +passed in the sendBillingRequest(), which is defined in the defined +in the IMarketBillingService.aidl file, which is included with the +in-app billing +sample application. For more information, see In-app Billing Service Interface.

      +

      In-app Billing version 2

      + +

      May 2012

      + +
        +
      • Adds support for subscriptions. +
          +
        • Adds a new supported string value, "2", for the API_VERSION key + of the Bundle object passed in the sendBillingRequest().
        • +
        • Adds a new JSON field, purchaseToken, to the + orders list returned in a PURCHASE_STATE_CHANGED + intent.
        • +
        • Adds a new purchaseState value, 3 (expired), to the + orders list returned in a PURCHASE_STATE_CHANGED + intent. The value indicates that a subscription has expired and is no longer valid.
        • +
        • Requires Google Play (Play Store) version 3.5 or higher.
        • +
        + +

        In-app Billing version 1

        + +

        March 2011

        + +
          +
        • Initial release.
        • +
        • Requires Google Play/Android Market 2.3.4 or higher.
        • +
        + diff --git a/docs/html/guide/google/play/billing/billing_subscriptions.jd b/docs/html/guide/google/play/billing/billing_subscriptions.jd new file mode 100755 index 000000000000..3cf97777dea8 --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_subscriptions.jd @@ -0,0 +1,859 @@ +page.title=Subscriptions +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

        Subscriptions let you sell content, services, or features in your app with +automated, recurring billing. Adding support for subscriptions is +straightforward and you can easily adapt an existing In-app Billing +implementation to sell subscriptions.

        + +

        If you have already implemented In-app Billing for one-time purchase +products, you will find that you can add support for subscriptions with minimal +impact on your code. If you are new to In-app Billing, you can implement +subscriptions using the standard communication model, data structures, and user +interactions as for other in-app products.subscriptions. Because the +implementation of subscriptions follows the same path as for other in-app +products, details are provided outside of this document, starting with the In-app Billing +Overview.

        + +

        This document is focused on highlighting implementation details that are +specific to subscriptions, along with some strategies for the associated billing +and business models.

        + +

        Overview of Subscriptions

        + +

        A subscription is a new product type offered in In-app Billing that lets you +sell content, services, or features to users from inside your app with recurring +monthly or annual billing. You can sell subscriptions to almost any type of +digital content, from any type of app or game.

        + +

        As with other in-app products, you configure and publish subscriptions using +the Developer Console and then sell them from inside apps installed on an +Android-powered devices. In the Developer console, you create subscription +products and add them to a product list, setting a price for each, choosing a +billing interval of monthly or annually, and then publishing. In your apps, it’s +straightforward to add support for subscription purchases. The implementation +extends the standard In-app Billing API to support a new product type but uses +the same communication model, data structures, and user interactions as for +other in-app products.

        + +

        When users purchase subscriptions in your apps, Google Play handles all +checkout details so your apps never have to directly process any financial +transactions. Google Play processes all payments for subscriptions through +Google Wallet, just as it does for standard in-app products and app purchases. +This ensures a consistent and familiar purchase flow for your users.

        + + + + +

        After users have purchase subscriptions, they can view the subscriptions and +cancel them, if necessary, from the My Apps screen in the Play Store app or +from the app's product details page in the Play Store app.

        + + + +

        Once users have purchased a subscription through In-app Billing, you can +easily give them extended access to additional content on your web site (or +other service) through the use of a server-side API provided for In-app Billing. +The server-side API lets you validate the status of a subscription when users +sign into your other services. For more information about the API, see Google Play Android Developer API, below.

        + +

        You can also build on your existing external subscriber base from inside your +Android apps. If you sell subscriptions on a web site, for example, you can add +your own business logic to your Android app to determine whether the user has +already purchased a subscription elsewhere, then allow access to your content if +so or offer a subscription purchase from Google Play if not.

        + +

        With the flexibility of In-app Billing, you can even implement your own +solution for sharing subscriptions across as many different apps or products as +you want. For example, you could sell a subscription that gives a subscriber +access to an entire collection of apps, games, or other content for a monthly or +annual fee. To implement this solution, you could add your own business logic to +your app to determine whether the user has already purchased a given +subscription and if so, allow access to your content.

        + + + +

        In general the same basic policies and terms apply to subscriptions as to +standard in-app products, however there are some differences. For complete +information about the current policies and terms, please read the policies document.

        + + +

        Subscription publishing and unpublishing

        + +

        To sell a subscription in an app, you use the tools in the Developer Console +to set up a product list for the app and then create and configure a new +subscription. In the subscription, you set the price and billing interval and +define a subscription ID, title, and description. When you are ready, you can +then publish the subscription in the app product list.

        + +

        In the product list, you can add subscriptions, in-app products, or both. You +can add multiple subscriptions that give access to different content or +services, or you can add multiple subscriptions that give access to the same +content but for different intervals or different prices, such as for a +promotion. For example, a news outlet might decide to offer both monthly and +annual subscriptions to the same content, with annual having a discount. You can +also offer in-app purchase equivalents for subscription products, to ensure that +your content is available to users of older devices that do not support +subscriptions.

        + +

        After you add a subscription or in-app product to the product list, you must +publish the product before Google Play can make it available for purchase. Note +that you must also publish the app itself before Google Play will make the +products available for purchase inside the app.

        + +

        Important: At this time, the capability to +unpublish a subscription is not available. Support for unpublishing a +subscription is coming to the Developer Console in the weeks ahead, so this is a +temporary limitation. In the short term, instead of unpublishing, +you can remove the subscription product from the product list offered in your +app to prevent users from seeing or purchasing it.

        + +

        Subscription pricing

        + +

        When you create a subscription in the Developer Console, you can set a price +for it in any available currencies. Each subscription must have a non-zero +price. You can price multiple subscriptions for the same content differently +— for example you could offer a discount on an annual subscription +relative to the monthly equivalent.

        + +

        Important: At this time, once you publish a +subscription product, you cannot change its price in any currency. Support for +changing the price of published subscriptions is coming to the Developer Console +in the weeks ahead. In the short term, you can work around this limitation by +publishing a new subscription product ID at a new price, then offer it in your +app instead of the original product. Users who have already purchased will +continue to be charged at the original price, but new users will be charged at +the new price.

        + +

        User billing

        + +

        You can sell subscription products with automated recurring billing at +either of two intervals:

        + +
          +
        • Monthly — Google Play bills the customer’s Google Wallet account at + the time of purchase and monthly subsequent to the purchase date (exact billing + intervals can vary slightly over time)
        • +
        • Annually — Google Play bills the customer's Google Wallet account at + the time of purchase and again on the same date in subsequent years.
        • +
        + +

        Billing continues indefinitely at the interval and price specified for the +subscription. At each subscription renewal, Google Play charges the user account +automatically, then notifies the user of the charges afterward by email. Billing +cycles will always match subscription cycles, based on the purchase date.

        + +

        Over the life of a subscription, the form of payment billed remains the same +— Google Play always bills the same form of payment (such as credit card, +Direct Carrier Billing) that was originally used to purchase the +subscription.

        + +

        When the subscription payment is approved by Google Wallet, Google Play +provides a purchase token back to the purchasing app through the In-app Billing +API. For details, see Purchase token, below. Your apps can +store the token locally or pass it to your backend servers, which can then use +it to validate or cancel the subscription remotely using the Google Play Android Developer API.

        + +

        In the case of billing errors, such as could happen if the customer’s credit +card becomes invalid, Google Play notifies your app of the change in purchase +state.

        + +

        As a best practice, we recommend that your app includes business logic to +notify your backend servers of subscription purchases, tokens, and any billing +errors that may occur. Your backend servers can use the server-side API to query +and update your records and follow up with customers directly, if needed.

        + +

        Subscription cancellation

        + +

        Users can view the status of all of their subscriptions and cancel them if +necessary from the My Apps screen in the Play Store app. Currently, the In-app +Billing API does not provide support for canceling subscriptions direct from +inside the purchasing app, although your app can broadcast an Intent to launch +the Play Store app directly to the My Apps screen.

        + +

        When the user cancels a subscription, Google Play does not offer a refund for +the current billing cycle. Instead, it allows the user to have access to the +cancelled subscription until the end of the current billing cycle, at which time +it terminates the subscription. For example, if a user purchases a monthly +subscription and cancels it on the 15th day of the cycle, Google Play will +consider the subscription valid until the end of the 30th day (or other day, +depending on the month).

        + +

        In some cases, the user may contact you directly to request cancellation of a +subscription. In this and similar cases, you can use the server-side API to +query and directly cancel the user’s subscription from your servers. + +

        Important: In all cases, you must continue +to offer the content that your subscribers have purchased through their +subscriptions, for as long any users are able to access it. That is, you must +not remove any subscriber’s content while any user still has an active +subscription to it, even if that subscription will terminate at the end of the +current billing cycle. Removing content that a subscriber is entitled to access +will result in penalties. Please see the policies document for more information.

        + +

        App uninstallation

        + +

        When the user uninstalls an app that includes purchased subscriptions, the Play Store app will notify the user that there are active subscriptions. If the user chooses to continue with the uninstalltion, the app is removed and the subscriptions remain active and recurring billing continues. The user can return to cancel the associated subscriptions at any time in the My Apps screen of the Play Store app. If the user chooses to cancel the uninstallation, the app and subscriptions remain as they were.

        + +

        Refunds

        + +

        As with other in-app products, Google Play does not provide a refund window +for subscription purchases. For example, users who purchase an app can ask for a +refund from Google Play within a 15-minute window. With subscriptions, Google +Play does not provide a refund window, so users will need to contact you +directly to request a refund. + +

        If you receive requests for refunds, you can use the server-side API to +cancel the subscription or verify that it is already cancelled. However, keep in +mind that Google Play considers cancelled subscriptions valid until the end of +their current billing cycles, so even if you grant a refund and cancel the +subscription, the user will still have access to the content. + +

        Note: Partial refunds for canceled +subscriptions are not available at this time.

        + +

        Payment processing and policies

        + +

        In general, the terms of Google Play allow you to sell in-app subscriptions +only through the standard payment processor, Google Wallet. For purchases of any +subscription products, just as for other in-app products and apps, the +transaction fee for subscriptions, just as for other in-app purchases, is the +same as the transaction fee for application purchases (30%).

        + +

        Apps published on Google Play that are selling subscriptions must use In-app +Billing to handle the transaction and may not provide links to a purchase flow +outside of the app and Google Play (such as to a web site).

        + +

        For complete details about terms and policies, see the policies +document.

        + +

        System requirements for subscriptions

        + +

        In-app purchases of subscriptions are supported only on devices that meet +these minimum requirements:

        + +
          +
        • Must run Android 2.2 or higher
        • +
        • Google Play Store app, version 3.5 or higher, must be installed
        • +
        + +

        Google Play 3.5 and later versions include support for the In-app Billing +v2 API or higher, which is needed to support handling of subscription +products.

        + +

        Compatibility considerations

        + +

        As noted in the previous section, support for subscriptions is available only +on devices that meet the system requirements. Not all devices will receive or +install Google Play 3.5, so not all users who install your apps will have access +to the In-app Billing API and subscriptions.

        + +

        If you are targeting older devices that run Android 2.1 or earlier, we +recommend that you offer those users an alternative way buy the content that is +available through subscriptions. For example, you could create standard in-app +products (one-time purchases) that give access to similar content as your +subscriptions, possibly for a longer interval such as a year.

        + + +

        Implementing Subscriptions

        + +

        Subscriptions are a standard In-app Billing product type. If you have already +implemented In-app Billing for one-time purchase products, you will find that +adding support for subscriptions is straightforward, with minimal impact on your +code. If you are new to In-app Billing, you can implement subscriptions using +the standard communication model, data structures, and user interactions as for +other in-app products.subscriptions.

        + +

        The full implementation details for In-app Billing are provided outside of +this document, starting with the In-app Billing +Overview. This document is focused on highlighting implementation details +that are specific to subscriptions, along with some strategies for the +associated billing and business models.

        + + +

        Sample application

        + +

        To help you get started with your In-app Billing implementation and +subscriptions, an updated version of the In-app Billing sample app is available. +You can download the sample app from the Android SDK repository using the +Android SDK Manager. For details, see +Downloading the Sample Application.

        + +

        Application model

        + +

        With subscriptions, your app uses the standard In-app Billing application +model, sending billing requests to the Play Store application over interprocess +communication (IPC) and receiving purchase responses from the Play Store app in +the form of asynchronous broadcast intents. Your application does not manage any +network connections between itself and the Google Play server or use any special +APIs from the Android platform.

        + +

        Your app also uses the standard In-app Billing components — a billing +Service for sending requests, a BroadcastReceiver for receiving the responses, +and a security component for verifying that the response was sent by Google +Play. Also recommended are a response Handler for processing notifications, +errors, and status messages, and an observer for sending callbacks to your +application as needed. All of these components and their interactions are +described in full in the In-app Billing +Overview and related documents.

        + +

        To initiate different types of billing communication with Google Play, your +app will use the standard set of in-app billing requests and receive the same +responses. Inside the requests and responses are two new fields described below. +

        + +

        Purchase token

        + +

        Central to the end-to-end architecture for subscriptions is the purchase +token, a string value that uniquely identifies (and associates) a user ID and a +subscription ID. Google Play generates the purchase token when the user +completes the purchase of a subscription product (and payment is approved by +Google Wallet) and then sends it to the purchasing app on the device through the +In-app Billing API.

        + +

        At the conclusion of a PURCHASE_REQUEST message flow, your app +can retrieve the purchase token and other transaction details by initiating a +GET_PURCHASE_INFORMATION request. The Bundle returned by the call +contains an JSON array of order objects. In the order corresponding to the +subscription purchase, the token is available in the purchaseToken +field.

        + +

        An example of a JSON order object that includes a subscription purchase token +is shown below.

        + +
        { "nonce" : 1836535032137741465,
        +  "orders" :
        +    [{ "notificationId" : "android.test.purchased",
        +       "orderId" : "transactionId.android.test.purchased",
        +       "packageName" : "com.example.dungeons",
        +       "productId" : "android.test.purchased",
        +       "developerPayload" : "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
        +       "purchaseTime" : 1290114783411,
        +       "purchaseState" : 0,
        +       "purchaseToken" : "rojeslcdyyiapnqcynkjyyjh" }]
        +}
        +
        + +

        After receiving a purchase token, your apps can store the token locally or +pass it to your backend servers, which can then use it to query the billing +status or cancel the subscription remotely. If your app will store the token +locally, please read the Security and +Design document for best practices for maintaining the security of your +data.

        + +

        Checking the In-app Billing API version

        + +

        Subscriptions support is available only in versions of Google Play that +support the In-app Billing v2 API (Google Play 3.5 and higher). For your app, +an essential first step at launch is to check whether the version of Google Play +installed on the device supports the In-app Billing v2 API and +subscriptions.

        + +

        To do this, create a CHECK_BILLING_SUPPORTED request Bundle that includes the +required key-value pairs, together with

        + +
          +
        • The API_VERSION key, assigning a value of 2.
        • +
        • The BILLING_REQUEST_ITEM_TYPE key, assigning a value of “subs”
        • +
        + +

        Send the request using sendBillingRequest(Bundle) and receive +the response Bundle. You can extract the response from the +BILLING_RESPONSE_RESPONSE_CODE key of the response. RESULT_OK +indicates that subscriptions are supported.

        + +

        The sample app declares constants for the accepted +BILLING_REQUEST_ITEM_TYPE values (from Consts.java):

        + +
           // These are the types supported in the IAB v2
        +   public static final String ITEM_TYPE_INAPP = "inapp";
        +   public static final String ITEM_TYPE_SUBSCRIPTION = "subs";
        +
        + +

        It sets up a convenience method for building the request bundle (from BillingService.java):

        + +
               protected Bundle makeRequestBundle(String method) {
        +           Bundle request = new Bundle();
        +           request.putString(Consts.BILLING_REQUEST_METHOD, method);
        +           request.putInt(Consts.BILLING_REQUEST_API_VERSION, 2);
        +           request.putString(Consts.BILLING_REQUEST_PACKAGE_NAME, getPackageName());
        +           return request;
        +       }
        +
        + +

        Here’s an example of how to test support for In-App Billing v2 and subscriptions +(from BillingService.java):

        + +
           /**
        +    * Wrapper class that checks if in-app billing is supported.
        +    */
        +   class CheckBillingSupported extends BillingRequest {
        +       public String mProductType = null;
        +       public CheckBillingSupported() {
        +           // This object is never created as a side effect of starting this
        +           // service so we pass -1 as the startId to indicate that we should
        +           // not stop this service after executing this request.
        +           super(-1);
        +       }
        +
        +       public CheckBillingSupported(String type) {
        +           super(-1);
        +           mProductType = type;
        +       }
        +
        +       @Override
        +       protected long run() throws RemoteException {
        +           Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
        +           if (mProductType != null) {
        +               request.putString(Consts.BILLING_REQUEST_ITEM_TYPE, mProductType);
        +           }
        +           Bundle response = mService.sendBillingRequest(request);
        +           int responseCode = response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE);
        +           if (Consts.DEBUG) {
        +               Log.i(TAG, "CheckBillingSupported response code: " +
        +                       ResponseCode.valueOf(responseCode));
        +           }
        +           boolean billingSupported = (responseCode == ResponseCode.RESULT_OK.ordinal());
        +           ResponseHandler.checkBillingSupportedResponse(billingSupported, mProductType);
        +           return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
        +       }
        +   }
        +
        + +

        Requesting a subscription purchase

        + +

        Once you’ve checked the API version as described above and determined that +subscriptions are supported, you can present subscription products to the user +for purchase. When the user has selected a subscription product and initiated a +purchase, your app handles the purchase just as it would for other in-app +products — by sending a REQUEST_PURCHASE request. You can then launch +Google Play to display the checkout user interface and handle the financial +transaction.. + +

        The REQUEST_PURCHASE includes a Bundle containing the item details, as +described in the In-app Billing +Overview. For a subscription, the Bundle must also specify:

        + +
          +
        • The ITEM_ID key, with a value that specifies a valid, published + subscription product.
        • +
        • The ITEM_TYPE key, with a value of “subs” + (ITEM_TYPE_SUBSCRIPTION in the sample app). If the request does not + specify the subscription's ITEM_TYPE, Google Play attempts to + handle the request as a standard in-app purchase (one-time purchase).
        • +
        + +

        Google Play synchronously returns a response bundle that includes +RESPONSE_CODE, PURCHASE_INTENT, and +REQUEST_ID. Your app uses the PURCHASE_INTENT to +launch the checkout UI and the message flow proceeds exactly as described in Messaging sequence.

        + +

        Here’s how the sample app initiates a purchase for a subscription, where +mProductType is ITEM_TYPE_SUBSCRIPTION (from +BillingService.java).

        + +
           /**
        +    * Wrapper class that requests a purchase.
        +    */
        +   class RequestPurchase extends BillingRequest {
        +       public final String mProductId;
        +       public final String mDeveloperPayload;
        +       public final String mProductType;
        +
        +. . .
        +
        +       @Override
        +       protected long run() throws RemoteException {
        +           Bundle request = makeRequestBundle("REQUEST_PURCHASE");
        +           request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId);
        +           request.putString(Consts.BILLING_REQUEST_ITEM_TYPE, mProductType);
        +           // Note that the developer payload is optional.
        +           if (mDeveloperPayload != null) {
        +               request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload);
        +           }
        +           Bundle response = mService.sendBillingRequest(request);
        +           PendingIntent pendingIntent
        +                   = response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
        +           if (pendingIntent == null) {
        +               Log.e(TAG, "Error with requestPurchase");
        +               return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
        +           }
        +
        +           Intent intent = new Intent();
        +           ResponseHandler.buyPageIntentResponse(pendingIntent, intent);
        +           return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID,
        +                   Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
        +       }
        +
        +       @Override
        +       protected void responseCodeReceived(ResponseCode responseCode) {
        +           ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode);
        +       }
        +   }
        +
        + +

        Restoring transactions

        + +

        Subscriptions always use the managed by user account purchase type, +so that you can restore a record of subscription transactions on the device when +needed. When a user installs your app onto a new device, or when the user +uninstalls/reinstalls the app on the original device, your app should restore +the subscriptions that the user has purchased.

        + +

        The process for restoring subscriptions transactions is the same as described +in Messaging sequence. Your app sends a +RESTORE_TRANSACTIONS request to Google Play. Google Play sends two +broadcast intents as asynchronous responses — a RESPONSE_CODE +intent and a PURCHASE_STATE_CHANGED intent.

        + +

        The PURCHASE_STATE_CHANGED intent contains a notification ID +that your app can use to retrieve the purchase details, including the purchase +token, by sending a standard GET_PURCHASE_INFORMATION request. The +Bundle returned in the call includes an JSON array of order objects +corresponding to subscription (and in-app product) purchases that you can +restore locally.

        + +

        Your app can store the restored purchase state and other transaction details +in the way that best meets your needs. Your app can use it later to check the +subscription validity, although please read the Security and +Design document for best practices for maintaining the security of your +data.

        + +

        Checking subscription validity

        + +

        Subscriptions are time-bound purchases that require successful billing +recurrences over time to remain valid. Your app should check the validity of +purchased subscriptions at launch or prior to granting access to subscriber +content.

        + +

        With In-app Billing, you validate a subscription by keeping track of its +purchase state, such as purchased or cancelled, and then checking the state +whenever needed. Google Play provides two ways to let you know when the purchase +state of a subscription changes:

        + +
          +
        • In-app Billing Notifications. Google Play pushes a notification + to your app whenever the purchase state of a subscription changes. Your app can + store the most recent purchase state for a given purchase token and then check + that state at run time, as needed.
        • +
        • Google Play Android Developer API. You can use this HTTP-based + API to poll Google Play for the current purchase state of a subscription. You + can store the purchased state for each purchaseToken on your + backend servers. For more information, see Google Play + Android Developer API, below.
        • +
        + +

        For most use-cases, especially those where backend servers are already keeping +track of subscribed users, implementing a combination of both methods is the +recommended approach. A typical implementation might work like this:

        + +
          +
        • When the user successfully purchases a new subscription, your app notifies a + backend server, which stores the purchase token, user name, and other + information in a secure location.
        • +
        • Since your app cannot know the expiration date, your server can poll Google + Play to get the expiration and store it with the purchase token and other + data.
        • +
        • Because your server now knows the expiration date, it does not need to poll + Google Play again until after the expiration date, at which time it can confirm + that the subscription was not cancelled.
        • +
        • On the client side, your app can continue to update the server whenever the + purchase state changes, storing the state locally.
        • +
        + +

        If you are using both notifications and the Google Play Android Developer API to validate subscriptions, we recommend the following:

        + +
          +
        • If your app wants to check validity but you can’t reach your server (or +you don’t have a server), use the latest purchase state received by +notification.
        • +
        • If you have a server and it’s reachable, always give preference to the +purchase state obtained from your server over the state received in +notifications.
        • +
        + +

        If necessary, you can also use a RESTORE_TRANSACTIONS request to retrieve a record of all managed and in-app products purchased by the user, which you can then store locally. However, using RESTORE_TRANSACTIONS on a regular basis is not recommended because of performance impacts.

        + +

        Regardless of the approach you choose, your app should check subscriptions +and validity at launch, such as prior to accessing subscriber content, game +levels, and so on.

        + +

        Table 1. Summary of purchaseState +values for subscription purchases, as received with a +PURCHASE_STATE_CHANGED intent.

        + + + + + + + + + + +
        StatepurchaseState ValueComments
        Purchased successfully0Sent at original purchase only (not at recurring billing cycles).
        Cancelled1Sent at original purchase only if the purchase has failed for some reason.
        Refunded2The purchase was refunded.
        Subscription expired3Sent if a subscription expires because of non-payment or user cancelation.
        + + +

        Launching your product page to let the user cancel or view subscriptions

        + +

        In-app Billing does not currently provide an API to let users directly view or cancel +subscriptions from within the purchasing app. Instead, users can launch the Play +Store app on their devices and go to the My Apps screen to manage subscriptions. In My Apps, +users can see a list of their subscriptions organized by application. Tapping one of the +subscriptions loads the app's product page, from which users can see active subscriptions +and billing status and cancel subscriptions as needed.

        + +

        To make it easier for users to find and manage their subscriptions from inside your app, +we recommend that you offer a "View My Subscriptions" or "Manage Subscriptions" option in +your UI that directly loads your app's product page in the Play Store app.

        + +

        To do this, create an intent with the ACTION_VIEW +action and include the market:// URI (rather than the http:// +URI) of your app's details page. Here’s an example:

        + +
        Intent intent = new Intent(Intent.ACTION_VIEW);
        +intent.setData(Uri.parse("market://details?id=com.example.app"));
        +startActivity(intent);
        + +

        For more information, see + Linking to Your Products.

        + +

        Recurring billing and changes in purchase state

        + +

        Google Play notifies your app when the user completes the purchase of a +subscription, but the purchase state does not change over time, provided that +recurring billing takes place successfully. Google Play does not notify your app +of a purchase state change until the subscription expires because of +non-payment or user cancellation.

        + +

        Over the life of a subscription, your app does not need to initiate any +recurring billing events — those are all handled by Google Play and they +are transparent to your application if billing is successful.

        + +

        Modifying your app for subscriptions

        + +

        For subscriptions, you make the same types of modifications to your app as +are described in +Modifying your Application Code.

        + +

        Note that, in your UI that lets users view and select subscriptions for +purchase, you should add logic to check for purchased subscriptions and validate +them. Your UI should not present subscriptions if the user has already purchased +them.

        + +

        Administering Subscriptions

        + +

        To create and manage subscriptions, you use the tools in the Developer +Console, just as for other in-app products.

        + +

        At the Developer Console, you can configure these attributes for each +subscription product:

        + +
          +
        • Purchase Type: always set to “subscription”
        • +
        • Subscription ID: An identifier for the subscription
        • +
        • Publishing State: Unpublished/Published
        • +
        • Language: The default language for displaying the subscription
        • +
        • Title: The title of the subscription product
        • +
        • Description: Details that tell the user about the subscription
        • +
        • Price: USD price of subscription per recurrence
        • +
        • Recurrence: monthly or yearly
        • +
        • Additional currency pricing (can be auto-filled)
        • +
        + +

        For details, please see Administering +In-app Billing.

        + + +

        Google Play Android Developer API

        + +

        Google Play offers an HTTP-based API that you can use to remotely query the +validity of a specific subscription at any time or cancel a subscription. The +API is designed to be used from your backend servers as a way of securely +managing subscriptions, as well as extending and integrating subscriptions with +other services.

        + +

        Using the API

        + +

        To use the API, you must first register a project at the Google APIs Console and receive +a Client ID and shared secret that your app will present when calling the +Google Play Android Developer API. All calls to the API are authenticated with +OAuth 2.0.

        + +

        Once your app is registered, you can access the API directly, using standard +HTTP methods to retrieve and manipulate resources, or you can use the Google +APIs Client Libraries, which are extended to support the API.

        + +

        The Google Play Android Developer API is built on a RESTful design that uses +HTTP and JSON, so any standard web stack can send requests and parse the +responses. However, if you don’t want to send HTTP requests and parse responses +manually, you can access the API using the client libraries, which provide +better language integration, improved security, and support for making calls +that require user authorization.

        + +

        For more information about the API and how to access it through the Google +APIs Client Libraries, see the documentation at:

        + +

        https://developers. +google.com/android-publisher/v1/

        + +

        Quota

        + +

        Applications using the Google Play Android Developer API are limited to an +initial courtesy usage quota of 15000 requests per day (per +application). This should provide enough access for normal +subscription-validation needs, assuming that you follow the recommendation in +this section.

        + +

        If you need to request a higher limit for your application, please use the +“Request more” link in the Google APIs Console. +Also, please read the section below on design best practices for minimizing your +use of the API.

        + +

        Authorization

        + +

        Calls to the Google Play Android Developer API require authorization. Google +uses the OAuth 2.0 protocol to allow authorized applications to access user +data. To learn more, see Authorization +in the Google Play Android Developer API documentation.

        + +

        Using the API efficiently

        + +

        Access to the Google Play Android Developer API is regulated to help ensure a +high-performance environment for all applications that use it. While you can +request a higher daily quota for your application, we highly recommend that you +minimize your access using the technique(s) below.

        + +
          +
        • Store subscription expiry on your servers — your servers + should use the Google Play Android Developer API to query the expiration date + for new subscription tokens, then store the expiration date locally. This allows + you to check the status of subscriptions only at or after the expiration (see + below).
        • +
        • Cache expiration and purchaseState — If your app contacts + your backend servers at runtime to verify subscription validity, your server + should cache the expiration and purchaseState to ensure the fastest possible + response (and best experience) for the user.
        • +
        • Query for subscription status only at expiration — Once your + server has retrieved the expiration date of subscription tokens, it should not + query the Google Play servers for the subscription status again until the + subscription is reaching or has passed the expiration date. Typically, your + servers would run a batch query each day to check the status of + expiring subscriptions, then update the database. Note that: +
            +
          • Your servers should not query all subscriptions every day
          • +
          • Your servers should never query subscription status dynamically, based on + individual requests from your Android application.
          • +
          +
        • +
        + +

        By following those general guidelines, your implementation will offer the +best possible performance for users and minimize use of the Google Play Android +Developer API.

        + diff --git a/docs/html/guide/google/play/billing/billing_testing.jd b/docs/html/guide/google/play/billing/billing_testing.jd new file mode 100755 index 000000000000..e2d4a014cbbf --- /dev/null +++ b/docs/html/guide/google/play/billing/billing_testing.jd @@ -0,0 +1,293 @@ +page.title=Testing In-app Billing +parent.title=In-app Billing +parent.link=index.html +@jd:body + + + +

        The Google Play publisher site provides several tools that help you test your in-app billing +implementation before it is published. You can use these tools to create test accounts and purchase +special reserved items that send static billing responses to your application.

        + +

        To test in-app billing in an application you must install the application on an Android-powered +device. You cannot use the Android emulator to test in-app billing. The device you use for testing +must run a standard version of the Android 1.6 or later platform (API level 4 or higher), and have +the most current version of the Google Play application installed. If a device is not running the +most current Google Play application, your application won't be able to send in-app billing +requests to Google Play. For general information about how to set up a device for use in +developing Android applications, see Using Hardware +Devices.

        + +

        The following section shows you how to set up and use the in-app billing test tools.

        + +

        Testing in-app purchases with static responses

        + +

        We recommend that you first test your in-app billing implementation using static responses from +Google Play. This enables you to verify that your application is handling the primary Google +Play responses correctly and that your application is able to verify signatures correctly.

        + +

        To test your implementation with static responses, you make an in-app billing request using a +special item that has a reserved product ID. Each reserved product ID returns a specific static +response from Google Play. No money is transferred when you make in-app billing requests with the +reserved product IDs. Also, you cannot specify the form of payment when you make a billing request +with a reserved product ID. Figure 1 shows the checkout flow for the reserved item that has the +product ID android.test.purchased.

        + + +

        + Figure 1. Wallet flow for the special reserved item android.test.purchased. +

        + +

        You do not need to list the reserved products in your application's product list. Google Play +already knows about the reserved product IDs. Also, you do not need to upload your application to +the publisher site to perform static response tests with the reserved product IDs. You can simply +install your application on a device, log into the device, and make billing requests using the +reserved product IDs.

        + +

        There are four reserved product IDs for testing static in-app billing responses:

        + +
          +
        • android.test.purchased +

          When you make an in-app billing request with this product ID, Google Play responds as + though you successfully purchased an item. The response includes a JSON string, which contains + fake purchase information (for example, a fake order ID). In some cases, the JSON string is + signed and the response includes the signature so you can test your signature verification + implementation using these responses.

          +
        • +
        • android.test.canceled +

          When you make an in-app billing request with this product ID Google Play responds as + though the purchase was canceled. This can occur when an error is encountered in the order + process, such as an invalid credit card, or when you cancel a user's order before it is + charged.

          +
        • +
        • android.test.refunded +

          When you make an in-app billing request with this product ID, Google Play responds as + though the purchase was refunded. Refunds cannot be initiated through Google Play's in-app + billing service. Refunds must be initiated by you (the merchant). After you process a refund + request through your Google Wallet account, a refund message is sent to your application by + Google Play. This occurs only when Google Play gets notification from Google Wallet that + a refund has been made. For more information about refunds, see Handling + IN_APP_NOTIFY messages and In-app Billing + Pricing.

          +
        • +
        • android.test.item_unavailable +

          When you make an in-app billing request with this product ID, Google Play responds as + though the item being purchased was not listed in your application's product list.

          +
        • +
        + +

        In some cases, the reserved items may return signed static responses, which lets you test +signature verification in your application. To test signature verification with the special reserved +product IDs, you may need to set up test accounts or +upload your application as a unpublished draft application. Table 1 shows you the conditions under +which static responses are signed.

        + +

        Table 1. +Conditions under which static responses are signed.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Application ever been published?Draft application uploaded and unpublished?User who is running the applicationStatic response signature
        NoNoAnyUnsigned
        NoNoDeveloperSigned
        YesNoAnyUnsigned
        YesNoDeveloperSigned
        YesNoTest accountSigned
        YesYesAnySigned
        + +

        To make an in-app billing request with a reserved product ID, you simply construct a normal +REQUEST_PURCHASE request, but instead of using a real product ID from your +application's product list you use one of the reserved product IDs.

        + +

        To test your application using the reserved product IDs, follow these steps:

        + +
          +
        1. Install your application on an Android-powered device. +

          You cannot use the emulator to test in-app billing; you must install your application on a + device to test in-app billing.

          +

          To learn how to install an application on a device, see Running on a + device.

          +
        2. +
        3. Sign in to your device with your developer account. +

          You do not need to use a test account if you are testing only with the reserved product + IDs.

          +
        4. +
        5. Verify that your device is running a supported version of the Google Play + application or the MyApps application. +

          If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of + the MyApps application. If your device is running any other version of Android, in-app billing + requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the + version of the Google Play application, see Updating Google + Play.

          +
        6. +
        7. Run your application and purchase the reserved product IDs.
        8. +
        + +

        Note: Making in-app billing requests with the reserved product IDs +overrides the usual Google Play production system. When you send an in-app billing request for a +reserved product ID, the quality of service will not be comparable to the production +environment.

        + +

        Testing In-app Purchases Using Your Own Product IDs

        + +

        After you finish your static response testing, and you verify that signature verification is +working in your application, you can test your in-app billing implementation by making actual in-app +purchases. Testing real in-app purchases enables you to test the end-to-end in-app billing +experience, including the actual responses from Google Play and the actual checkout flow that +users will experience in your application.

        + +

        Note: You do not need to publish your application to do end-to-end +testing. You only need to upload your application as a draft application to perform end-to-end +testing.

        + +

        To test your in-app billing implementation with actual in-app purchases, you will need to +register at least one test account on the Google Play publisher site. You cannot use your +developer account to test the complete in-app purchase process because Google Wallet does not let +you buy items from yourself. If you have not set up test accounts before, see Setting up test +accounts.

        + +

        Also, a test account can purchase an item in your product list only if the item is published. The +application does not need to be published, but the item does need to be published.

        + +

        When you use a test account to purchase items, the test account is billed through Google Wallet +and your Google Wallet Merchant account receives a payout for the purchase. Therefore, you may +want to refund purchases that are made with test accounts, otherwise the purchases will show up as +actual payouts to your merchant account.

        + +

        To test your in-app billing implementation with actual purchases, follow these steps:

        + +
          +
        1. Upload your application as a draft application to the publisher site. +

          You do not need to publish your application to perform end-to-end testing with real product + IDs; you only need to upload your application as a draft application. However, you must sign + your application with your release key before you upload it as a draft application. Also, the + version number of the uploaded application must match the version number of the application you + load to your device for testing. To learn how to upload an application to Google Play, see + Uploading + applications.

          +
        2. +
        3. Add items to the application's product list. +

          Make sure that you publish the items (the application can remain unpublished). See Creating a product + list to learn how to do this.

          +
        4. +
        5. Install your application on an Android-powered device. +

          You cannot use the emulator to test in-app billing; you must install your application on a + device to test in-app billing.

          +

          To learn how to install an application on a device, see Running on a + device.

          +
        6. +
        7. Make one of your test accounts the primary account on your device. +

          To perform end-to-end testing of in-app billing, the primary account on your device must be + one of the test accounts + that you registered on the Google Play site. If the primary account on your device is not a + test account, you must do a factory reset of the device and then sign in with one of your test + accounts. To perform a factory reset, do the following:

          +
            +
          1. Open Settings on your device.
          2. +
          3. Touch Privacy.
          4. +
          5. Touch Factory data reset.
          6. +
          7. Touch Reset phone.
          8. +
          9. After the phone resets, be sure to sign in with one of your test accounts during the + device setup process.
          10. +
          +
        8. +
        9. Verify that your device is running a supported version of the Google Play + application or the MyApps application. +

          If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of + the MyApps application. If your device is running any other version of Android, in-app billing + requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the + version of the Google Play application, see Updating Google + Play.

          +
        10. +
        11. Make in-app purchases in your application.
        12. +
        + +

        Note: The only way to change the primary account on a device is to +do a factory reset, making sure you log on with your primary account first.

        + +

        When you are finished testing your in-app billing implementation, you are ready to +publish your application on Google Play. You can follow the normal steps for preparing, signing, and publishing on Google Play. +

        + diff --git a/docs/html/guide/google/play/billing/index.jd b/docs/html/guide/google/play/billing/index.jd new file mode 100755 index 000000000000..a33b19961f13 --- /dev/null +++ b/docs/html/guide/google/play/billing/index.jd @@ -0,0 +1,116 @@ +page.title=In-app Billing +@jd:body + + + +

        In-app Billing is a Google Play service that lets you sell digital content from inside +your applications. You can use the service to sell a wide range of content, including downloadable +content such as media files or photos, virtual content such as game levels or potions, premium services +and features, and more. You can use In-app Billing to sell products as

        + +
          +
        • Standard in-app products (one-time billing), or
        • +
        • Subscriptions, (recurring, automated billing)
        • +
        + + + +

        When you use the in-app billing service to sell an item, +whether it's an in-app product or a subscription, Google Play +handles all checkout details so your application never has to directly process +any financial transactions. Google Play uses the same checkout backend service as +is used for application purchases, so your users experience a consistent and +familiar purchase flow (see figure 1). Also, the transaction fee for in-app +purchases is the same as the transaction fee for application purchases +(30%).

        + +

        Any application that you publish through Google Play can implement In-app Billing. No special +account or registration is required other than an Android Market publisher account and a Google +Wallet Merchant account. Also, because the service uses no dedicated framework APIs, you can add +in-app billing to any application that uses a minimum API level of 4 or higher.

        + +

        To help you integrate in-app billing into your application, the Android SDK +provides a sample application that demonstrates how to sell standard in-app +products and subscriptions from inside an app. The sample contains examples of +billing-related classes you can use to implement in-app billing in your +application. It also contains examples of the database, user interface, and +business logic you might use to implement in-app billing.

        + +

        Important: Although the sample application is a working example +of how you can implement in-app billing, we strongly recommend that you modify and +obfuscate the sample code before you use it in a production application. For more information, see +Security and Design.

        + + +

        + Figure 1. Applications initiate in-app billing requests through their own UI + (first screen). Google Play responds to the request by providing the checkout user interface + (middle screen). When checkout is complete, the application resumes. +

        + +

        To learn more about Google Play's in-app billing service and start integrating it into your +applications, read the following documents:

        + +
        +
        Overview of In-app + Billing
        +
        Learn how the service works and what a typical in-app billing implementation looks + like.
        +
        Implementing + In-app Billing
        +
        Use this step-by-step guide to start incorporating in-app billing into your + application. The instructions apply to both one-time and subscription purchases.
        + +
        Subscriptions
        +
        Learn how subscriptions work and how to implement support for them in your app.
        +
        Security + and Design
        +
        Review these best practices to help ensure that your in-app billing implementation is + secure and well designed.
        +
        Testing In-app + Billing
        +
        Understand how the in-app billing test tools work and learn how to test your in-app billing + implementation.
        +
        Administering + In-app Billing
        +
        Learn how to set up your product list, register test accounts, and handle refunds.
        +
        In-app Billing + Reference
        +
        Get detailed information about Google Play response codes and the in-app billing + interface.
        +
        + diff --git a/docs/html/guide/google/play/expansion-files.jd b/docs/html/guide/google/play/expansion-files.jd new file mode 100644 index 000000000000..62ca1e2572f8 --- /dev/null +++ b/docs/html/guide/google/play/expansion-files.jd @@ -0,0 +1,1270 @@ +page.title=APK Expansion Files +@jd:body + + +
        +
        +

        Quickview

        +
          +
        • Recommended for most apps that exceed the 50MB APK limit
        • +
        • You can provide up to 4GB of additional data for each APK
        • +
        • Google Play hosts and serves the expansion files at no charge
        • +
        • The files can be any file type you want and are saved to the device's shared storage
        • +
        + +

        In this document

        +
          +
        1. Overview +
            +
          1. File name format
          2. +
          3. Storage location
          4. +
          5. Download process
          6. +
          7. Development checklist
          8. +
          +
        2. +
        3. Rules and Limitations
        4. +
        5. Downloading the Expansion Files +
            +
          1. About the Downloader Library
          2. +
          3. Preparing to use the Downloader Library
          4. +
          5. Declaring user permissions
          6. +
          7. Implementing the downloader service
          8. +
          9. Implementing the alarm receiver
          10. +
          11. Starting the download
          12. +
          13. Receiving download progress
          14. +
          +
        6. +
        7. Using APKExpansionPolicy
        8. +
        9. Reading the Expansion File +
            +
          1. Getting the file names
          2. +
          3. Using the APK Expansion Zip Library
          4. +
          +
        10. +
        11. Testing Your Expansion Files +
            +
          1. Testing file reads
          2. +
          3. Testing file downloads
          4. +
          +
        12. +
        13. Updating Your Application
        14. +
        + +

        See also

        +
          +
        1. Application Licensing
        2. +
        3. Multiple +APK Support
        4. +
        +
        +
        + + + +

        Google Play currently requires that your APK file be no more than 50MB. For most +applications, this is plenty of space for all the application's code and assets. +However, some apps need more space for high-fidelity graphics, media files, or other large assets. +Previously, if your app exceeded 50MB, you had to host and download the additional resources +yourself when the user opens the app. Hosting and serving the extra files can be costly, and the +user experience is often less than ideal. To make this process easier for you and more pleasant +for users, Google Play allows you to attach two large expansion files that supplement your +APK.

        + +

        Google Play hosts the expansion files for your application and serves them to the device at +no cost to you. The expansion files are saved to the device's shared storage location (the +SD card or USB-mountable partition; also known as the "external" storage) where your app can access +them. On most devices, Google Play downloads the expansion file(s) at the same time it +downloads the APK, so your application has everything it needs when the user opens it for the +first time. In some cases, however, your application must download the files from Google Play +when your application starts.

        + + + +

        Overview

        + +

        Each time you upload an APK using the Google Play Android Developer Console, you have the option to +add one or two expansion files to the APK. Each file can be up to 2GB and it can be any format you +choose, but we recommend you use a compressed file to conserve bandwidth during the download. +Conceptually, each expansion file plays a different role:

        + +
          +
        • The main expansion file is the +primary expansion file for additional resources required by your application.
        • +
        • The patch expansion file is optional and intended for small updates to the +main expansion file.
        • +
        + +

        While you can use the two expansion files any way you wish, we recommend that the main +expansion file deliver the primary assets and should rarely if ever updated; the patch expansion +file should be smaller and serve as a “patch carrier,” getting updated with each major +release or as necessary.

        + +

        However, even if your application update requires only a new patch expansion file, you still must +upload a new APK with an updated {@code +versionCode} in the manifest. (The +Developer Console does not allow you to upload an expansion file to an existing APK.)

        + +

        Note: The patch expansion file is semantically the same as the +main expansion file—you can use each file any way you want. The system does +not use the patch expansion file to perform patching for your app. You must perform patching +yourself or be able to distinguish between the two files.

        + + + +

        File name format

        + +

        Each expansion file you upload can be any format you choose (ZIP, PDF, MP4, etc.). Regardless of +the file type, Google Play considers them opaque binary blobs and renames the files +using the following scheme:

        + +
        +[main|patch].<expansion-version>.<package-name>.obb
        +
        + +

        There are three components to this scheme:

        + +
        +
        {@code main} or {@code patch}
        +
        Specifies whether the file is the main or patch expansion file. There can be +only one main file and one patch file for each APK.
        +
        {@code <expansion-version>}
        +
        This is an integer that matches the version code of the APK with which the expansion is +first associated (it matches the application's {@code android:versionCode} +value). +

        "First" is emphasized because although the Developer Console allows you to +re-use an uploaded expansion file with a new APK, the expansion file's name does not change—it +retains the version applied to it when you first uploaded the file.

        +
        {@code <package-name>}
        +
        Your application's Java-style package name.
        +
        + +

        For example, suppose your APK version is 314159 and your package name is com.example.app. If you +upload a main expansion file, the file is renamed to:

        +
        main.314159.com.example.app.obb
        + + +

        Storage location

        + +

        When Google Play downloads your expansion files to a device, it saves them to the system's +shared storage location. To ensure proper behavior, you must not delete, move, or rename the +expansion files. In the event that your application must perform the download from Google Play +itself, you must save the files to the exact same location.

        + +

        The specific location for your expansion files is:

        + +
        +<shared-storage>/Android/obb/<package-name>/
        +
        + +
          +
        • {@code <shared-storage>} is the path to the shared storage space, available from +{@link android.os.Environment#getExternalStorageDirectory()}.
        • +
        • {@code <package-name>} is your application's Java-style package name, available +from {@link android.content.Context#getPackageName()}.
        • +
        + +

        For each application, there are never more than two expansion files in this directory. +One is the main expansion file and the other is the patch expansion file (if necessary). Previous +versions are overwritten when you update your application with new expansion files.

        + +

        If you must unpack the contents of your expansion files, do not delete the +{@code .obb} expansion files afterwards and do not save the unpacked data +in the same directory. You should save your unpacked files in the directory +specified by {@link android.content.Context#getExternalFilesDir getExternalFilesDir()}. However, +if possible, it's best if you use an expansion file format that allows you to read directly from +the file instead of requiring you to unpack the data. For example, we've provided a library +project called the APK Expansion Zip Library that reads your data directly +from the ZIP file.

        + +

        Note: Unlike APK files, any files saved on the shared storage can +be read by the user and other applications.

        + +

        Tip: If you're packaging media files into a ZIP, you can use media +playback calls on the files with offset and length controls (such as {@link +android.media.MediaPlayer#setDataSource(FileDescriptor,long,long) MediaPlayer.setDataSource()} and +{@link android.media.SoundPool#load(FileDescriptor,long,long,int) SoundPool.load()}) without the +need to unpack your ZIP. In order for this to work, you must not perform additional compression on +the media files when creating the ZIP packages. For example, when using the zip tool, +you should use the -n option to specify the file suffixes that should not be +compressed:
        +zip -n .mp4;.ogg main_expansion media_files

        + + +

        Download process

        + +

        Most of the time, Google Play downloads and saves your expansion files at the same time it +downloads the APK to the device. However, in some cases Google Play +cannot download the expansion files or the user might have deleted previously downloaded expansion +files. To handle these situations, your app must be able to download the files +itself when the main activity starts, using a URL provided by Google Play.

        + +

        The download process from a high level looks like this:

        + +
          +
        1. User selects to install your app from Google Play.
        2. +
        3. If Google Play is able to download the expansion files (which is the case for most +devices), it downloads them along with the APK. +

          If Google Play is unable to download the expansion files, it downloads the +APK only.

          +
        4. +
        5. When the user launches your application, your app must check whether the expansion files are +already saved on the device. +
            +
          1. If yes, your app is ready to go.
          2. +
          3. If no, your app must download the expansion files over HTTP from Google Play. Your app +must send a request to the Google Play client using the Google Play's Application Licensing service, which +responds with the name, file size, and URL for each expansion file. With this information, you then +download the files and save them to the proper storage location.
          4. +
          +
        6. +
        + +

        Caution: It is critical that you include the necessary code to +download the expansion files from Google Play in the event that the files are not already on the +device when your application starts. As discussed in the following section about Downloading the Expansion Files, we've made a library available to you that +greatly simplifies this process and performs the download from a service with a minimal amount of +code from you.

        + + + + +

        Development checklist

        + +

        Here's a summary of the tasks you should perform to use expansion files with your +application:

        + +
          +
        1. First determine whether your application absolutely requires more than 50MB per installation. +Space is precious and you should keep your total application size as small as possible. If your app +uses more than 50MB in order to provide multiple versions of your graphic assets for multiple screen +densities, consider instead publishing multiple APKs in which each APK +contains only the assets required for the screens that it targets.
        2. +
        3. Determine which application resources to separate from your APK and package them in a +file to use as the main expansion file. +

          Normally, you should only use the second patch expansion file when performing updates to +the main expansion file. However, if your resources exceed the 2GB limit for the main +expansion file, you can use the patch file for the rest of your assets.

          +
        4. +
        5. Develop your application such that it uses the resources from your expansion files in the +device's shared storage location. +

          Remember that you must not delete, move, or rename the expansion files.

          +

          If your application doesn't demand a specific format, we suggest you create ZIP files for +your expansion files, then read them using the APK Expansion Zip +Library.

          +
        6. +
        7. Add logic to your application's main activity that checks whether the expansion files +are on the device upon start-up. If the files are not on the device, use Google Play's Application Licensing service to request URLs +for the expansion files, then download and save them. +

          To greatly reduce the amount of code you must write and ensure a good user experience +during the download, we recommend you use the Downloader +Library to implement your download behavior.

          +

          If you build your own download service instead of using the library, be aware that you +must not change the name of the expansion files and must save them to the proper +storage location.

        8. +
        + +

        Once you've finished your application development, follow the guide to Testing +Your Expansion Files.

        + + + + + + +

        Rules and Limitations

        + +

        Adding APK expansion files is a feature available when you upload your application using the +Developer Console. When uploading your application for the first time or updating an +application that uses expansion files, you must be aware of the following rules and limitations:

        + +
          +
        1. Each expansion file can be no more than 2GB.
        2. +
        3. In order to download your expansion files from Google Play, the user must have +acquired your application from Google Play. Google Play will not +provide the URLs for your expansion files if the application was installed by other means.
        4. +
        5. When performing the download from within your application, the URL that Google Play +provides for each file is unique for every download and each one expires shortly after it is given +to your application.
        6. +
        7. If you update your application with a new APK or upload multiple APKs for the same +application, you can select expansion files that you've uploaded for a previous APK. The +expansion file's name does not change—it retains the version received by the APK to +which the file was originally associated.
        8. +
        9. If you use expansion files in combination with multiple APKs in order to +provide different expansion files for different devices, you still must upload separate APKs +for each device in order to provide a unique {@code versionCode} +value and declare different filters for +each APK.
        10. +
        11. You cannot issue an update to your application by changing the expansion files +alone—you must upload a new APK to update your app. If your changes only +concern the assets in your expansion files, you can update your APK simply by changing the {@code versionCode} (and +perhaps also the {@code +versionName}).

        12. +
        13. Do not save other data into your obb/ +directory. If you must unpack some data, save it into the location specified by {@link +android.content.Context#getExternalFilesDir getExternalFilesDir()}.
        14. +
        15. Do not delete or rename the {@code .obb} expansion file (unless you're +performing an update). Doing so will cause Google Play (or your app itself) to repeatedly +download the expansion file.
        16. +
        17. When updating an expansion file manually, you must delete the previous expansion file.
        18. +
        + + + + + + + + + +

        Downloading the Expansion Files

        + +

        In most cases, Google Play downloads and saves your expansion files to the device at the same +time it installs or updates the APK. This way, the expansion files are available when your +application launches for the first time. However, in some cases your app must download the +expansion files itself by requesting them from a URL provided to you in a response +from Google Play's Application Licensing service.

        + +

        The basic logic you need to download your expansion files is the following:

        + +
          +
        1. When your application starts, look for the expansion files on the shared storage location (in the +Android/obb/<package-name>/ directory). +
            +
          1. If the expansion files are there, you're all set and your application can continue.
          2. +
          3. If the expansion files are not there: +
              +
            1. Perform a request using Google Play's Application Licensing to get your +app's expansion file names, sizes, and URLs.
            2. +
            3. Use the URLs provided by Google Play to download the expansion files and save +the expansion files. You must save the files to the shared storage location +(Android/obb/<package-name>/) and use the exact file name provided +by Google Play's response. +

              Note: The URL that Google Play provides for your +expansion files is unique for every download and each one expires shortly after it is given to +your application.

              +
            4. +
            +
          4. +
          +
        2. +
        + + +

        If your application is free (not a paid app), then you probably haven't used the Application Licensing service. It's primarily +designed for you to enforce +licensing policies for your application and ensure that the user has the right to +use your app (he or she rightfully paid for it on Google Play). In order to facilitate the +expansion file functionality, the licensing service has been enhanced to provide a response +to your application that includes the URL of your application's expansion files that are hosted +on Google Play. So, even if your application is free for users, you need to include the +License Verification Library (LVL) to use APK expansion files. Of course, if your application +is free, you don't need to enforce license verification—you simply need the +library to perform the request that returns the URL of your expansion files.

        + +

        Note: Whether your application is free or not, Google Play +returns the expansion file URLs only if the user acquired your application from Google Play.

        + +

        In addition to the LVL, you need a set of code that downloads the expansion files +over an HTTP connection and saves them to the proper location on the device's shared storage. +As you build this procedure into your application, there are several issues you should take into +consideration:

        + +
          +
        • The device might not have enough space for the expansion files, so you should check +before beginning the download and warn the user if there's not enough space.
        • +
        • File downloads should occur in a background service in order to avoid blocking the user +interaction and allow the user to leave your app while the download completes.
        • +
        • A variety of errors might occur during the request and download that you must +gracefully handle.
        • +
        • Network connectivity can change during the download, so you should handle such changes and +if interrupted, resume the download when possible.
        • +
        • While the download occurs in the background, you should provide a notification that +indicates the download progress, notifies the user when it's done, and takes the user back to +your application when selected.
        • +
        + + +

        To simplify this work for you, we've built the Downloader Library, +which requests the expansion file URLs through the licensing service, downloads the expansion files, +performs all of the tasks listed above, and even allows your activity to pause and resume the +download. By adding the Downloader Library and a few code hooks to your application, almost all the +work to download the expansion files is already coded for you. As such, in order to provide the best +user experience with minimal effort on your behalf, we recommend you use the Downloader Library to +download your expansion files. The information in the following sections explain how to integrate +the library into your application.

        + +

        If you'd rather develop your own solution to download the expansion files using the Google +Play URLs, you must follow the Application +Licensing documentation to perform a license request, then retrieve the expansion file names, +sizes, and URLs from the response extras. You should use the {@code +APKExpansionPolicy} class (included in the License Verification Library) as your licensing +policy, which captures the expansion file names, sizes, and URLs from the licensing service..

        + + + +

        About the Downloader Library

        + +

        To use APK expansion files with your application and provide the best user experience with +minimal effort on your behalf, we recommend you use the Downloader Library that's included in the +Google Market Apk Expansion package. This library downloads your expansion files in a +background service, shows a user notification with the download status, handles network +connectivity loss, resumes the download when possible, and more.

        + +

        To implement expansion file downloads using the Downloader Library, all you need to do is:

        + +
          +
        • Extend a special {@link android.app.Service} subclass and {@link +android.content.BroadcastReceiver} subclass that each require just a few +lines of code from you.
        • +
        • Add some logic to your main activity that checks whether the expansion files have +already been downloaded and, if not, invokes the download process and displays a +progress UI.
        • +
        • Implement a callback interface with a few methods in your main activity that +receives updates about the download progress.
        • +
        + +

        The following sections explain how to set up your app using the Downloader Library.

        + + +

        Preparing to use the Downloader Library

        + +

        To use the Downloader Library, you need to +download two packages from the SDK Manager and add the appropriate libraries to your +application.

        + +

        First, open the Android SDK Manager, expand +Extras and download:

        +
          +
        • Google Market Licensing package
        • +
        • Google Market Apk Expansion package
        • +
        + +

        If you're using Eclipse, create a project for each library and add it to your app:

        +
          +
        1. Create a new Library Project for the License Verification Library and Downloader +Library. For each library: +
            +
          1. Begin a new Android project.
          2. +
          3. Select Create project from existing +source and choose the library from the {@code <sdk>/extras/google/} directory +({@code market_licensing/} for the License Verification Library or {@code +market_apk_expansion/downloader_library/} for the Downloader Library).
          4. +
          5. Specify a Project Name such as "Google Play License Library" and "Google Play +Downloader +Library"
          6. +
          7. Click Finish.
          8. +
          +

          Note: The Downloader Library depends on the License +Verification Library. Be sure to add the License +Verification Library to the Downloader Library's project properties (same process as +steps 2 and 3 below).

          +
        2. +
        3. Right-click the Android project in which you want to use APK expansion files and +select Properties.
        4. +
        5. In the Library panel, click Add to select and add each of the +libraries to your application.
        6. +
        + +

        Or, from a command line, update your project to include the libraries:

        +
          +
        1. Change directories to the <sdk>/tools/ directory.
        2. +
        3. Execute android update project with the {@code --library} option to add both the +LVL and the Downloader Library to your project. For example: +
          +android update project --path ~/Android/MyApp \
          +--library ~/android_sdk/extras/google/market_licensing \
          +--library ~/android_sdk/extras/google/market_apk_expansion/downloader_library
          +
          +
        4. +
        + +

        With both the License Verification Library and Downloader Library added to your +application, you'll be able to quickly integrate the ability to download expansion files from +Google Play. The format that you choose for the expansion files and how you read them +from the shared storage is a separate implementation that you should consider based on your +application needs.

        + +

        Tip: The Apk Expansion package includes a sample +application +that shows how to use the Downloader Library in an app. The sample uses a third library +available in the Apk Expansion package called the APK Expansion Zip Library. If +you plan on +using ZIP files for your expansion files, we suggest you also add the APK Expansion Zip Library to +your application. For more information, see the section below +about Using the APK Expansion Zip Library.

        + + + +

        Declaring user permissions

        + +

        In order to download the expansion files, the Downloader Library +requires several permissions that you must declare in your application's manifest file. They +are:

        + +
        +<manifest ...>
        +    <!-- Required to access Google Play Licensing -->
        +    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
        +
        +    <!-- Required to download files from Google Play -->
        +    <uses-permission android:name="android.permission.INTERNET" />
        +
        +    <!-- Required to keep CPU alive while downloading files (NOT to keep screen awake) -->
        +    <uses-permission android:name="android.permission.WAKE_LOCK" />
        +
        +    <!-- Required to poll the state of the network connection and respond to changes -->
        +    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        +
        +    <!-- Required to check whether Wi-Fi is enabled -->
        +    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
        +
        +    <!-- Required to read and write the expansion files on shared storage -->
        +    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        +    ...
        +</manifest>
        +
        + +

        Note: By default, the Downloader Library requires API +level 4, but the APK Expansion Zip Library requires API level 5.

        + + +

        Implementing the downloader service

        + +

        In order to perform downloads in the background, the Downloader Library provides its +own {@link android.app.Service} subclass called {@code DownloaderService} that you should extend. In +addition to downloading the expansion files for you, the {@code DownloaderService} also:

        + +
          +
        • Registers a {@link android.content.BroadcastReceiver} that listens for changes to the +device's network connectivity (the {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} +broadcast) in order to pause the download when necessary (such as due to connectivity loss) and +resume the download when possible (connectivity is acquired).
        • +
        • Schedules an {@link android.app.AlarmManager#RTC_WAKEUP} alarm to retry the download for +cases in which the service gets killed.
        • +
        • Builds a custom {@link android.app.Notification} that displays the download progress and +any errors or state changes.
        • +
        • Allows your application to manually pause and resume the download.
        • +
        • Verifies that the shared storage is mounted and available, that the files don't already exist, +and that there is enough space, all before downloading the expansion files. Then notifies the user +if any of these are not true.
        • +
        + +

        All you need to do is create a class in your application that extends the {@code +DownloaderService} class and override three methods to provide specific application details:

        + +
        +
        {@code getPublicKey()}
        +
        This must return a string that is the Base64-encoded RSA public key for your publisher +account, available from the profile page on the Developer Console (see Setting Up for Licensing).
        +
        {@code getSALT()}
        +
        This must return an array of random bytes that the licensing {@code Policy} uses to +create an {@code +Obfuscator}. The salt ensures that your obfuscated {@link android.content.SharedPreferences} +file in which your licensing data is saved will be unique and non-discoverable.
        +
        {@code getAlarmReceiverClassName()}
        +
        This must return the class name of the {@link android.content.BroadcastReceiver} in +your application that should receive the alarm indicating that the download should be +restarted (which might happen if the downloader service unexpectedly stops).
        +
        + +

        For example, here's a complete implementation of {@code DownloaderService}:

        + +
        +public class SampleDownloaderService extends DownloaderService {
        +    // You must use the public key belonging to your publisher account
        +    public static final String BASE64_PUBLIC_KEY = "YourLVLKey";
        +    // You should also modify this salt
        +    public static final byte[] SALT = new byte[] { 1, 42, -12, -1, 54, 98,
        +            -100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84
        +    };
        +
        +    @Override
        +    public String getPublicKey() {
        +        return BASE64_PUBLIC_KEY;
        +    }
        +
        +    @Override
        +    public byte[] getSALT() {
        +        return SALT;
        +    }
        +
        +    @Override
        +    public String getAlarmReceiverClassName() {
        +        return SampleAlarmReceiver.class.getName();
        +    }
        +}
        +
        + +

        Notice: You must update the {@code BASE64_PUBLIC_KEY} value +to be the public key belonging to your publisher account. You can find the key in the Developer +Console under your profile information. This is necessary even when testing +your downloads.

        + +

        Remember to declare the service in your manifest file:

        +
        +<application ...>
        +    <service android:name=".SampleDownloaderService" />
        +    ...
        +</application>
        +
        + + + +

        Implementing the alarm receiver

        + +

        In order to monitor the progress of the file downloads and restart the download if necessary, the +{@code DownloaderService} schedules an {@link android.app.AlarmManager#RTC_WAKEUP} alarm that +delivers an {@link android.content.Intent} to a {@link android.content.BroadcastReceiver} in your +application. You must define the {@link android.content.BroadcastReceiver} to call an API +from the Downloader Library that checks the status of the download and restarts +it if necessary.

        + +

        You simply need to override the {@link android.content.BroadcastReceiver#onReceive +onReceive()} method to call {@code +DownloaderClientMarshaller.startDownloadServiceIfRequired()}.

        + +

        For example:

        + +
        +public class SampleAlarmReceiver extends BroadcastReceiver {
        +    @Override
        +    public void onReceive(Context context, Intent intent) {
        +        try {
        +            DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent,
        +                    SampleDownloaderService.class);
        +        } catch (NameNotFoundException e) {
        +            e.printStackTrace();
        +        }      
        +    }
        +}
        +
        + +

        Notice that this is the class for which you must return the name +in your service's {@code getAlarmReceiverClassName()} method (see the previous section).

        + +

        Remember to declare the receiver in your manifest file:

        +
        +<application ...>
        +    <receiver android:name=".SampleAlarmReceiver" />
        +    ...
        +</application>
        +
        + + + +

        Starting the download

        + +

        The main activity in your application (the one started by your launcher icon) is +responsible for verifying whether the expansion files are already on the device and initiating +the download if they are not.

        + +

        Starting the download using the Downloader Library requires the following +procedures:

        + +
          +
        1. Check whether the files have been downloaded. +

          The Downloader Library includes some APIs in the {@code Helper} class to +help with this process:

          +
            +
          • {@code getExtendedAPKFileName(Context, c, boolean mainFile, int +versionCode)}
          • +
          • {@code doesFileExist(Context c, String fileName, long fileSize)}
          • +
          +

          For example, the sample app provided in the Apk Expansion package calls the +following method in the activity's {@link android.app.Activity#onCreate onCreate()} method to check +whether the expansion files already exist on the device:

          +
          +boolean expansionFilesDelivered() {
          +    for (XAPKFile xf : xAPKS) {
          +        String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsBase, xf.mFileVersion);
          +        if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
          +            return false;
          +    }
          +    return true;
          +}        
          +
          +

          In this case, each {@code XAPKFile} object holds the version number and file size of a known +expansion file and a boolean as to whether it's the main expansion file. (See the sample +application's {@code SampleDownloaderActivity} class for details.)

          +

          If this method returns false, then the application must begin the download.

          +
        2. +
        3. Start the download by calling the static method {@code +DownloaderClientMarshaller.startDownloadServiceIfRequired(Context c, PendingIntent +notificationClient, Class<?> serviceClass)}. +

          The method takes the following parameters:

          +
            +
          • context: Your application's {@link android.content.Context}.
          • +
          • notificationClient: A {@link android.app.PendingIntent} to start your main +activity. This is used in the {@link android.app.Notification} that the {@code DownloaderService} +creates to show the download progress. When the user selects the notification, the system +invokes the {@link android.app.PendingIntent} you supply here and should open the activity +that shows the download progress (usually the same activity that started the download).
          • +
          • serviceClass: The {@link java.lang.Class} object for your implementation of +{@code DownloaderService}, required to start the service and begin the download if necessary.
          • +
          +

          The method returns an integer that indicates +whether or not the download is required. Possible values are:

          +
            +
          • {@code NO_DOWNLOAD_REQUIRED}: Returned if the files already +exist or a download is already in progress.
          • +
          • {@code LVL_CHECK_REQUIRED}: Returned if a license verification is +required in order to acquire the expansion file URLs.
          • +
          • {@code DOWNLOAD_REQUIRED}: Returned if the expansion file URLs are already known, +but have not been downloaded.
          • +
          +

          The behavior for {@code LVL_CHECK_REQUIRED} and {@code DOWNLOAD_REQUIRED} are essentially the +same and you normally don't need to be concerned about them. In your main activity that calls {@code +startDownloadServiceIfRequired()}, you can simply check whether or not the response is {@code +NO_DOWNLOAD_REQUIRED}. If the response is anything other than {@code NO_DOWNLOAD_REQUIRED}, +the Downloader Library begins the download and you should update your activity UI to +display the download progress (see the next step). If the response is {@code +NO_DOWNLOAD_REQUIRED}, then the files are available and your application can start.

          +

          For example:

          +
          +@Override
          +public void onCreate(Bundle savedInstanceState) {
          +    // Check if expansion files are available before going any further
          +    if (!expansionFilesDelivered()) {
          +        // Build an Intent to start this activity from the Notification
          +        Intent notifierIntent = new Intent(this, MainActivity.getClass());
          +        notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
          +                                Intent.FLAG_ACTIVITY_CLEAR_TOP);
          +        ...
          +        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
          +                notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
          +        
          +        // Start the download service (if required)
          +        int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
          +                        pendingIntent, SampleDownloaderService.class);
          +        // If download has started, initialize this activity to show download progress
          +        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
          +            // This is where you do set up to display the download progress (next step)
          +            ...
          +            return;
          +        } // If the download wasn't necessary, fall through to start the app
          +    }
          +    startApp(); // Expansion files are available, start the app
          +}
          +
          +
        4. +
        5. When the {@code startDownloadServiceIfRequired()} method returns anything other +than {@code NO_DOWNLOAD_REQUIRED}, create an instance of {@code IStub} by +calling {@code DownloaderClientMarshaller.CreateStub(IDownloaderClient client, Class<?> +downloaderService)}. The {@code IStub} provides a binding between your activity to the downloader +service such that your activity receives callbacks about the download progress. +

          In order to instantiate your {@code IStub} by calling {@code CreateStub()}, you must pass it +an implementation of the {@code IDownloaderClient} interface and your {@code DownloaderService} +implementation. The next section about Receiving download progress discusses +the {@code IDownloaderClient} interface, which you should usually implement in your {@link +android.app.Activity} class so you can update the activity UI when the download state changes.

          +

          We recommend that you call {@code +CreateStub()} to instantiate your {@code IStub} during your activity's {@link +android.app.Activity#onCreate onCreate()} method, after {@code startDownloadServiceIfRequired()} +starts the download.

          +

          For example, in the previous code sample for {@link android.app.Activity#onCreate +onCreate()}, you can respond to the {@code startDownloadServiceIfRequired()} result like this:

          +
          +        // Start the download service (if required)
          +        int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
          +                        pendingIntent, SampleDownloaderService.class);
          +        // If download has started, initialize activity to show progress
          +        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
          +            // Instantiate a member instance of IStub
          +            mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
          +                    SampleDownloaderService.class);
          +            // Inflate layout that shows download progress
          +            setContentView(R.layout.downloader_ui);
          +            return;
          +        }
          +
          + +

          After the {@link android.app.Activity#onCreate onCreate()} method returns, your activity +receives a call to {@link android.app.Activity#onResume onResume()}, which is where you should then +call {@code connect()} on the {@code IStub}, passing it your application's {@link +android.content.Context}. Conversely, you should call +{@code disconnect()} in your activity's {@link android.app.Activity#onStop onStop()} callback.

          +
          +@Override
          +protected void onResume() {
          +    if (null != mDownloaderClientStub) {
          +        mDownloaderClientStub.connect(this);
          +    }
          +    super.onResume();
          +}
          +
          +@Override
          +protected void onStop() {
          +    if (null != mDownloaderClientStub) {
          +        mDownloaderClientStub.disconnect(this);
          +    }
          +    super.onStop();
          +}
          +
          +

          Calling {@code connect()} on the {@code IStub} binds your activity to the {@code +DownloaderService} such that your activity receives callbacks regarding changes to the download +state through the {@code IDownloaderClient} interface.

          +
        6. +
        + + + +

        Receiving download progress

        + +

        To receive updates regarding the download progress and to interact with the {@code +DownloaderService}, you must implement the Downloader Library's {@code IDownloaderClient} interface. +Usually, the activity you use to start the download should implement this interface in order to +display the download progress and send requests to the service.

        + +

        The required interface methods for {@code IDownloaderClient} are:

        + +
        +
        {@code onServiceConnected(Messenger m)}
        +
        After you instantiate the {@code IStub} in your activity, you'll receive a call to this +method, which passes a {@link android.os.Messenger} object that's connected with your instance +of {@code DownloaderService}. To send requests to the service, such as to pause and resume +downloads, you must call {@code DownloaderServiceMarshaller.CreateProxy()} to receive the {@code +IDownloaderService} interface connected to the service. +

        A recommended implementation looks like this:

        +
        +private IDownloaderService mRemoteService;
        +...
        +
        +@Override
        +public void onServiceConnected(Messenger m) {
        +    mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
        +    mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
        +}
        +
        +

        With the {@code IDownloaderService} object initialized, you can send commands to the +downloader service, such as to pause and resume the download ({@code requestPauseDownload()} +and {@code requestContinueDownload()}).

        +
        +
        {@code onDownloadStateChanged(int newState)}
        +
        The download service calls this when a change in download state occurs, such as the +download begins or completes. +

        The newState value will be one of several possible values specified in +by one of the {@code IDownloaderClient} class's {@code STATE_*} constants.

        +

        To provide a useful message to your users, you can request a corresponding string +for each state by calling {@code Helpers.getDownloaderStringResourceIDFromState()}. This +returns the resource ID for one of the strings bundled with the Downloader +Library. For example, the string "Download paused because you are roaming" corresponds to {@code +STATE_PAUSED_ROAMING}.

        +
        {@code onDownloadProgress(DownloadProgressInfo progress)}
        +
        The download service calls this to deliver a {@code DownloadProgressInfo} object, +which describes various information about the download progress, including estimated time remaining, +current speed, overall progress, and total so you can update the download progress UI.
        +
        +

        Tip: For examples of these callbacks that update the download +progress UI, see the {@code SampleDownloaderActivity} in the sample app provided with the +Apk Expansion package.

        + +

        Some public methods for the {@code IDownloaderService} interface you might find useful are:

        + +
        +
        {@code requestPauseDownload()}
        +
        Pauses the download.
        +
        {@code requestContinueDownload()}
        +
        Resumes a paused download.
        +
        {@code setDownloadFlags(int flags)}
        +
        Sets user preferences for network types on which its OK to download the files. The +current implementation supports one flag, {@code FLAGS_DOWNLOAD_OVER_CELLULAR}, but you can add +others. By default, this flag is not enabled, so the user must be on Wi-Fi to download +expansion files. You might want to provide a user preference to enable downloads over +the cellular network. In which case, you can call: +
        +mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
        +
        +
        +
        + + + + +

        Using APKExpansionPolicy

        + +

        If you decide to build your own downloader service instead of using the Google Play +Downloader Library, you should still use the {@code +APKExpansionPolicy} that's provided in the License Verification Library. The {@code +APKExpansionPolicy} class is nearly identical to {@code ServerManagedPolicy} (available in the +Google Play License Verification Library) but includes additional handling for the APK expansion +file response extras.

        + +

        Note: If you do use the Downloader Library as discussed in the previous section, the +library performs all interaction with the {@code APKExpansionPolicy} so you don't have to use +this class directly.

        + +

        The class includes methods to help you get the necessary information about the available +expansion files:

        + +
          +
        • {@code getExpansionURLCount()}
        • +
        • {@code getExpansionURL(int index)}
        • +
        • {@code getExpansionFileName(int index)}
        • +
        • {@code getExpansionFileSize(int index)}
        • +
        + +

        For more information about how to use the {@code APKExpansionPolicy} when you're not +using the Downloader Library, see the documentation for Adding Licensing to Your App, +which explains how to implement a license policy such as this one.

        + + + + + + + +

        Reading the Expansion File

        + +

        Once your APK expansion files are saved on the device, how you read your files +depends on the type of file you've used. As discussed in the overview, your +expansion files can be any kind of file you +want, but are renamed using a particular file name format and are saved to +{@code <shared-storage>/Android/obb/<package-name>/}.

        + +

        Regardless of how you read your files, you should always first check that the external +storage is available for reading. There's a chance that the user has the storage mounted to a +computer over USB or has actually removed the SD card.

        + +

        Note: When your application starts, you should always check whether +the external storage space is available and readable by calling {@link +android.os.Environment#getExternalStorageState()}. This returns one of several possible strings +that represent the state of the external storage. In order for it to be readable by your +application, the return value must be {@link android.os.Environment#MEDIA_MOUNTED}.

        + + +

        Getting the file names

        + +

        As described in the overview, your APK expansion files are saved +using a specific file name format:

        + +
        +[main|patch].<expansion-version>.<package-name>.obb
        +
        + +

        To get the location and names of your expansion files, you should use the +{@link android.os.Environment#getExternalStorageDirectory()} and {@link +android.content.Context#getPackageName()} methods to construct the path to your files.

        + +

        Here's a method you can use in your application to get an array containing the complete path +to both your expansion files:

        + +
        +// The shared path to all app expansion files
        +private final static String EXP_PATH = "/Android/obb/";
        +
        +static String[] getAPKExpansionFiles(Context ctx, int mainVersion, int patchVersion) {
        +    String packageName = ctx.getPackageName();
        +    Vector<String> ret = new Vector<String>();
        +    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        +        // Build the full path to the app's expansion files
        +        File root = Environment.getExternalStorageDirectory();
        +        File expPath = new File(root.toString() + EXP_PATH + packageName);
        +
        +        // Check that expansion file path exists
        +        if (expPath.exists()) {
        +            if ( mainVersion > 0 ) {
        +                String strMainPath = expPath + File.separator + "main." +
        +                        mainVersion + "." + packageName + ".obb";
        +                File main = new File(strMainPath);
        +                if ( main.isFile() ) {
        +                        ret.add(strMainPath);
        +                }
        +            }
        +            if ( patchVersion > 0 ) {
        +                String strPatchPath = expPath + File.separator + "patch." +
        +                        mainVersion + "." + packageName + ".obb";
        +                File main = new File(strPatchPath);
        +                if ( main.isFile() ) {
        +                        ret.add(strPatchPath);
        +                }
        +            }
        +        }
        +    }
        +    String[] retArray = new String[ret.size()];
        +    ret.toArray(retArray);
        +    return retArray;
        +}
        +
        + +

        You can call this method by passing it your application {@link android.content.Context} +and the desired expansion file's version.

        + +

        There are many ways you could determine the expansion file version number. One simple way is to +save the version in a {@link android.content.SharedPreferences} file when the download begins, by +querying the expansion file name with the {@code APKExpansionPolicy} class's {@code +getExpansionFileName(int index)} method. You can then get the version code by reading the {@link +android.content.SharedPreferences} file when you want to access the expansion +file.

        + +

        For more information about reading from the shared storage, see the Data Storage +documentation.

        + + + +

        Using the APK Expansion Zip Library

        + + + +

        The Google Market Apk Expansion package includes a library called the APK +Expansion Zip Library (located in {@code +<sdk>/extras/google/google_market_apk_expansion/zip_file/}). This is an optional library that +helps you read your expansion +files when they're saved as ZIP files. Using this library allows you to easily read resources from +your ZIP expansion files as a virtual file system.

        + +

        The APK Expansion Zip Library includes the following classes and APIs:

        + +
        +
        {@code APKExpansionSupport}
        +
        Provides some methods to access expansion file names and ZIP files: + +
        +
        {@code getAPKExpansionFiles()}
        +
        The same method shown above that returns the complete file path to both expansion +files.
        +
        {@code getAPKExpansionZipFile(Context ctx, int mainVersion, int +patchVersion)}
        +
        Returns a {@code ZipResourceFile} representing the sum of both the main file and +patch file. That is, if you specify both the mainVersion and the +patchVersion, this returns a {@code ZipResourceFile} that provides read access to +all the data, with the patch file's data merged on top of the main file.
        +
        +
        + +
        {@code ZipResourceFile}
        +
        Represents a ZIP file on the shared storage and performs all the work to provide a virtual +file system based on your ZIP files. You can get an instance using {@code +APKExpansionSupport.getAPKExpansionZipFile()} or with the {@code ZipResourceFile} by passing it the +path to your expansion file. This class includes a variety of useful methods, but you generally +don't need to access most of them. A couple of important methods are: + +
        +
        {@code getInputStream(String assetPath)}
        +
        Provides an {@link java.io.InputStream} to read a file within the ZIP file. The +assetPath must be the path to the desired file, relative to +the root of the ZIP file contents.
        +
        {@code getAssetFileDescriptor(String assetPath)}
        +
        Provides an {@link android.content.res.AssetFileDescriptor} for a file within the +ZIP file. The assetPath must be the path to the desired file, relative to +the root of the ZIP file contents. This is useful for certain Android APIs that require an {@link +android.content.res.AssetFileDescriptor}, such as some {@link android.media.MediaPlayer} APIs.
        +
        +
        + +
        {@code APEZProvider}
        +
        Most applications don't need to use this class. This class defines a {@link +android.content.ContentProvider} that marshals the data from the ZIP files through a content +provider {@link android.net.Uri} in order to provide file access for certain Android APIs that +expect {@link android.net.Uri} access to media files. For example, this is useful if you want to +play a video with {@link android.widget.VideoView#setVideoURI VideoView.setVideoURI()}.

        +
        + +

        Reading from a ZIP file

        + +

        When using the APK Expansion Zip Library, reading a file from your ZIP usually requires the +following:

        + +
        +// Get a ZipResourceFile representing a merger of both the main and patch files
        +ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(appContext,
        +        mainVersion, patchVersion);
        +        
        +// Get an input stream for a known file inside the expansion file ZIPs
        +InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
        +
        + +

        The above code provides access to any file that exists in either your main expansion file or +patch expansion file, by reading from a merged map of all the files from both files. All you +need to provide the {@code getAPKExpansionFile()} method is your application {@code +android.content.Context} and the version number for both the main expansion file and patch +expansion file.

        + +

        If you'd rather read from a specific expansion file, you can use the {@code +ZipResourceFile} constructor with the path to the desired expansion file:

        + +
        +// Get a ZipResourceFile representing a specific expansion file
        +ZipResourceFile expansionFile = new ZipResourceFile(filePathToMyZip);
        +
        +// Get an input stream for a known file inside the expansion file ZIPs
        +InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
        +
        + +

        For more information about using this library for your expansion files, look at +the sample application's {@code SampleDownloaderActivity} class, which includes additional code to +verify the downloaded files using CRC. Beware that if you use this sample as the basis for +your own implementation, it requires that you declare the byte size of your expansion +files in the {@code xAPKS} array.

        + + + + +

        Testing Your Expansion Files

        + +

        Before publishing your application, there are two things you should test: Reading the +expansion files and downloading the files.

        + + +

        Testing file reads

        + +

        Before you upload your application to Google Play, you +should test your application's ability to read the files from the shared storage. All you need to do +is add the files to the appropriate location on the device shared storage and launch your +application:

        + +
          +
        1. On your device, create the appropriate directory on the shared storage where Google +Play will save your files. +

          For example, if your package name is {@code com.example.android}, you need to create +the directory {@code Android/obb/com.example.android/} on the shared storage space. (Plug in +your test device to your computer to mount the shared storage and manually create this +directory.)

          +
        2. +
        3. Manually add the expansion files to that directory. Be sure that you rename your files to +match the file name format that Google Play will use. +

          For example, regardless of the file type, the main expansion file for the {@code +com.example.android} application should be {@code main.0300110.com.example.android.obb}. +The version code can be whatever value you want. Just remember:

          +
            +
          • The main expansion file always starts with {@code main} and the patch file starts with +{@code patch}.
          • +
          • The package name always matches that of the APK to which the file is attached on +Google Play. +
          +
        4. +
        5. Now that the expansion file(s) are on the device, you can install and run your application to +test your expansion file(s).
        6. +
        + +

        Here are some reminders about handling the expansion files:

        +
          +
        • Do not delete or rename the {@code .obb} expansion files (even if you unpack +the data to a different location). Doing so will cause Google Play (or your app itself) to +repeatedly download the expansion file.
        • +
        • Do not save other data into your obb/ +directory. If you must unpack some data, save it into the location specified by {@link +android.content.Context#getExternalFilesDir getExternalFilesDir()}.
        • +
        + + + +

        Testing file downloads

        + +

        Because your application must sometimes manually download the expansion files when it first +opens, it's important that you test this process to be sure your application can successfully query +for the URLs, download the files, and save them to the device.

        + +

        To test your application's implementation of the manual download procedure, you must upload +your application to Google Play as a "draft" to make your expansion files available for +download:

        + +
          +
        1. Upload your APK and corresponding expansion files using the Google Play Developer +Console.
        2. +
        3. Fill in the necessary application details (title, screenshots, etc.). You can come back and +finalize these details before publishing your application. +

          Click the Save button. Do not click Publish. This saves +the application as a draft, such that your application is not published for Google Play users, +but the expansion files are available for you to test the download process.

        4. +
        5. Install the application on your test device using the Eclipse tools or {@code adb}.
        6. +
        7. Launch the app.
        8. +
        + +

        If everything works as expected, your application should begin downloading the expansion +files as soon as the main activity starts.

        + + + + +

        Updating Your Application

        + +

        One of the great benefits to using expansion files on Google Play is the ability to +update your application without re-downloading all of the original assets. Because Google Play +allows you to provide two expansion files with each APK, you can use the second file as a "patch" +that provides updates and new assets. Doing so avoids the +need to re-download the main expansion file which could be large and expensive for users.

        + +

        The patch expansion file is technically the same as the main expansion file and neither +the Android system nor Google Play perform actual patching between your main and patch expansion +files. Your application code must perform any necessary patches itself.

        + +

        If you use ZIP files as your expansion files, the APK Expansion Zip +Library that's included with the Apk Expansion package includes the ability to merge +your +patch file with the main expansion file.

        + +

        Note: Even if you only need to make changes to the patch +expansion file, you must still update the APK in order for Google Play to perform an update. +If you don't require code changes in the application, you should simply update the {@code versionCode} in the +manifest.

        + +

        As long as you don't change the main expansion file that's associated with the APK +in the Developer Console, users who previously installed your application will not +download the main expansion file. Existing users receive only the updated APK and the new patch +expansion file (retaining the previous main expansion file).

        + +

        Here are a few issues to keep in mind regarding updates to expansion files:

        + +
          +
        • There can be only two expansion files for your application at a time. One main expansion +file and one patch expansion file. During an update to a file, Google Play deletes the +previous version (and so must your application when performing manual updates).
        • +
        • When adding a patch expansion file, the Android system does not actually patch your +application or main expansion file. You must design your application to support the patch data. +However, the Apk Expansion package includes a library for using ZIP files +as expansion files, which merges the data from the patch file into the main expansion file so +you can easily read all the expansion file data.
        • +
        + + + + diff --git a/docs/html/guide/google/play/filters.jd b/docs/html/guide/google/play/filters.jd new file mode 100644 index 000000000000..3db9cb634d06 --- /dev/null +++ b/docs/html/guide/google/play/filters.jd @@ -0,0 +1,454 @@ +page.title=Filters on Google Play +@jd:body + +
        +
        + +

        Quickview

        +
          +
        • Google Play applies filters that control which Android-powered devices can access your +application when the user is visiting the store.
        • +
        • Filtering is determined by comparing device configurations that you declare in you app's +manifest file to the configurations defined by the device, as well as other factors.
        + +

        In this document

        + +
          +
        1. How Filters Work on Google Play
        2. +
        3. Filtering based on Manifest Elements +
            +
          1. Advanced manifest filters
          2. +
          +
        4. +
        5. Other Filters
        6. +
        7. Publishing Multiple APKs with Different Filters
        8. +
        + +

        See also

        +
          +
        1. Android Compatibility
        2. +
        3. <supports-gl-texture>
        4. +
        5. <supports-screens>
        6. +
        7. <uses-configuration>
        8. +
        9. <uses-feature>
        10. +
        11. <uses-library>
        12. +
        13. <uses-permission>
        14. +
        15. <uses-sdk>
        16. +
        + +
        + +
        + +

        Interested in publishing your app on Google Play?

        +

        Go to Google Play to create a publisher +account and upload your app.

        +
        + +
        +
        + + +

        When a user searches or browses on Google Play on an Android device, the results are filtered +based on which applications are compatible with that device. For example, if an application +requires a camera (as specified in the application manifest file), then Google Play will not show +the app on any device that does not have a camera.

        + +

        Declarations in the manifest file that are compared to the device's configuration is not the +only part of how applications are filtered. Filtering might also occur due to the user's country and +carrier, the presence or absence of a SIM card, and other factors.

        + +

        Changes to the Google Play filters are independent of changes to the Android platform itself. +This document is updated periodically to reflect any changes that affect the way Google Play +filters applications.

        + + +

        How Filters Work on Google Play

        + +

        Google Play uses the filter restrictions described below to determine +whether to show your application to a user who is browsing or searching for +applications from the Google Play app. When determining whether to display your app, +Google Play checks the device's hardware and software configuration, as well as it's +carrier, location, and other characteristics. It then compares those against the +restrictions and dependencies expressed by the application's +manifest file and publishing details. If the application is +compatible with the device according to the filter rules, Google Play displays the +application to the user. Otherwise, Google Play hides your application from search +results and category browsing, even if a user specifically requests +the app by clicking a deep link that points directly to the app's ID within Google Play..

        + +

        Note: When users browse the Google Play web site, they can see all published +applications. The Google Play web site compares the application requirements to each of the +user's registered devices for compatibility, though, and only allows them to install the application +if it's compatible with their device.

        + +

        You can use any combination of the available filters for your app. For example, you can set a +minSdkVersion requirement of "4" and set smallScreens="false" +in the app, then when uploading the app to Google Play you could target European countries (carriers) +only. Google Play's filters will thus prevent the application from being available on any device +that does not match all three of these requirements.

        + +

        All filtering restrictions are associated with an application's version and can +change between versions. For example, if a user has installed your application and you publish an +update that makes the app invisible to the user, the user will not see that an update is +available.

        + + +

        Filtering based on Manifest Elements

        + +

        Most filters are triggered by elements within an application's +manifest file, AndroidManifest.xml +(although not everything in the manifest file can trigger filtering). +Table 1 lists the manifest elements that you should use to trigger +filtering, and explains how the filtering for each element works.

        + +

        Table 1. Manifest elements that +trigger filtering on Google Play.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Manifest ElementFilter NameHow It Works
        <supports-screens> + Screen Size + +

        An application indicates the screen sizes that it is capable of supporting by +setting attributes of the <supports-screens> element. When +the application is published, Google Play uses those attributes to determine whether +to show the application to users, based on the screen sizes of their +devices.

        + +

        As a general rule, Google Play assumes that the platform on the device can adapt +smaller layouts to larger screens, but cannot adapt larger layouts to smaller +screens. Thus, if an application declares support for "normal" screen size only, +Google Play makes the application available to both normal- and large-screen devices, +but filters the application so that it is not available to small-screen +devices.

        + +

        If an application does not declare attributes for +<supports-screens>, Google Play uses the default values for those +attributes, which vary by API Level. Specifically:

        + +
          +
        • For applications that set either the android: +minSdkVersion or android: +targetSdkVersion to 3 or lower, the <supports-screens> element itself +is undefined and no attributes are available. In this case, Google Play assumes that +the application is designed for normal-size screens and shows the application to +devices that have normal or larger screens.

          + +
        • When the either the android: +minSdkVersion or android: +targetSdkVersion is set to 4 or higher, the default for all attributes is +"true". In this way, the application is considered to support all screen sizes by +default.
        • +
        + +

        Example 1
        + The manifest declares <uses-sdk android:minSdkVersion="3"> + and does not include a <supports-screens> element. + Result: Google Play will not show the app to a user of a + small-screen device, but will show it to users of normal and large-screen + devices, unless other filters apply.

        +

        Example 2
        +
        The manifest declares <uses-sdk android:minSdkVersion="3" + android:targetSdkVersion="4"> and does not include a + <supports-screens> element. + Result: Google Play will show the app to users on all + devices, unless other filters apply.

        +

        Example 3
        +
        The manifest declares <uses-sdk android:minSdkVersion="4"> + and does not include a <supports-screens> element. + Result: Google Play will show the app to all users, + unless other filters apply.

        +

        For more information on how to declare support for screen sizes in your + application, see <supports-screens> + and Supporting Multiple + Screens.

        +
        <uses-configuration> + Device + Configuration:
        + keyboard, navigation, touch screen

        An application can + request certain hardware features, and Google Play will show the app only on devices that have the required hardware.

        +

        Example 1
        +
        The manifest includes <uses-configuration android:reqFiveWayNav="true" />, and a user is searching for apps on a device that does not have a five-way navigational control. Result: Google Play will not show the app to the user.

        +

        Example 2
        +
        The manifest does not include a <uses-configuration> element. Result: Google Play will show the app to all users, unless other filters apply.

        +

        For more details, see <uses-configuration>.

        <uses-feature> + + Device Features
        + (name)

        An application can require certain device features to be +present on the device. This functionality was introduced in Android 2.0 (API +Level 5).

        +

        Example 1
        +
        The manifest includes <uses-feature +android:name="android.hardware.sensor.light" />, and a user +is searching for apps on a device that does not have a light sensor. +Result: Google Play will not show the app to the user.

        +

        Example 2
        +
        The manifest does not include a <uses-feature> +element. Result: Google Play will show the app to all users, +unless other filters apply.

        +

        For complete information, see <uses-feature> +.

        +

        Filtering based on implied features: In some cases, Google +Play interprets permissions requested through +<uses-permission> elements as feature requirements equivalent +to those declared in <uses-feature> elements. See <uses-permission>, +below.

        +
        OpenGL-ES + Version
        +(openGlEsVersion)

        An application can require that the device support a specific + OpenGL-ES version using the <uses-feature + android:openGlEsVersion="int"> attribute.

        +

        Example 1
        +
        An app + requests multiple OpenGL-ES versions by specifying openGlEsVersion multiple times in the + manifest. Result: Google Play assumes that the app requires the highest of the indicated versions.

        +

        Example 2
        +
        An app + requests OpenGL-ES version 1.1, and a user is searching for apps on a device that supports OpenGL-ES version 2.0. Result: Google Play will show the app to the user, unless other filters apply. If a + device reports that it supports OpenGL-ES version X, Google Play assumes that it + also supports any version earlier than X. +

        +

        Example 3
        +
        A user is searching for apps on a device that does not + report an OpenGL-ES version (for example, a device running Android 1.5 or earlier). Result: Google Play assumes that the device + supports only OpenGL-ES 1.0. Google Play will only show the user apps that do not specify openGlEsVersion, or apps that do not specify an OpenGL-ES version higher than 1.0.

        +

        Example 4
        +
        The manifest does not specify openGlEsVersion. Result: Google Play will show the app to all users, unless other filters apply.

        +

        For more details, see <uses-feature>.

        <uses-library>Software Libraries

        An application can require specific + shared libraries to be present on the device.

        +

        Example 1
        +
        An app requires the com.google.android.maps library, and a user is searching for apps on a device that does not have the com.google.android.maps library. Result: Google Play will not show the app to the user.

        +

        Example 2
        + The manifest does not include a <uses-library> element. Result: Google Play will show the app to all users, unless other filters apply.

        +

        For more details, see <uses-library>.

        <uses-permission> Strictly, Google Play does not filter based on +<uses-permission> elements. However, it does read the +elements to determine whether the application has hardware feature requirements +that may not have been properly declared in <uses-feature> +elements. For example, if an application requests the CAMERA +permission but does not declare a <uses-feature> element for +android.hardware.camera, Google Play considers that the +application requires a camera and should not be shown to users whose devices do +not offer a camera.

        +

        In general, if an application requests hardware-related permissions, +Google Play assumes that the application requires the underlying hardware +features, even though there might be no corresponding to +<uses-feature> declarations. Google Play then sets up +filtering based on the features implied by the <uses-feature> +declarations.

        +

        For a list of permissions that imply hardware features, see +the documentation for the <uses-feature> +element.

        +
        <uses-sdk>Minimum Framework Version (minSdkVersion)

        An application can require a minimum API level.

        +

        Example 1
        + The manifest includes <uses-sdk + android:minSdkVersion="3">, and the app uses APIs that were introduced in API Level 3. A user is searching for apps on a device that has API Level 2. Result: Google Play will not show the app to the user.

        +

        Example 2
        + The manifest does not include minSdkVersion, and the app uses APIs that were introduced in API Level 3. A user is searching for apps on a device that has API Level 2. Result: Google Play assumes that minSdkVersion is "1" and that the app is compatible with all versions of Android. Google Play shows the app to the user and allows the user to download the app. The app crashes at runtime.

        +

        Because you want to avoid this second scenario, we recommend that you always declare a minSdkVersion. For details, see android:minSdkVersion.

        Maximum Framework Version (maxSdkVersion)

        Deprecated. Android + 2.1 and later do not check or enforce the maxSdkVersion attribute, and + the SDK will not compile if maxSdkVersion is set in an app's manifest. For devices already + compiled with maxSdkVersion, Google Play will respect it and use it for + filtering.

        +

        Declaring maxSdkVersion is not recommended. For details, see android:maxSdkVersion.

        + + + +

        Advanced manifest filters

        + +

        In addition to the manifest elements in table 1, Google Play can also +filter applications based on the advanced manifest elements in table 2.

        + +

        These manifest elements and the filtering they trigger are for exceptional use-cases +only. These are designed for certain types of high-performance games and similar applications that +require strict controls on application distribution. Most applications should never use +these filters.

        + +

        Table 2. Advanced manifest elements for +Google Play filtering.

        + + + + + + + + + + +
        Manifest ElementSummary
        {@code +<compatible-screens>} +

        Google Play filters the application if the device screen size and density does not match +any of the screen configurations (declared by a {@code <screen>} element) in the {@code +<compatible-screens>} element.

        +

        Caution: Normally, you should not use +this manifest element. Using this element can dramatically +reduce the potential user base for your application, by excluding all combinations of screen size +and density that you have not listed. You should instead use the {@code +<supports-screens>} manifest element (described above in table +1) to enable screen compatibility mode for screen configurations you have not accounted for +with alternative resources.

        +
        {@code +<supports-gl-texture>} +

        Google Play filters the application unless one or more of the GL texture compression +formats supported by the application are also supported by the device.

        +
        + + + +

        Other Filters

        + +

        Google Play uses other application characteristics to determine whether to show or hide an application for a particular user on a given device, as described in the table below.

        + +

        Table 3. Application and publishing +characteristics that affect filtering on Google Play.

        + + + + + + + + + + +
        Filter Name How It Works
        Publishing Status

        Only published applications will appear in + searches and browsing within Google Play.

        Even if an app is unpublished, it can + be installed if users can see it in their Downloads area among their purchased, + installed, or recently uninstalled apps.

        If an application has been + suspended, users will not be able to reinstall or update it, even if it appears in their Downloads.

        Priced + Status

        Not all users can see paid apps. To show paid apps, a device +must have a SIM card and be running Android 1.1 or later, and it must be in a +country (as determined by SIM carrier) in which paid apps are available.

        Country / Carrier Targeting

        When you upload your app to + Google Play, you can select specific countries to target. The app will only + be visible to the countries (carriers) that you select, as follows:

        +
        • A device's country is determined based on the carrier, if a carrier is + available. If no carrier can be determined, Google Play tries to + determine the country based on IP.

        • Carrier is determined based on + the device's SIM (for GSM devices), not the current roaming carrier.

        +
        Native Platform

        An application that includes native + libraries that target a specific platform (ARM EABI v7 or x86, for example) are + visible only on devices that support that platform. For details about the NDK and using + native libraries, see What is the + Android NDK?

        Copy-Protected Applications

        To + copy protect an application, set copy protection to "On" when you configure publishing +options for your application. Google Play will not show copy-protected applications on +developer devices or unreleased devices.

        + + + +

        Publishing Multiple APKs with Different Filters

        + +

        Some specific Google Play filters allow you to publish multiple APKs for the same +application in order to provide a different APK to different device configurations. For example, if +you're creating a video game that uses high-fidelity graphic assets, you might want to create +two APKs that each support different texture compression formats. This way, you can reduce the +size of the APK file by including only the textures that are required for each device +configuration. Depending on each device's support for your texture compression formats, Google +Play will deliver it the APK that you've declared to support that device.

        + +

        Currently, Google Play allows you to publish multiple APKs for the same application only +when each APK provides different filters based on the following configurations:

        + + +

        All other filters still work the same as usual, but these three are the only filters that can +distinguish one APK from another within the same application listing on Google Play. For example, +you cannot publish multiple APKs for the same application if the APKs differ only based on +whether the device has a camera.

        + +

        Caution: Publishing multiple APKs for the same application is +considered an advanced feature and most application should publish only one +APK that supports a wide range of device configurations. Publishing multiple APKs +requires that you follow specific rules within your filters and that you pay extra attention to the +version codes for each APK to ensure proper update paths for each configuration.

        + +

        If you need more information about how to publish multiple APKs on Google Play, read Multiple APK Support.

        diff --git a/docs/html/guide/google/play/index.jd b/docs/html/guide/google/play/index.jd new file mode 100644 index 000000000000..b11bcdca8001 --- /dev/null +++ b/docs/html/guide/google/play/index.jd @@ -0,0 +1,16 @@ +page.title=Google Play APIs +page.landing=1 +page.landing.intro=When you ditribute your Android app using Google Play you have the opportunity to enhance your app's capabilities with services such as in-app billing and control your app distribution with advanced device filtering. +@jd:body + + +
        +
          +
        • Monetize with in-app billing
          Lorem ipsum dolor sit amet, soldum +consectetur adipiscing elit. Learn more »
        • +
        • Control your app distribution
          Lorem ipsum dolor sit amet, soldum consectetur +adipiscing elit. Learn more »
        • +
        • Protect from piracy
          Lorem ipsum dolor sit amet, soldum +consectetur adipiscing elit. Learn more »
        • +
        +
        \ No newline at end of file diff --git a/docs/html/guide/google/play/licensing/adding-licensing.jd b/docs/html/guide/google/play/licensing/adding-licensing.jd new file mode 100644 index 000000000000..49375c206b67 --- /dev/null +++ b/docs/html/guide/google/play/licensing/adding-licensing.jd @@ -0,0 +1,1071 @@ +page.title=Adding Licensing to Your App +parent.title=Application Licensing +parent.link=index.html +@jd:body + + + + + + + +

        After you've set up a publisher account and development environment (see Setting Up for Licensing), you are ready to add license verification to +your app with the License Verification Library (LVL).

        + +

        Adding license verification with the LVL involves these tasks:

        + +
          +
        1. Adding the licensing permission your application's manifest.
        2. +
        3. Implementing a Policy — you can choose one of the full implementations provided in the LVL or create your own.
        4. +
        5. Implementing an Obfuscator, if your {@code Policy} will cache any +license response data.
        6. +
        7. Adding code to check the license in your application's main +Activity.
        8. +
        9. Implementing a DeviceLimiter (optional and not recommended for +most applications).
        10. +
        + +

        The sections below describe these tasks. When you are done with the +integration, you should be able to compile your application successfully and you +can begin testing, as described in Setting Up the Test +Environment.

        + +

        For an overview of the full set of source files included in the LVL, see Summary of LVL Classes +and Interfaces.

        + + +

        Adding the Licensing Permission

        + +

        To use the Google Play application for sending a license check to the +server, your application must request the proper permission, +com.android.vending.CHECK_LICENSE. If your application does +not declare the licensing permission but attempts to initiate a license check, +the LVL throws a security exception.

        + +

        To request the licensing permission in your application, declare a <uses-permission> +element as a child of <manifest>, as follows:

        + +

        <uses-permission +android:name="com.android.vending.CHECK_LICENSE">

        + +

        For example, here's how the LVL sample application declares the permission: +

        + +
        <?xml version="1.0" encoding="utf-8"?>
        +
        +<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...">
        +    <!-- Devices >= 3 have version of Google Play that supports licensing. -->
        +    <uses-sdk android:minSdkVersion="3" />
        +    <!-- Required permission to check licensing. -->
        +    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
        +    ...
        +</manifest>
        +
        + +

        Note: Currently, you cannot declare the +CHECK_LICENSE permission in the LVL library project's manifest, +because the SDK Tools will not merge it into the manifests of dependent +applications. Instead, you must declare the permission in each dependent +application's manifest.

        + + +

        Implementing a Policy

        + + + +

        Google Play licensing service does not itself determine whether a +given user with a given license should be granted access to your application. +Rather, that responsibility is left to a {@code Policy} implementation that you provide +in your application.

        + +

        Policy is an interface declared by the LVL that is designed to hold your +application's logic for allowing or disallowing user access, based on the result +of a license check. To use the LVL, your application must provide an +implementation of {@code Policy}.

        + +

        The {@code Policy} interface declares two methods, allowAccess() and +processServerResponse(), which are called by a {@code LicenseChecker} +instance when processing a response from the license server. It also declares an +enum called LicenseResponse, which specifies the license response +value passed in calls to processServerResponse().

        + +
          +
        • processServerResponse() lets you preprocess the raw response +data received from the licensing server, prior to determining whether to grant +access. + +

          A typical implementation would extract some or all fields from the license +response and store the data locally to a persistent store, such as through +{@link android.content.SharedPreferences} storage, to ensure that the data is +accessible across application invocations and device power cycles. For example, +a {@code Policy} would maintain the timestamp of the last successful license check, the +retry count, the license validity period, and similar information in a +persistent store, rather than resetting the values each time the application is +launched.

          + +

          When storing response data locally, the {@code Policy} must ensure that the data is +obfuscated (see Implementing an Obfuscator, +below).

        • + +
        • allowAccess() determines whether to grant the user access to +your application, based on any available license response data (from the +licensing server or from cache) or other application-specific information. For +example, your implementation of allowAccess() could take into +account additional criteria, such as usage or other data retrieved from a +backend server. In all cases, an implementation of allowAccess() +should only return true if the user is licensed to use the +application, as determined by the licensing server, or if there is a transient +network or system problem that prevents the license check from completing. In +such cases, your implementation can maintain a count of retry responses and +provisionally allow access until the next license check is complete.
        • + +
        + +

        To simplify the process of adding licensing to your application and to +provide an illustration of how a {@code Policy} should be designed, the LVL includes +two full {@code Policy} implementations that you can use without modification or +adapt to your needs:

        + +
          +
        • ServerManagedPolicy, a flexible {@code Policy} +that uses server-provided settings and cached responses to manage access across +varied network conditions, and
        • +
        • StrictPolicy, which does not cache any response +data and allows access only if the server returns a licensed +response.
        • +
        + +

        For most applications, the use of ServerManagedPolicy is highly +recommended. ServerManagedPolicy is the LVL default and is integrated with +the LVL sample application.

        + + +

        Guidelines for custom policies

        + +

        In your licensing implementation, you can use one of the complete policies +provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a +custom policy. For any type of custom policy, there are several important design +points to understand and account for in your implementation.

        + +

        The licensing server applies general request limits to guard against overuse +of resources that could result in denial of service. When an application exceeds +the request limit, the licensing server returns a 503 response, which gets +passed through to your application as a general server error. This means that no +license response will be available to the user until the limit is reset, which +can affect the user for an indefinite period.

        + +

        If you are designing a custom policy, we recommend that the {@code Policy}: +

          + +
        1. Caches (and properly obfuscates) the most recent successful license response +in local persistent storage.
        2. +
        3. Returns the cached response for all license checks, for as long as the +cached response is valid, rather than making a request to the licensing server. +Setting the response validity according to the server-provided VT +extra is highly recommended. See Server Response Extras +for more information.
        4. +
        5. Uses an exponential backoff period, if retrying any requests the result in +errors. Note that the Google Play client automatically retries failed +requests, so in most cases there is no need for your {@code Policy} to retry them.
        6. +
        7. Provides for a "grace period" that allows the user to access your +application for a limited time or number of uses, while a license check is being +retried. The grace period benefits the user by allowing access until the next +license check can be completed successfully and it benefits you by placing a +hard limit on access to your application when there is no valid license response +available.
        8. +
        + +

        Designing your {@code Policy} according to the guidelines listed above is critical, +because it ensures the best possible experience for users while giving you +effective control over your application even in error conditions.

        + +

        Note that any {@code Policy} can use settings provided by the licensing server to +help manage validity and caching, retry grace period, and more. Extracting the +server-provided settings is straightforward and making use of them is highly +recommended. See the ServerManagedPolicy implementation for an example of how to +extract and use the extras. For a list of server settings and information about +how to use them, see Server Response +Extras.

        + +

        ServerManagedPolicy

        + + + +

        The LVL includes a full and recommended implementation of the {@code Policy} +interface called ServerManagedPolicy. The implementation is integrated with the +LVL classes and serves as the default {@code Policy} in the library.

        + +

        ServerManagedPolicy provides all of the handling for license and retry +responses. It caches all of the response data locally in a +{@link android.content.SharedPreferences} file, obfuscating it with the +application's {@code Obfuscator} implementation. This ensures that the license response +data is secure and persists across device power cycles. ServerManagedPolicy +provides concrete implementations of the interface methods +processServerResponse() and allowAccess() and also +includes a set of supporting methods and types for managing license +responses.

        + +

        Importantly, a key feature of ServerMangedPolicy is its use of +server-provided settings as the basis for managing licensing across an +application's refund period and through varying network and error conditions. +When an application contacts the Google Play server for a license check, the +server appends several settings as key-value pairs in the extras field of certain +license response types. For example, the server provides recommended values for the +application's license validity period, retry grace period, and maximum allowable +retry count, among others. ServerManagedPolicy extracts the values from the +license response in its processServerResponse() method and checks +them in its allowAccess() method. For a list of the server-provided +settings used by ServerManagedPolicy, see Server Response +Extras.

        + +

        For convenience, best performance, and the benefit of using license settings +from the Google Play server, using ServerManagedPolicy as your +licensing {@code Policy} is strongly recommended.

        + +

        If you are concerned about the security of license response data that is +stored locally in {@link android.content.SharedPreferences}, you can use a stronger obfuscation +algorithm or design a stricter {@code Policy} that does not store license data. The LVL +includes an example of such a {@code Policy} — see StrictPolicy for more information.

        + +

        To use ServerManagedPolicy, simply import it to your Activity, create an +instance, and pass a reference to the instance when constructing your +{@code LicenseChecker}. See Instantiate LicenseChecker and +LicenseCheckerCallback for more information.

        + +

        StrictPolicy

        + +

        The LVL includes an alternative full implementation of the {@code Policy} interface +called StrictPolicy. The StrictPolicy implementation provides a more restrictive +Policy than ServerManagedPolicy, in that it does not allow the user to access +the application unless a license response is received from the server at the +time of access that indicates that the user is licensed.

        + +

        The principal feature of StrictPolicy is that it does not store any +license response data locally, in a persistent store. Because no data is stored, +retry requests are not tracked and cached responses can not be used to fulfill +license checks. The {@code Policy} allows access only if:

        + +
          +
        • The license response is received from the licensing server, and
        • +
        • The license response indicates that the user is licensed to access the +application.
        • +
        + +

        Using StrictPolicy is appropriate if your primary concern is to ensure that, +in all possible cases, no user will be allowed to access the application unless +the user is confirmed to be licensed at the time of use. Additionally, the +Policy offers slightly more security than ServerManagedPolicy — since +there is no data cached locally, there is no way a malicious user could tamper +with the cached data and obtain access to the application.

        + +

        At the same time, this {@code Policy} presents a challenge for normal users, since it +means that they won't be able to access the application when there is no network +(cell or Wi-Fi) connection available. Another side-effect is that your +application will send more license check requests to the server, since using a +cached response is not possible.

        + +

        Overall, this policy represents a tradeoff of some degree of user convenience +for absolute security and control over access. Consider the tradeoff carefully +before using this {@code Policy}.

        + +

        To use StrictPolicy, simply import it to your Activity, create an instance, +and pass a reference to it when constructing your {@code LicenseChecker}. See +Instantiate LicenseChecker and LicenseCheckerCallback +for more information.

        + +

        Implementing an Obfuscator

        + + + +

        A typical {@code Policy} implementation needs to save the license response data for +an application to a persistent store, so that it is accessible across +application invocations and device power cycles. For example, a {@code Policy} would +maintain the timestamp of the last successful license check, the retry count, +the license validity period, and similar information in a persistent store, +rather than resetting the values each time the application is launched. The +default {@code Policy} included in the LVL, ServerManagedPolicy, stores license response +data in a {@link android.content.SharedPreferences} instance, to ensure that the +data is persistent.

        + +

        Because the {@code Policy} will use stored license response data to determine whether +to allow or disallow access to the application, it must ensure that any +stored data is secure and cannot be reused or manipulated by a root user on a +device. Specifically, the {@code Policy} must always obfuscate the data before storing +it, using a key that is unique for the application and device. Obfuscating using +a key that is both application-specific and device-specific is critical, because +it prevents the obfuscated data from being shared among applications and +devices.

        + +

        The LVL assists the application with storing its license response data in a +secure, persistent manner. First, it provides an {@code Obfuscator} +interface that lets your application supply the obfuscation algorithm of its +choice for stored data. Building on that, the LVL provides the helper class +PreferenceObfuscator, which handles most of the work of calling the +application's {@code Obfuscator} class and reading and writing the obfuscated data in a +{@link android.content.SharedPreferences} instance.

        + +

        The LVL provides a full {@code Obfuscator} implementation called +AESObfuscator that uses AES encryption to obfuscate data. You can +use AESObfuscator in your application without modification or you +can adapt it to your needs. For more information, see the next section.

        + + +

        AESObfuscator

        + +

        The LVL includes a full and recommended implementation of the {@code Obfuscator} +interface called AESObfuscator. The implementation is integrated with the +LVL sample application and serves as the default {@code Obfuscator} in the library.

        + +

        AESObfuscator provides secure obfuscation of data by using AES to +encrypt and decrypt the data as it is written to or read from storage. +The {@code Obfuscator} seeds the encryption using three data fields provided +by the application:

        + +
          +
        1. A salt — an array of random bytes to use for each (un)obfuscation.
        2. +
        3. An application identifier string, typically the package name of the application.
        4. +
        5. A device identifier string, derived from as many device-specific sources +as possible, so as to make it as unique.
        6. +
        + +

        To use AESObfuscator, first import it to your Activity. Declare a private +static final array to hold the salt bytes and initialize it to 20 randomly +generated bytes.

        + +
            ...
        +    // Generate 20 random bytes, and put them here.
        +    private static final byte[] SALT = new byte[] {
        +     -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
        +     -45, 77, -117, -36, -113, -11, 32, -64, 89
        +     };
        +    ...
        +
        + +

        Next, declare a variable to hold a device identifier and generate a value for +it in any way needed. For example, the sample application included in the LVL +queries the system settings for the +android.Settings.Secure.ANDROID_ID, which is unique to each device. +

        + +

        Note that, depending on the APIs you use, your application might need to +request additional permissions in order to acquire device-specific information. +For example, to query the {@link android.telephony.TelephonyManager} to obtain +the device IMEI or related data, the application will also need to request the +android.permission.READ_PHONE_STATE permission in its manifest.

        + +

        Before requesting new permissions for the sole purpose of acquiring +device-specific information for use in your {@code Obfuscator}, consider +how doing so might affect your application or its filtering on Google Play +(since some permissions can cause the SDK build tools to add +the associated <uses-feature>).

        + +

        Finally, construct an instance of AESObfuscator, passing the salt, +application identifier, and device identifier. You can construct the instance +directly, while constructing your {@code Policy} and {@code LicenseChecker}. For example:

        + +
            ...
        +    // Construct the LicenseChecker with a Policy.
        +    mChecker = new LicenseChecker(
        +        this, new ServerManagedPolicy(this,
        +            new AESObfuscator(SALT, getPackageName(), deviceId)),
        +        BASE64_PUBLIC_KEY  // Your public licensing key.
        +        );
        +    ...
        +
        + +

        For a complete example, see MainActivity in the LVL sample application.

        + + +

        Checking the License from an Activity

        + +

        Once you've implemented a {@code Policy} for managing access to your application, the +next step is to add a license check to your application, which initiates a query +to the licensing server if needed and manages access to the application based on +the license response. All of the work of adding the license check and handling +the response takes place in your main {@link android.app.Activity} source file. +

        + +

        To add the license check and handle the response, you must:

        + +
          +
        1. Add imports
        2. +
        3. Implement LicenseCheckerCallback as a private inner class
        4. +
        5. Create a Handler for posting from LicenseCheckerCallback to the UI thread
        6. +
        7. Instantiate LicenseChecker and LicenseCheckerCallback
        8. +
        9. Call checkAccess() to initiate the license check
        10. +
        11. Embed your public key for licensing
        12. +
        13. Call your LicenseChecker's onDestroy() method to close IPC connections.
        14. +
        + +

        The sections below describe these tasks.

        + +

        Overview of license check and response

        + + + +

        In most cases, you should add the license check to your application's main +{@link android.app.Activity}, in the {@link android.app.Activity#onCreate onCreate()} method. This +ensures that when the user launches your application directly, the license check +will be invoked immediately. In some cases, you can add license checks in other +locations as well. For example, if your application includes multiple Activity +components that other applications can start by {@link android.content.Intent}, +you could add license checks in those Activities.

        + +

        A license check consists of two main actions:

        + +
          +
        • A call to a method to initiate the license check — in the LVL, this is +a call to the checkAccess() method of a {@code LicenseChecker} object that +you construct.
        • +
        • A callback that returns the result of the license check. In the LVL, this is +a LicenseCheckerCallback interface that you implement. The +interface declares two methods, allow() and +dontAllow(), which are invoked by the library based on to the +result of the license check. You implement these two methods with whatever logic +you need, to allow or disallow the user access to your application. Note that +these methods do not determine whether to allow access — that +determination is the responsibility of your {@code Policy} implementation. Rather, these +methods simply provide the application behaviors for how to allow and +disallow access (and handle application errors). +

          The allow() and dontAllow() methods do provide a "reason" +for their response, which can be one of the {@code Policy} values, {@code LICENSED}, +{@code NOT_LICENSED}, or {@code RETRY}. In particular, you should handle the case in which +the method receives the {@code RETRY} response for {@code dontAllow()} and provide the user with an +"Retry" button, which might have happened because the service was unavailable during the +request.

        • +
        + +
        + + +
        Figure 6. Overview of a +typical license check interaction.
        +
        + +

        The diagram above illustrates how a typical license check takes place:

        + +
          +
        1. Code in the application's main Activity instantiates {@code LicenseCheckerCallback} +and {@code LicenseChecker} objects. When constructing {@code LicenseChecker}, the code passes in +{@link android.content.Context}, a {@code Policy} implementation to use, and the +publisher account's public key for licensing as parameters.
        2. +
        3. The code then calls the checkAccess() method on the +{@code LicenseChecker} object. The method implementation calls the {@code Policy} to determine +whether there is a valid license response cached locally, in +{@link android.content.SharedPreferences}. +
            +
          • If so, the checkAccess() implementation calls + allow().
          • +
          • Otherwise, the {@code LicenseChecker} initiates a license check request that is sent + to the licensing server.
          • +
          + +

          Note: The licensing server always returns +LICENSED when you perform a license check of a draft application.

          +
        4. +
        5. When a response is received, {@code LicenseChecker} creates a LicenseValidator that +verifies the signed license data and extracts the fields of the response, then +passes them to your {@code Policy} for further evaluation. +
            +
          • If the license is valid, the {@code Policy} caches the response in +{@link android.content.SharedPreferences} and notifies the validator, which then calls the +allow() method on the {@code LicenseCheckerCallback} object.
          • +
          • If the license not valid, the {@code Policy} notifies the validator, which calls +the dontAllow() method on {@code LicenseCheckerCallback}.
          • +
          +
        6. +
        7. In case of a recoverable local or server error, such as when the network is +not available to send the request, {@code LicenseChecker} passes a {@code RETRY} response to +your {@code Policy} object's processServerResponse() method. +

          Also, both the {@code allow()} and {@code dontAllow()} callback methods receive a +reason argument. The {@code allow()} method's reason is usually {@code +Policy.LICENSED} or {@code Policy.RETRY} and the {@code dontAllow()} reason is usually {@code +Policy.NOT_LICENSED} or {@code Policy.RETRY}. These response values are useful so you can show +an appropriate response for the user, such as by providing a "Retry" button when {@code +dontAllow()} responds with {@code Policy.RETRY}, which might have been because the service was +unavailable.

        8. +
        9. In case of a application error, such as when the application attempts to +check the license of an invalid package name, {@code LicenseChecker} passes an error +response to the LicenseCheckerCallback's applicationError() +method.
        10. +
        + +

        Note that, in addition to initiating the license check and handling the +result, which are described in the sections below, your application also needs +to provide a Policy implementation and, if the {@code Policy} +stores response data (such as ServerManagedPolicy), an Obfuscator implementation.

        + + +

        Add imports

        + +

        First, open the class file of the application's main Activity and import +{@code LicenseChecker} and {@code LicenseCheckerCallback} from the LVL package.

        + +
            import com.android.vending.licensing.LicenseChecker;
        +    import com.android.vending.licensing.LicenseCheckerCallback;
        + +

        If you are using the default {@code Policy} implementation provided with the LVL, +ServerManagedPolicy, import it also, together with the AESObfuscator. If you are +using a custom {@code Policy} or {@code Obfuscator}, import those instead.

        + +
            import com.android.vending.licensing.ServerManagedPolicy;
        +    import com.android.vending.licensing.AESObfuscator;
        + +

        Implement LicenseCheckerCallback as a private inner class

        + +

        {@code LicenseCheckerCallback} is an interface provided by the LVL for handling +result of a license check. To support licensing using the LVL, you must +implement {@code LicenseCheckerCallback} and +its methods to allow or disallow access to the application.

        + +

        The result of a license check is always a call to one of the +{@code LicenseCheckerCallback} methods, made based on the validation of the response +payload, the server response code itself, and any additional processing provided +by your {@code Policy}. Your application can implement the methods in any way needed. In +general, it's best to keep the methods simple, limiting them to managing UI +state and application access. If you want to add further processing of license +responses, such as by contacting a backend server or applying custom constraints, +you should consider incorporating that code into your {@code Policy}, rather than +putting it in the {@code LicenseCheckerCallback} methods.

        + +

        In most cases, you should declare your implementation of +{@code LicenseCheckerCallback} as a private class inside your application's main +Activity class.

        + +

        Implement the allow() and dontAllow() methods as +needed. To start with, you can use simple result-handling behaviors in the +methods, such as displaying the license result in a dialog. This helps you get +your application running sooner and can assist with debugging. Later, after you +have determined the exact behaviors you want, you can add more complex handling. +

        + +

        Some suggestions for handling unlicensed responses in +dontAllow() include:

        + +
          +
        • Display a "Try again" dialog to the user, including a button to initiate a +new license check if the reason supplied is {@code Policy.RETRY}.
        • +
        • Display a "Purchase this application" dialog, including a button that +deep-links the user to the application's details page on Google Play, from which the +use can purchase the application. For more information on how to set up such +links, see Linking to Your Products.
        • +
        • Display a Toast notification that indicates that the features of the +application are limited because it is not licensed.
        • +
        + +

        The example below shows how the LVL sample application implements +{@code LicenseCheckerCallback}, with methods that display the license check result in a +dialog.

        + +
        +private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
        +    public void allow(int reason) {
        +        if (isFinishing()) {
        +            // Don't update UI if Activity is finishing.
        +            return;
        +        }
        +        // Should allow user access.
        +        displayResult(getString(R.string.allow));
        +    }
        +
        +    public void dontAllow(int reason) {
        +        if (isFinishing()) {
        +            // Don't update UI if Activity is finishing.
        +            return;
        +        }
        +        displayResult(getString(R.string.dont_allow));
        +        
        +        if (reason == Policy.RETRY) {
        +            // If the reason received from the policy is RETRY, it was probably
        +            // due to a loss of connection with the service, so we should give the
        +            // user a chance to retry. So show a dialog to retry.
        +            showDialog(DIALOG_RETRY);
        +        } else {
        +            // Otherwise, the user is not licensed to use this app.
        +            // Your response should always inform the user that the application
        +            // is not licensed, but your behavior at that point can vary. You might
        +            // provide the user a limited access version of your app or you can
        +            // take them to Google Play to purchase the app.
        +            showDialog(DIALOG_GOTOMARKET);
        +        }
        +    }
        +}
        +
        + +

        Additionally, you should implement the applicationError() +method, which the LVL calls to let your application handle errors that are not +retryable. For a list of such errors, see Server +Response Codes in the Licensing Reference. You can implement +the method in any way needed. In most cases, the +method should log the error code and call dontAllow().

        + +

        Create a Handler for posting from LicenseCheckerCallback +to the UI thread

        + +

        During a license check, the LVL passes the request to the Google Play +application, which handles communication with the licensing server. The LVL +passes the request over asynchronous IPC (using {@link android.os.Binder}) so +the actual processing and network communication do not take place on a thread +managed by your application. Similarly, when the Google Play application +receives the result, it invokes a callback method over IPC, which in turn +executes in an IPC thread pool in your application's process.

        + +

        The {@code LicenseChecker} class manages your application's IPC communication with +the Google Play application, including the call that sends the request and +the callback that receives the response. {@code LicenseChecker} also tracks open license +requests and manages their timeouts.

        + +

        So that it can handle timeouts properly and also process incoming responses +without affecting your application's UI thread, {@code LicenseChecker} spawns a +background thread at instantiation. In the thread it does all processing of +license check results, whether the result is a response received from the server +or a timeout error. At the conclusion of processing, the LVL calls your +{@code LicenseCheckerCallback} methods from the background thread.

        + +

        To your application, this means that:

        + +
          +
        1. Your {@code LicenseCheckerCallback} methods will be invoked, in many cases, from a +background thread.
        2. +
        3. Those methods won't be able to update state or invoke any processing in the +UI thread, unless you create a Handler in the UI thread and have your callback +methods post to the Handler.
        4. +
        + +

        If you want your {@code LicenseCheckerCallback} methods to update the UI thread, +instantiate a {@link android.os.Handler} in the main Activity's +{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, +as shown below. In this example, the LVL sample application's +{@code LicenseCheckerCallback} methods (see above) call displayResult() to +update the UI thread through the Handler's +{@link android.os.Handler#post(java.lang.Runnable) post()} method.

        + +
        private Handler mHandler;
        +
        +    @Override
        +    public void onCreate(Bundle savedInstanceState) {
        +        ...
        +        mHandler = new Handler();
        +    }
        +
        + +

        Then, in your {@code LicenseCheckerCallback} methods, you can use Handler methods to +post Runnable or Message objects to the Handler. Here's how the sample +application included in the LVL posts a Runnable to a Handler in the UI thread +to display the license status.

        + +
            private void displayResult(final String result) {
        +        mHandler.post(new Runnable() {
        +            public void run() {
        +                mStatusText.setText(result);
        +                setProgressBarIndeterminateVisibility(false);
        +                mCheckLicenseButton.setEnabled(true);
        +            }
        +        });
        +    }
        +
        + +

        Instantiate LicenseChecker and LicenseCheckerCallback

        + +

        In the main Activity's +{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, +create private instances of LicenseCheckerCallback and {@code LicenseChecker}. You must +instantiate {@code LicenseCheckerCallback} first, because you need to pass a reference +to that instance when you call the constructor for {@code LicenseChecker}.

        + +

        When you instantiate {@code LicenseChecker}, you need to pass in these parameters:

        + +
          +
        • The application {@link android.content.Context}
        • +
        • A reference to the {@code Policy} implementation to use for the license check. In +most cases, you would use the default {@code Policy} implementation provided by the LVL, +ServerManagedPolicy.
        • +
        • The String variable holding your publisher account's public key for +licensing.
        • +
        + +

        If you are using ServerManagedPolicy, you won't need to access the class +directly, so you can instantiate it in the {@code LicenseChecker} constructor, +as shown in the example below. Note that you need to pass a reference to a new +Obfuscator instance when you construct ServerManagedPolicy.

        + +

        The example below shows the instantiation of {@code LicenseChecker} and +{@code LicenseCheckerCallback} from the onCreate() method of an Activity +class.

        + +
        public class MainActivity extends Activity {
        +    ...
        +    private LicenseCheckerCallback mLicenseCheckerCallback;
        +    private LicenseChecker mChecker;
        +
        +    @Override
        +    public void onCreate(Bundle savedInstanceState) {
        +        super.onCreate(savedInstanceState);
        +        ...
        +        // Construct the LicenseCheckerCallback. The library calls this when done.
        +        mLicenseCheckerCallback = new MyLicenseCheckerCallback();
        +
        +        // Construct the LicenseChecker with a Policy.
        +        mChecker = new LicenseChecker(
        +            this, new ServerManagedPolicy(this,
        +                new AESObfuscator(SALT, getPackageName(), deviceId)),
        +            BASE64_PUBLIC_KEY  // Your public licensing key.
        +            );
        +        ...
        +    }
        +}
        +
        + + +

        Note that {@code LicenseChecker} calls the {@code LicenseCheckerCallback} methods from the UI +thread only if there is valid license response cached locally. If the +license check is sent to the server, the callbacks always originate from the +background thread, even for network errors.

        + + +

        Call checkAccess() to initiate the license check

        + +

        In your main Activity, add a call to the checkAccess() method of the +{@code LicenseChecker} instance. In the call, pass a reference to your +{@code LicenseCheckerCallback} instance as a parameter. If you need to handle any +special UI effects or state management before the call, you might find it useful +to call checkAccess() from a wrapper method. For example, the LVL +sample application calls checkAccess() from a +doCheck() wrapper method:

        + +
            @Override
        +    public void onCreate(Bundle savedInstanceState) {
        +        super.onCreate(savedInstanceState);
        +        ...
        +        // Call a wrapper method that initiates the license check
        +        doCheck();
        +        ...
        +    }
        +    ...
        +    private void doCheck() {
        +        mCheckLicenseButton.setEnabled(false);
        +        setProgressBarIndeterminateVisibility(true);
        +        mStatusText.setText(R.string.checking_license);
        +        mChecker.checkAccess(mLicenseCheckerCallback);
        +    }
        +
        + + +

        Embed your public key for licensing

        + +

        For each publisher account, the Google Play service automatically +generates a 2048-bit RSA public/private key pair that is used exclusively for +licensing. The key pair is uniquely associated with the publisher account and is +shared across all applications that are published through the account. Although +associated with a publisher account, the key pair is not the same as +the key that you use to sign your applications (or derived from it).

        + +

        The Google Play publisher site exposes the public key for licensing to any +developer signed in to the publisher account, but it keeps the private key +hidden from all users in a secure location. When an application requests a +license check for an application published in your account, the licensing server +signs the license response using the private key of your account's key pair. +When the LVL receives the response, it uses the public key provided by the +application to verify the signature of the license response.

        + +

        To add licensing to an application, you must obtain your publisher account's +public key for licensing and copy it into your application. Here's how to find +your account's public key for licensing:

        + +
          +
        1. Go to the Google Play publisher site and sign in. +Make sure that you sign in to the account from which the application you are +licensing is published (or will be published).
        2. +
        3. In the account home page, locate the "Edit profile" link and click it.
        4. +
        5. In the Edit Profile page, locate the "Licensing" pane, shown below. Your +public key for licensing is given in the "Public key" text box.
        6. +
        + +

        To add the public key to your application, simply copy/paste the key string +from the text box into your application as the value of the String variable +BASE64_PUBLIC_KEY. When you are copying, make sure that you have +selected the entire key string, without omitting any characters.

        + +

        Here's an example from the LVL sample application:

        + +
            public class MainActivity extends Activity {
        +        private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
        +    ...
        +    }
        +
        + +

        Call your LicenseChecker's onDestroy() method +to close IPC connections

        + +

        Finally, to let the LVL clean up before your application +{@link android.content.Context} changes, add a call to the {@code LicenseChecker}'s +onDestroy() method from your Activity's +{@link android.app.Activity#onDestroy()} implementation. The call causes the +{@code LicenseChecker} to properly close any open IPC connection to the Google Play +application's ILicensingService and removes any local references to the service +and handler.

        + +

        Failing to call the {@code LicenseChecker}'s onDestroy() method +can lead to problems over the lifecycle of your application. For example, if the +user changes screen orientation while a license check is active, the application +{@link android.content.Context} is destroyed. If your application does not +properly close the {@code LicenseChecker}'s IPC connection, your application will crash +when the response is received. Similarly, if the user exits your application +while a license check is in progress, your application will crash when the +response is received, unless it has properly called the +{@code LicenseChecker}'s onDestroy() method to disconnect from the service. +

        + +

        Here's an example from the sample application included in the LVL, where +mChecker is the {@code LicenseChecker} instance:

        + +
            @Override
        +    protected void onDestroy() {
        +        super.onDestroy();
        +        mChecker.onDestroy();
        +        ...
        +    }
        +
        + +

        If you are extending or modifying {@code LicenseChecker}, you might also need to call +the {@code LicenseChecker}'s finishCheck() method, to clean up any open IPC +connections.

        + +

        Implementing a DeviceLimiter

        + +

        In some cases, you might want your {@code Policy} to limit the number of actual +devices that are permitted to use a single license. This would prevent a user +from moving a licensed application onto a number of devices and using the +application on those devices under the same account ID. It would also prevent a +user from "sharing" the application by providing the account information +associated with the license to other individuals, who could then sign in to that +account on their devices and access the license to the application.

        + +

        The LVL supports per-device licensing by providing a +DeviceLimiter interface, which declares a single method, +allowDeviceAccess(). When a LicenseValidator is handling a response +from the licensing server, it calls allowDeviceAccess(), passing a +user ID string extracted from the response.

        + +

        If you do not want to support device limitation, no work is +required — the {@code LicenseChecker} class automatically uses a default +implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter +is a "no-op" class whose allowDeviceAccess() method simply returns +a LICENSED response for all users and devices.

        + +
        +

        Caution: Per-device licensing is not recommended for +most applications because:

        +
          +
        • It requires that you provide a backend server to manage a users and devices +mapping, and
        • +
        • It could inadvertently result in a user being denied access to an +application that they have legitimately purchased on another device.
        • +
        +
        + + + + + + + + + + + +

        Obfuscating Your Code

        + +

        To ensure the security of your application, particularly for a paid +application that uses licensing and/or custom constraints and protections, it's +very important to obfuscate your application code. Properly obfuscating your +code makes it more difficult for a malicious user to decompile the application's +bytecode, modify it — such as by removing the license check — +and then recompile it.

        + +

        Several obfuscator programs are available for Android applications, including +ProGuard, which also offers +code-optimization features. The use of ProGuard or a similar program to obfuscate +your code is strongly recommended for all applications that use Google +Play Licensing.

        + +

        Publishing a Licensed Application

        + +

        When you are finished testing your license implementation, you are ready to +publish the application on Google Play. Follow the normal steps to prepare, sign, and then publish the application. +

        + +

        Removing Copy Protection

        + +

        After uploading your licensed application, remember to remove copy protection +from the application, if it is currently used. To check and remove copy +protection, sign in to the publisher site and go the application's upload +details page. In the Publishing options section, make sure that the Copy +Protection radio button selection is "Off".

        + + +

        Where to Get Support

        + +

        If you have questions or encounter problems while implementing or deploying +publishing in your applications, please use the support resources listed in the +table below. By directing your queries to the correct forum, you can get the +support you need more quickly.

        + +

        Table 2. Developer support resources +for Google Play Licensing Service.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Support TypeResourceRange of Topics
        Development and testing issuesGoogle Groups: android-developers +LVL download and integration, library projects, {@code Policy} +questions, user experience ideas, handling of responses, {@code Obfuscator}, IPC, test +environment setup
        Stack Overflow: http://stackoverflow.com/questions/tagged/android
        Accounts, publishing, and deployment issuesGoogle Play +Help ForumPublisher accounts, licensing key pair, test accounts, server +responses, test responses, application deployment and results
        Market +Licensing Support FAQ
        LVL issue trackerMarketlicensing +project issue trackerBug and issue reports related specifically to the LVL source code classes +and interface implementations
        + +

        For general information about how to post to the groups listed above, see Developer Forums document +in the Resources tab.

        + + diff --git a/docs/html/guide/google/play/licensing/index.jd b/docs/html/guide/google/play/licensing/index.jd new file mode 100644 index 000000000000..d393738bac17 --- /dev/null +++ b/docs/html/guide/google/play/licensing/index.jd @@ -0,0 +1,61 @@ +page.title=Application Licensing +@jd:body + + +

        Google Play offers a licensing service that lets you enforce licensing policies for +applications that you publish on Google Play. With Google Play Licensing, your application can +query Google Play at run time to obtain the licensing status for the current user, then allow or +disallow further use as appropriate.

        + +

        Using the service, you can apply a flexible licensing policy on an application-by-application +basis—each application can enforce licensing in the way most appropriate for it. If necessary, +an application can apply custom constraints based on the licensing status obtained from Google Play. +For example, an application can check the licensing status and then apply custom constraints +that allow the user to run it unlicensed for a specific validity period. An application can also +restrict use of the application to a specific device, in addition to any other constraints.

        + +

        The licensing service is a secure means of controlling access to your applications. When an +application checks the licensing status, the Google Play server signs the licensing status +response using a key pair that is uniquely associated with the publisher account. Your application +stores the public key in its compiled .apk file and uses it to verify the licensing +status response.

        + +

        Any application that you publish through Google Play can use the Google Play Licensing +service. No special account or registration is needed. Additionally, because the service uses no +dedicated framework APIs, you can add licensing to any application that uses a minimum API level of +3 or higher.

        + +

        Note: The Google Play Licensing service is primarily intended +for paid applications that wish to verify that the current user did in fact pay for the application +on Google Play. However, any application (including free apps) may use the licensing service +to initiate the download of an APK expansion file. In which case, the request that your application +sends to the licensing service is not to check whether the user paid for the app, but to request the +URL of the expansion files. For information about downloading expansion files for your application, +read the guide to APK Expansion Files.

        + + +

        To learn more about Google Play's application licensing service and start integrating it into +your applications, read the following documents:

        + +
        +
        Licensing +Overview
        +
        Describes how the service works and what a typical licensing implementation looks +like.
        +
        Setting Up for +Licensing
        +
        Explains how to set up your Google Play account, development environment, and +testing environment in order to add licensing to your app.
        +
        Adding +Licensing to Your App
        +
        Provides a step-by-step guide to add licensing verification to your application.
        +
        Licensing +Reference
        +
        Provides detailed information about the licensing library's classes and the service response +codes.
        +
        + + + + + diff --git a/docs/html/guide/google/play/licensing/licensing-reference.jd b/docs/html/guide/google/play/licensing/licensing-reference.jd new file mode 100644 index 000000000000..d3d522460ee3 --- /dev/null +++ b/docs/html/guide/google/play/licensing/licensing-reference.jd @@ -0,0 +1,439 @@ +page.title=Licensing Reference +parent.title=Application Licensing +parent.link=index.html +@jd:body + + + + + + +

        LVL Classes and Interfaces

        + +

        Table 1 lists all of the source files in the License Verification +Library (LVL) available through the Android SDK. All of the files are part of +the com.android.vending.licensing package.

        + +

        Table 1. Summary of LVL library +classes and interfaces.

        + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        CategoryNameDescription
        License check and resultLicenseCheckerClass that you instantiate (or subclass) to initiate a license check.
        LicenseCheckerCallbackInterface that you implement to handle result of the license check.
        PolicyPolicyInterface that you implement to determine whether to allow +access to the application, based on the license response.
        ServerManagedPolicyDefault {@code Policy} implementation. Uses settings provided by the +licensing server to manage local storage of license data, license validity, +retry.
        StrictPolicyAlternative {@code Policy} implementation. Enforces licensing based on a direct +license response from the server only. No caching or request retry.
        Data obfuscation
        (optional)
        ObfuscatorInterface that you implement if you are using a {@code Policy} (such as +ServerManagedPolicy) that caches license response data in a persistent store. +Applies an obfuscation algorithm to encode and decode data being written or +read.
        AESObfuscatorDefault Obfuscator implementation that uses AES encryption/decryption +algorithm to obfuscate/unobfuscate data.
        Device limitation
        (optional)
        DeviceLimiterInterface that you implement if you want to restrict use of an +application to a specific device. Called from LicenseValidator. Implementing +DeviceLimiter is not recommended for most applications because it requires a +backend server and may cause the user to lose access to licensed applications, +unless designed with care.
        NullDeviceLimiterDefault DeviceLimiter implementation that is a no-op (allows access to all +devices).
        Library core, no integration neededResponseDataClass that holds the fields of a license response.
        LicenseValidatorClass that decrypts and verifies a response received from the licensing +server.
        ValidationExceptionClass that indicates errors that occur when validating the integrity of data +managed by an Obfuscator.
        PreferenceObfuscatorUtility class that writes/reads obfuscated data to the system's +{@link android.content.SharedPreferences} store.
        ILicensingServiceOne-way IPC interface over which a license check request is passed to the +Google Play client.
        ILicenseResultListenerOne-way IPC callback implementation over which the application receives an +asynchronous response from the licensing server.
        +
        + + +

        Server Response Codes

        + +

        Table 2 lists all of the license response codes supported by the +licensing server. In general, an application should handle all of these response +codes. By default, the LicenseValidator class in the LVL provides all of the +necessary handling of these response codes for you.

        + +

        Table 2. Summary of response codes +returned by the Google Play server in a license response.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Response CodeDescriptionSigned?ExtrasComments
        {@code LICENSED}The application is licensed to the user. The user has purchased the +application or the application only exists as a draft.YesVTGT, GRAllow access according to {@code Policy} constraints.
        {@code LICENSED_OLD_KEY}The application is licensed to the user, but there is an updated application +version available that is signed with a different key. Yes VT, GT, GR, UTOptionally allow access according to {@code Policy} constraints. +

        Can indicate that the key pair used by the installed +application version is invalid or compromised. The application can allow access +if needed or inform the user that an upgrade is available and limit further use +until upgrade.

        +
        {@code NOT_LICENSED}The application is not licensed to the user.NoDo not allow access.
        {@code ERROR_CONTACTING_SERVER}Local error — the Google Play application was not able to reach the +licensing server, possibly because of network availability problems. NoRetry the license check according to {@code Policy} retry limits.
        {@code ERROR_SERVER_FAILURE}Server error — the server could not load the publisher account's key +pair for licensing.NoRetry the license check according to {@code Policy} retry limits. +
        {@code ERROR_INVALID_PACKAGE_NAME}Local error — the application requested a license check for a package +that is not installed on the device. No Do not retry the license check. +

        Typically caused by a development error.

        +
        {@code ERROR_NON_MATCHING_UID}Local error — the application requested a license check for a package +whose UID (package, user ID pair) does not match that of the requesting +application. No Do not retry the license check. +

        Typically caused by a development error.

        +
        {@code ERROR_NOT_MARKET_MANAGED}Server error — the application (package name) was not recognized by +Google Play. NoDo not retry the license check. +

        Can indicate that the application was not published +through Google Play or that there is an development error in the licensing +implementation.

        +
        + +

        Note: As documented in +Setting Up The Testing Environment, the response code can be manually +overridden for the application developer and any registered test users via the +Google Play publisher site. +

        +Additionally, as noted above, applications that are in draft mode (in other +words, applications that have been uploaded but have never been +published) will return {@code LICENSED} for all users, even if not listed as a test +user. Since the application has never been offered for download, it is assumed +that any users running it must have obtained it from an authorized channel for +testing purposes.

        + + + + +

        Server Response Extras

        + +

        To assist your application in managing access to the application across the application refund +period and provide other information, The licensing server includes several pieces of +information in the license responses. Specifically, the service provides recommended values for the +application's license validity period, retry grace period, maximum allowable retry count, and other +settings. If your application uses APK +expansion files, the response also includes the file names, sizes, and URLs. The server appends +the settings as key-value pairs in the license response "extras" field.

        + +

        Any {@code Policy} implementation can extract the extras settings from the license +response and use them as needed. The LVL default {@code Policy} implementation, {@code +ServerManagedPolicy}, serves as a working +implementation and an illustration of how to obtain, store, and use the +settings.

        + +

        Table 3. Summary of +license-management settings supplied by the Google Play server in a license +response.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        ExtraDescription
        {@code VT}License validity timestamp. Specifies the date/time at which the current +(cached) license response expires and must be rechecked on the licensing server. See the section +below about License validity period. +
        {@code GT}Grace period timestamp. Specifies the end of the period during which a +Policy may allow access to the application, even though the response status is +{@code RETRY}.

        The value is managed by the server, however a typical value would be 5 +or more days. See the section +below about Retry period and maximum retry count.

        {@code GR}Maximum retries count. Specifies how many consecutive {@code RETRY} license checks +the {@code Policy} should allow, before denying the user access to the application. +

        The value is managed by the server, however a typical value would be "10" or +higher. See the section +below about Retry period and maximum retry count.

        {@code UT}Update timestamp. Specifies the day/time when the most recent update to +this application was uploaded and published.

        The server returns this extra +only for {@code LICENSED_OLD_KEYS} responses, to allow the {@code Policy} to determine how much +time has elapsed since an update was published with new licensing keys before +denying the user access to the application.

        {@code FILE_URL1} or {@code FILE_URL2}The URL for an expansion file (1 is for the main file, 2 is the patch file). Use this to +download the file over HTTP.
        {@code FILE_NAME1} or {@code FILE_NAME2}The expansion file's name (1 is for the main file, 2 is the patch file). You must use this +name when saving the file on the device.
        {@code FILE_SIZE1} or {@code FILE_SIZE2}The size of the file in bytes (1 is for the main file, 2 is the patch file). Use this to +assist with downloading and to ensure that enough space is available on the device's shared +storage location before downloading.
        + + + +

        License validity period

        + +

        The Google Play licensing server sets a license validity period for all +downloaded applications. The period expresses the interval of time over which an +application's license status should be considered as unchanging and cacheable by +a licensing {@code Policy} in the application. The licensing server includes the +validity period in its response to all license checks, appending an +end-of-validity timestamp to the response as an extra under the key {@code VT}. A +{@code Policy} can extract the VT key value and use it to conditionally allow access to +the application without rechecking the license, until the validity period +expires.

        + +

        The license validity signals to a licensing {@code Policy} when it must recheck the +licensing status with the licensing server. It is not intended to imply +whether an application is actually licensed for use. That is, when an +application's license validity period expires, this does not mean that the +application is no longer licensed for use — rather, it indicates only that +the {@code Policy} must recheck the licensing status with the server. It follows that, +as long as the license validity period has not expired, it is acceptable for the +{@code Policy} to cache the initial license status locally and return the cached license +status instead of sending a new license check to the server.

        + +

        The licensing server manages the validity period as a means of helping the +application properly enforce licensing across the refund period offered by +Google Play for paid applications. It sets the validity period based on +whether the application was purchased and, if so, how long ago. Specifically, +the server sets a validity period as follows:

        + +
          +
        • For a paid application, the server sets the initial license validity period +so that the license response remains valid for as long as the application is +refundable. A licensing {@code Policy} in the application may cache the +result of the initial license check and does not need to recheck the license +until the validity period has expired.
        • +
        • When an application is no longer refundable, the server +sets a longer validity period — typically a number of days.
        • + + +
        • For a free application, the server sets the validity period to a very high +value (long.MAX_VALUE). This ensures that, provided the {@code Policy} has +cached the validity timestamp locally, it will not need to recheck the +license status of the application in the future.
        • +
        + +

        The {@code ServerManagedPolicy} implementation uses the extracted timestamp +(mValidityTimestamp) as a primary condition for determining whether +to recheck the license status with the server before allowing the user access to +the application.

        + + +

        Retry period and maximum retry count

        + +

        In some cases, system or network conditions can prevent an application's +license check from reaching the licensing server, or prevent the server's +response from reaching the Google Play client application. For example, the +user might launch an application when there is no cell network or data +connection available—such as when on an airplane—or when the +network connection is unstable or the cell signal is weak.

        + +

        When network problems prevent or interrupt a license check, the Google +Play client notifies the application by returning a {@code RETRY} response code to +the {@code Policy}'s processServerResponse() method. In the case of system +problems, such as when the application is unable to bind with Google Play's +{@code ILicensingService} implementation, the {@code LicenseChecker} library itself calls the +Policy processServerResonse() method with a {@code RETRY} response code. +

        + +

        In general, the {@code RETRY} response code is a signal to the application that an +error has occurred that has prevented a license check from completing. + +

        The Google Play server helps an application to manage licensing under +error conditions by setting a retry "grace period" and a recommended maximum +retries count. The server includes these values in all license check responses, +appending them as extras under the keys {@code GT} and {@code GR}.

        + +

        The application {@code Policy} can extract the {@code GT} and {@code GR} extras and use them to +conditionally allow access to the application, as follows:

        + +
          +
        • For a license check that results in a {@code RETRY} response, the {@code Policy} should +cache the {@code RETRY} response code and increment a count of {@code RETRY} responses.
        • +
        • The {@code Policy} should allow the user to access the application, provided that +either the retry grace period is still active or the maximum retries count has +not been reached.
        • +
        + +

        The {@code ServerManagedPolicy} uses the server-supplied {@code GT} and {@code GR} values as +described above. The example below shows the conditional handling of the retry +responses in the allow() method. The count of {@code RETRY} responses is +maintained in the processServerResponse() method, not shown.

        + + +
            
        +public boolean allowAccess() {
        +    long ts = System.currentTimeMillis();
        +    if (mLastResponse == LicenseResponse.LICENSED) {
        +        // Check if the LICENSED response occurred within the validity timeout.
        +        if (ts <= mValidityTimestamp) {
        +            // Cached LICENSED response is still valid.
        +            return true;
        +        }
        +    } else if (mLastResponse == LicenseResponse.RETRY &&
        +                ts < mLastResponseTime + MILLIS_PER_MINUTE) {
        +        // Only allow access if we are within the retry period or we haven't used up our
        +        // max retries.
        +        return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
        +    }
        +    return false;
        +}
        + diff --git a/docs/html/guide/google/play/licensing/overview.jd b/docs/html/guide/google/play/licensing/overview.jd new file mode 100644 index 000000000000..467a3a2c151c --- /dev/null +++ b/docs/html/guide/google/play/licensing/overview.jd @@ -0,0 +1,246 @@ +page.title=Licensing Overview +parent.title=Application Licensing +parent.link=index.html +@jd:body + + +
        +
        + +

        Quickview

        +
          +
        • Licensing allows you to verify your app was purchased from Google Play
        • +
        • Your app maintains control of how it enforces its licensing status
        • +
        • The service is free for all developers who publish on Google Play
        • +
        + +

        In this document

        +
          +
        1. License Responses are Secure
        2. +
        3. Licensing Verification Library
        4. +
        5. Requirements and Limitations
        6. +
        7. Replacement for Copy Protection
        8. +
        + +
        +
        + + +

        Google Play Licensing is a network-based service that lets an application query a trusted +Google Play licensing server to determine whether the application is licensed to the current +device user. The licensing service is based on the capability of the Google Play licensing server +to determine whether a given user is licensed to use a given application. Google Play considers a +user to be licensed if the user is a recorded purchaser of the application.

        + +

        The request starts when your application makes a request to a service hosted by +the Google Play client application. The Google Play application then sends a request to +the licensing server and receives the result. The Google Play application sends +the result to your application, which can allow or disallow further use of the +application as needed.

        + +

        Note: If a paid application has been uploaded to Google Play but +saved only as a draft application (the app is unpublished), the licensing server considers all users +to be licensed users of the application (because it's not even possible to purchase the app). +This exception is necessary in order for you to perform testing of your licensing +implementation.

        + + +
        + +

        Figure 1. Your application initiates a +license check through the License Verification Library and the Google Play +client, which handles communication with the Google Play server.

        +
        + + +

        To properly identify the user and determine the license status, the licensing server requires +information about the application and user—your application and the Google Play client work +together to assemble the information and the Google Play client passes it to the server.

        + +

        To help you add licensing to your application, the Android SDK provides a downloadable set of +library sources that you can include in your application project: the Google Market +Licensing package. The License Verification Library (LVL) is a library you can add to your +application that +handles all of the licensing-related communication with the Google Play licensing service. With +the LVL added to your application, your application can determine its licensing status for the +current user by simply calling a method and implementing a callback that receives the status +response.

        + +

        Your application does not query the licensing server +directly, but instead calls the Google Play client over remote IPC to +initiate a license request. In the license request:

        + +
          +
        • Your application provides: its package name, a nonce that is later used to +validate any response from the server, and a callback over which the +response can be returned asynchronously.
        • +
        • The Google Play client collects the necessary information about the user and the device, +such as the device's primary Google account username, IMSI, and other +information. It then sends the license check request to the server on behalf of +your application.
        • +
        • The Google Play server evaluates the request using all available information, attempting +to establish the user's identity to a sufficient level of confidence. The server +then checks the user identity against purchase records for your application and +returns a license response, which the Google Play client returns to your +application over the IPC callback.
        • +
        + +

        You can choose when, and how often, you want your application to check its +license and you have full control over how it handles the response, verifies the +signed response data, and enforces access controls.

        + +

        Notice that during a license check, your application does not manage any +network connections or use any licensing related APIs in the Android platform.

        + + + + +

        License Responses are Secure

        + +

        To ensure the integrity of each license query, the server signs the license +response data using an RSA key pair that is shared exclusively between the Google Play +server and you.

        + +

        The licensing service generates a single licensing key pair for each +publisher account and exposes the public key in your account's profile page. You must copy the +public key from the web site and embed it in your application source code. The server retains the +private key internally and uses it to sign license responses for the applications you +publish with that account.

        + +

        When your application receives a signed response, it uses the embedded public +key to verify the data. The use of public key cryptography in the licensing +service makes it possible for the application to detect responses that have been +tampered with or that are spoofed.

        + + + + +

        Licensing Verification Library

        + +

        The Android SDK provides a downloadable package called the Google Market Licensing package, +which includes the License Verification Library (LVL). The LVL greatly simplifies the process of +adding licensing to your application and helps ensure a more secure, robust implementation for your +application. The LVL provides internal classes that handle most of the standard operations of a +license query, such as contacting the Google Play client to initiate a license request and +verifying and validating the responses. It also exposes interfaces that let you easily plug in your +custom code for defining licensing policy and managing access as needed by your application. The key +LVL interfaces are:

        + +
        +
        {@code Policy}
        +
        Your implementation determines whether to allow access to the +application, based on the license response received from the server and any +other data available (such as from a backend server associated with your +application). The implementation can evaluate the various fields of the license +response and apply other constraints, if needed. The implementation also lets +you manage the handling of license checks that result in errors, such as network +errors.
        + +
        {@code LicenseCheckerCallback}
        +
        Your implementation manages access to the +application, based on the result of the {@code Policy} object's handling of the license +response. Your implementation can manage access in any way needed, including +displaying the license result in the UI or directing the user to purchase the +application (if not currently licensed).
        +
        + + +

        To help you get started with a {@code Policy}, the LVL provides two fully complete +{@code Policy} implementations that you can use without modification or adapt to your +needs:

        + +
        +
        {@code ServerManagedPolicy}
        +
        A flexible {@code Policy} +that uses settings provided by the licensing server to manage response caching +and access to the application while the device is offline (such as when the +user is on an airplane). For most applications, the use of +{@code ServerManagedPolicy} is highly recommended.
        + +
        {@code StrictPolicy}
        +
        A restrictive {@code Policy} that +does not cache any response data and allows the application access only +when the server returns a licensed response.
        +
        + +

        The LVL is available as a downloadable package of the Android SDK. The +package includes both the LVL itself and an example application that shows how +the library should be integrated with your application and how your application +should manage response data, UI interaction, and error conditions.

        + +

        The LVL sources are provided as an Android library project, which +means that you can maintain a single set of library sources and share them +across multiple applications. A full test environment is also available through +the SDK, so you can develop and test the licensing implementation in your +applications before publishing them, even if you don't have access to a +physical device.

        + + + + +

        Requirements and Limitations

        + +

        Google Play Licensing is designed to let you apply license controls to +applications that you publish through Google Play. The service is not +designed to let you control access to applications that are not published +through Google Play or that are run on devices that do not offer the Google +Play client.

        + +

        Here are some points to keep in mind as you implement licensing in your +application:

        + +
          +
        • An application can use the service only if the Google Play client is +installed on its host device and the device is running Android 1.5 (API level 3) +or higher.
        • +
        • To complete a license check, the licensing server must be accessible over +the network. You can implement license caching behaviors to manage access to your application when +there is no network connectivity.
        • +
        • The security of your application's licensing controls ultimately relies on +the design of your implementation itself. The service provides the building +blocks that let you securely check licensing, but the actual enforcement and +handling of the license are factors are up to you. By following the best +practices in the following documents, you can help ensure that your implementation will be +secure.
        • +
        • Adding licensing to an application does not affect the way the application +functions when run on a device that does not offer Google Play.
        • +
        • You can implement licensing controls for a free app, but only if you're using the service to +provide APK expansion files.
        • +
        + + + +

        Replacement for Copy Protection

        + +

        Google Play Licensing is a flexible, secure mechanism for controlling +access to your applications. It effectively replaces the Copy Protection +mechanism offered on Google Play and gives you wider distribution +potential for your applications.

        + +
          +
        • A limitation of the legacy Copy Protection mechanism on Google Play is +that applications using it can be installed only on compatible devices that +provide a secure internal storage environment. For example, a copy-protected +application cannot be downloaded from Google Play to a device that provides root +access, and the application cannot be installed to a device's SD card.
        • +
        • With Google Play licensing, you can move to a license-based model in +which access is not bound to the characteristics of the host device, but to your +publisher account on Google Play and the licensing policy that you define. +Your application can be installed and controlled on any compatible device on +any storage, including SD card.
        • +
        + +

        Although no license mechanism can completely prevent all unauthorized use, +the licensing service lets you control access for most types of normal usage, +across all compatible devices, locked or unlocked, that run Android 1.5 or +higher version of the platform.

        + +

        To begin adding application licensing to your application, continue to Setting Up for Licensing.

        + + + + + + diff --git a/docs/html/guide/google/play/licensing/setting-up.jd b/docs/html/guide/google/play/licensing/setting-up.jd new file mode 100644 index 000000000000..80a44192c754 --- /dev/null +++ b/docs/html/guide/google/play/licensing/setting-up.jd @@ -0,0 +1,701 @@ +page.title=Setting Up for Licensing +parent.title=Application Licensing +parent.link=index.html +@jd:body + + + + +

        Before you start adding license verification to your application, you need to set up your Google +Play publishing account, your development environment, and test accounts required to verify +your implementation.

        + + +

        Setting Up a Publisher Account

        + +

        If you don't already have a publisher account for Google Play, you need to register for one +using your Google account and agree to the terms of service on the Google Play publisher site:

        + +

        http://play.google.com/apps/publish +

        + +

        For more information, see Get Started with Publishing.

        + +

        If you already have a publisher account on Google Play, use your existing +account to set up licensing.

        + +

        Using your publisher account on Google Play, you can:

        + +
          +
        • Obtain a public key for licensing
        • +
        • Debug and test an application's licensing implementation, prior to +publishing the application
        • +
        • Publish the applications to which you have added licensing support
        • +
        + +

        Administrative settings for licensing

        + +

        You can manage several +administrative controls for Google Play licensing on the publisher site. The controls are available +in the Edit Profile page, in the "Licensing" panel, shown in figure 1. The controls +let you:

        + +
          +
        • Set up multiple "test accounts," identified by email address. The licensing +server allows users signed in to test accounts on a device or emulator to send +license checks and receive static test responses.
        • +
        • Obtain the account's public key for licensing. When you are implementing +licensing in an application, you must copy the public key string into the +application.
        • +
        • Configure static test responses that the server sends, when it receives a +license check for an application uploaded to the publisher account, from a user +signed in to the publisher account or a test account.
        • +
        + + + +

        Figure 1. The Licensing +panel of your account's Edit Profile page lets you manage administrative +settings for licensing.

        + +

        For more information about how to work with test accounts and static test +responses, see Setting Up a Testing Environment, below. + + + +

        Setting Up the Development Environment

        + +

        Setting up your environment for licensing involves these tasks:

        + +
          +
        1. Setting up the runtime environment for development
        2. +
        3. Downloading the LVL into your SDK
        4. +
        5. Setting up the Licensing Verification Library
        6. +
        7. Including the LVL library project in your application
        8. +
        + +

        The sections below describe these tasks. When you are done with setup, +you can begin Adding +Licensing to Your App.

        + +

        To get started, you need to set up a proper runtime environment on which +you can run, debug, and test your application's implementation of license +checking and enforcement.

        + + +

        Setting up the runtime environment

        + +

        As described earlier, applications check licensing status not by contacting +the licensing server directly, but by binding to a service provided by the +Google Play application and initiating a license check request. The Google +Play service then handles the direct communication with the licensing server +and finally routes the response back to your application. To debug and test +licensing in your application, you need to set up a runtime environment that +includes the necessary Google Play service, so that your application is able +to send license check requests to the licensing server.

        + +

        There are two types of runtime environment that you can use:

        + +
          +
        • An Android-powered device that includes the Google Play application, or
        • +
        • An Android emulator running the Google APIs Add-on, API level 8 (release 2) +or higher
        • +
        + +

        Running on a device

        + +

        To use an Android-powered device for +debugging and testing licensing, the device must:

        + +
          +
        • Run a compatible version of Android 1.5 or later (API level +3 or higher) platform, and
        • +
        • Run a system image on which the Google Play client application +is preinstalled.
        • +
        + +

        If Google Play is not preinstalled in the system image, your application won't +be able to communicate with the Google Play licensing server.

        + +

        For general information about how to set up a device for use in developing +Android applications, see Using Hardware Devices.

        + +

        Running on an Android emulator

        + +

        If you don't have a device available, you can use an Android emulator for debugging and testing +licensing.

        + +

        Because the Android platforms provided in the Android SDK do +not include Google Play, you need to download the Google APIs Add-On +platform, API level 8 (or higher), from the SDK repository. After downloading +the add-on, you need to create an AVD configuration that uses that system image. +

        + +

        The Google APIs Add-On does not include the full Google Play client. +However, it does provide:

        + +
          +
        • An Google Play background service that implements the +ILicensingService remote interface, so that your application can +send license checks over the network to the licensing server.
        • +
        • A set of underlying account services that let you add an a Google account on +the AVD and sign in using your publisher account or test account credentials. +

          Signing in using your publisher or test account enables you to debug and test +your application without having publish it. For more information see Signing in to an authorized account, below.

        • +
        + +

        Several versions of the Google APIs add-on are available through the SDK Manager, but only +the version for Android 2.2 and higher includes the necessary Google +Play services.

        + +

        To set up an emulator for adding licensing to an application, follow +these steps:

        + +
          +
        1. Launch the Android SDK Manager (available under the Eclipse Window +menu or by executing {@code <sdk>/tools/android sdk}).
        2. +
        3. Select and download Google APIs for the Android version you'd like to target +(must be Android 2.2 or higher).
        4. +
        5. When the download is complete, open the AVD Manager (available under the Eclipse +Window +menu or by executing {@code <sdk>/tools/android avd}).
        6. +
        7. Click +New and set the configuration details for the new AVD.
        8. +
        9. In the dialog that appears, assign a descriptive name to the AVD and then +use the Target menu to choose the Google APIs as +the system image to run on the new AVD. Set the other configuration details as +needed and then click Create AVD to finish. The SDK tools +create the new AVD configuration, which then appears in the list of available +Android Virtual Devices.
        10. +
        + +

        If you are not familiar with AVDs or how to use them, see Managing Virtual Devices.

        + +

        Updating your project configuration

        + +

        After you set up a runtime environment that meets the requirements described +above — either on an actual device or on an emulator — make sure to +update your application project or build scripts as needed, so that your compiled +.apk files that use licensing are deployed into that environment. +In particular, if you are developing in Eclipse, make sure that you set up a +Run/Debug Configuration that targets the appropriate device or AVD.

        + +

        You do not need to make any changes to your application's +build configuration, provided that the project is already configured to compile +against a standard Android 1.5 (API level 3) or higher library. For example: + +

          +
        • If you have an existing application that is compiled against +the Android 1.5 library, you do not need to make any changes to your +build configuration to support licensing. The build target meets the minimum +requirements for licensing, so you would continue building +against the same version of the Android platform.
        • + +
        • Similarly, if you are building against Android 1.5 (API level 3) but +are using an emulator running the Google APIs Add-On API 8 as the application's +runtime environment, there is no need to change your application's build +configuration.
        • +
        + +

        In general, adding licensing to an application should have no impact +whatsoever on the application's build configuration.

        + + +

        Downloading the LVL

        + +

        The License Verification Library (LVL) is a collection of helper classes that +greatly simplify the work that you need to do to add licensing to your +application. In all cases, we recommend that you download the LVL and use it as +the basis for the licensing implementation in your application.

        + +

        The LVL is available as a downloadable package of the Android SDK. The +package includes:

        + +
          +
        • The LVL sources, stored inside an Android library project.
        • +
        • An example application called "sample" that depends on the LVL library +project. The example illustrates how an application uses the library helper +classes to check and enforce licensing.
        • +
        + +

        To download the LVL package into your development environment, use the +Android SDK Manager. Launch the Android SDK Manager and then +select the Google Market Licensing package, as shown in figure 2. +Accept the terms and click Install Selected to begin the download.

        + + +

        Figure 2. The Licensing package contains the LVL and +the LVL sample application.

        + +

        When the download is complete, the Android SDK Manager installs both +the LVL library project and the example application into these directories:

        + +

        <sdk>/extras/google/market_licensing/library/ +  (the LVL library project)
        +<sdk>/extras/google/market_licensing/sample/  (the example +application)

        + +

        If you aren't familiar with how to download packess into your SDK, see the +Exploring the SDK +document.

        + + +

        Setting Up the Licensing Verification Library

        + +

        After downloading the LVL to your computer, you need to set it up in your +development environment, either as an Android library project or by +copying (or importing) the library sources directly into your existing +application package. In general, using the LVL as a library project is recommended, +since it lets you reuse your licensing code across multiple applications and +maintain it more easily over time. Note that the LVL is not designed to be +compiled separately and added to an application as a static .jar file.

        + +

        Moving the library sources to a new location

        + +

        Because you will be customizing the LVL sources to some extent, you should +make sure to move or copy the library sources (the entire +directory at <sdk>/market_licensing/library/) +to a working directory outside of the SDK. You should then use the relocated +sources as your working set. If you are using a source-code management +system, add and track the sources that are in the working location rather +than those in default location in the SDK.

        + +

        Moving the library sources is important is because, when you later update the +Licensing package, the SDK installs the new files to the same location as +the older files. Moving your working library files to a safe location ensures +that your work won't be inadvertently overwritten should you download a new +version of the LVL.

        + +

        Creating the LVL as a library project

        + + + +

        The recommended way of using the LVL is setting it up as a new Android +library project. A library project is a type of development project +that holds shared Android source code and resources. Other Android application +projects can reference the library project and, at build time, include its +compiled sources in their .apk files. In the context of licensing, +this means that you can do most of your licensing development once, in a library +project, then include the library sources in your various application projects. +In this way, you can easily maintain a uniform implementation of licensing +across all of your projects and maintain it centrally.

        + +

        The LVL is provided as a configured library project — once you have +downloaded it, you can start using it right away.

        + +

        If you are working in Eclipse with ADT, you need to add the LVL to your +workspace as a new development project, in the same way as you would a new +application project.

        + +
          +
        1. Use the New Project Wizard to create a new +project from existing sources. Select the LVL's library directory +(the directory containing the library's AndroidManifest.xml file) as the project +root.
        2. +
        3. When you are creating the library project, you can select any application +name, package, and set other fields as needed.
        4. +
        5. For the library's build target, select Android 1.5 (API level 3) or higher.
        6. +
        + +

        When created, the project is +predefined as a library project in its project.properties file, so +no further configuration is needed.

        + +

        For more information about how to create an application project or work with +library projects in Eclipse, see Managing Projects from +Eclipse with ADT.

        + + +

        Copying the LVL sources to your application

        + +

        As an alternative to adding the LVL as a library project, you can copy the +library sources directly into your application. To do so, copy (or import) the +LVL's library/src/com directory into your application's +src/ directory.

        + +

        If you add the LVL sources directly to your application, you can skip the +next section and start working with the library, as described in Adding +Licensing to Your App.

        + + +

        Including the LVL library project sources in your +application

        + +

        If you want to use the LVL sources as a library project, you need to add a +reference to the LVL library project in your application project properties. This tells +build tools to include the LVL library project sources in your application at +compile time. The process for adding a reference to a library project depends +on your development environment, as described below.

        + +

        If you are developing in Eclipse with ADT, you should already have added the +library project to your workspace, as described in the previous section. If you +haven't done that already, do it now before continuing.

        + +

        Next, open the application's project properties window, as shown below. +Select the "Android" properties group and click Add, then +choose the LVL library project (com_android_vending_licensing) and click +OK. For more information, see + +Managing Projects from Eclipse with ADT

        . + + + +

        Figure 3. If you are +working in Eclipse with ADT, you can add the LVL library project to your +application from the application's project properties.

        + + +

        If you are developing using the SDK command-line tools, navigate to the +directory containing your application project and open the +project.properties file. Add a line to the file that specifies the +android.library.reference.<n> key and the path to the +library. For example:

        + +
        android.library.reference.1=path/to/library_project
        + +

        Alternatively, you can use this command to update the project +properties, including the reference to the library project:

        + +
        android update lib-project
        +--target <target_ID> \
        +--path path/to/my/app_project \
        +--library path/to/my/library_project
        +
        + +

        For more information about working with library projects, +see +Setting up a Library Project.

        + + + + + + + + + + + + + + + + + + + + + +

        Setting Up the Testing Environment

        + +

        The Google Play publisher site provides configuration tools that let you +and others test licensing on your application before it is published. As you are +implementing licensing, you can make use of the publisher site tools to test +your application's Policy and handling of different licensing responses and +error conditions.

        + +

        The main components of the test environment for licensing include:

        + +
          +
        • A "Test response" configuration in your publisher account that lets you +set the static licensing response returned, when the server processes a +license check for an application uploaded to the publisher account, from a user +signed in to the publisher account or a test account.
        • +
        • An optional set of test accounts that will receive the static test +response when they check the license of an application that you have uploaded +(regardless whether the application is published or not).
        • +
        • A runtime environment for the application that includes the Google Play +application or Google APIs Add-On, on which the user is signed in to the +publisher account or one of the test accounts.
        • +
        + +

        Setting up the test environment properly involves:

        + +
          +
        1. Setting static test responses that are returned by the licensing server.
        2. +
        3. Setting up test accounts as needed.
        4. +
        5. Signing in properly to an emulator or device, before initiating a license check test.
        6. +
        + +

        The sections below provide more information.

        + + +

        Setting test responses for license checks

        + +

        Google Play provides a configuration setting in your publisher account +that lets you override the normal processing of a license check and return a +specified static response code. The setting is for testing only and applies +only to license checks for applications that you have uploaded, made by +any user signed in to an emulator or device using the credentials of the +publisher account or a registered test account. For other users, the server +always processes license checks according to normal rules.

        + +

        To set a test response for your account, sign in to your publisher account +and click "Edit Profile". In the Edit Profile page, locate the Test Response +menu in the Licensing panel, shown below. You can select from the full set of +valid server response codes to control the response or condition you want to +test in your application.

        + +

        In general, you should make sure to test your application's licensing +implementation with every response code available in the Test Response menu. +For a description of the codes, see Server +Response Codes in the Licensing Reference.

        + + +

        Figure 4. The Licensing +panel of your account's Edit Profile page, showing the Test Accounts field and the +Test Response menu.

        + +

        Note that the test response that you configure applies account-wide — +that is, it applies not to a single application, but to all +applications associated with the publisher account. If you are testing multiple +applications at once, changing the test response will affect all of those +applications on their next license check (if the user is signed in to +the emulator or device using the publisher account or a test account).

        + +

        Before you can successfully receive a test response for a license check, +you must sign in to the device or emulator on which the application +is installed, and from which it is querying the server. Specifically, you must +sign using either your publisher account or one of the test accounts that you +have set up. For more information about test accounts, see the next section.

        + +

        See Server +Response Codes for a list of +test responses available and their meanings.

        + + +

        Setting up test accounts

        + +

        In some cases, you might want to let multiple teams of developers test +licensing on applications that will ultimately be published through your +publisher account, but without giving them access to your publisher account's +sign-in credentials. To meet that need, the Google Play publisher site lets +you set up one or more optional test accounts — accounts that are +authorized to query the licensing server and receive static test responses from +your publisher account.

        + +

        Test accounts are standard Google accounts that you register on your +publisher account, such that they will receive the test response for +applications that you have uploaded. Developers can then sign in to their +devices or emulators using the test account credentials and initiate license +checks from installed applications. When the licensing server receives a license +check from a user of a test account, it returns the static test response +configured for the publisher account.

        + +

        Necessarily, there are limitations on the access and permissions given to +users signed in through test accounts, including:

        + +
          +
        • Test account users can query the licensing server only for applications that +are already uploaded to the publisher account.
        • +
        • Test account users do not have permission to upload applications to your +publisher account.
        • +
        • Test account users do not have permission to set the publisher account's +static test response.
        • +
        + +

        The table below summarizes the differences in capabilities, between the +publisher account, a test account, and any other account.

        + +

        Table 1. +Differences in account types for testing licensing.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Account TypeCan check license before upload?Can receive test response?Can set test response?
        Publisher accountYesYesYes
        Test accountNoYesNo
        OtherNoNoNo
        + +

        Registering test accounts on the publisher account

        + +

        To get started, you need to register each test account in your publisher +account. As shown in Figure 4, you +register test accounts in the Licensing panel of your publisher account's Edit +Profile page. Simply enter the accounts as a comma-delimited list and click +Save to save your profile changes.

        + +

        You can use any Google account as a test account. If you want to own and +control the test accounts, you can create the accounts yourself and distribute +the credentials to your developers or testers.

        + +

        Handling application upload and distribution for test +account users

        + +

        As mentioned above, users of test accounts can only receive static test +responses for applications that are uploaded to the publisher account. Since +those users do not have permission to upload applications, as the publisher you +will need to work with those users to collect apps for upload and distribute +uploaded apps for testing. You can handle collection and distribution in any way +that is convenient.

        + +

        Once an application is uploaded and becomes known to the licensing server, +developers and testers can continue modify the application in their local +development environment, without having to upload new versions. You only need to +upload a new version if the local application increments the +versionCode attribute in the manifest file.

        + +

        Distributing your public key to test account users

        + +

        The licensing server handles static test responses in the normal way, +including signing the license response data, adding extras parameters, and so +on. To support developers who are implementing licensing using test accounts, +rather than the publisher account, you will need to distribute +your public key to them. Developers without access to the publisher site do not +have access to your public key, and without the key they won't be able to +verify license responses.

        + +

        Note that if you decide to generate a new licensing key pair for your account +for some reason, you need to notify all users of test accounts. For +testers, you can embed the new key in the application package and distribute it +to users. For developers, you will need to distribute the new key to them +directly.

        + + +

        Signing in to an authorized account in the runtime +environment

        + +

        The licensing service is designed to determine whether a given user is +licensed to use a given application — during a license check, the Google +Play application gathers the user ID from the primary account on the system +and sends it to the server, together with the package name of the application +and other information. However, if there is no user information available, the +license check cannot succeed, so the Google Play application terminates the +request and returns an error to the application.

        + +

        During testing, to ensure that your application can successfully query the +licensing server, you must make sure that you sign in to an account on the +device or emulator using:

        + +
          +
        • The credentials of a publisher account, or
        • +
        • The credentials of a test account that is registered with a publisher +account
        • +
        + + + + +

        Signing in using a publisher account offers the advantage of letting your +applications receive static test responses even before the applications are +uploaded to the publisher site.

        + +

        If you are part of a larger organization or are working with external groups +on applications that will be published through your site, you will more likely +want to distribute test accounts instead, then use those to sign in during +testing.

        + +

        To sign in on a device or emulator, follow the steps below. The preferred +approach is to sign in as the primary account — however, if there are +other accounts already in use on the device or emulator, you can create an +additional account and sign in to it using the publisher or test account +credentials.

        + +
          +
        1. Open Settings > Accounts & sync
        2. +
        3. Select Add Account and choose to add a Google account. +
        4. +
        5. Select Next and then Sign in.
        6. +
        7. Enter the username and password of either the publisher account or a test +account that is registered in the publisher account.
        8. +
        9. Select Sign in. The system signs you in to the new +account.
        10. +
        + +

        Once you are signed in, you can begin testing licensing in your application +(if you have completed the LVL integration steps above). When your application +initiates a license check, it will receive a response containing the static test +response configured on the publisher account.

        + +

        Note that, if you are using an emulator, you will need to sign in to the +publisher account or test account each time you wipe data when restarting the +emulator.

        + +

        Once you've completed the setup procedures, continue to Adding Licensing to Your App.

        + + + diff --git a/docs/html/guide/google/play/publishing/multiple-apks.jd b/docs/html/guide/google/play/publishing/multiple-apks.jd new file mode 100644 index 000000000000..e41817e4520d --- /dev/null +++ b/docs/html/guide/google/play/publishing/multiple-apks.jd @@ -0,0 +1,643 @@ +page.title=Multiple APK Support + +@jd:body + +
        +
        + +

        Quickview

        +
          +
        • Simultaneously publish different APKs for different +device configurations
        • +
        • Different APKs are distributed to different devices based on filters declared in the +manifest file
        • +
        • You should publish multiple APKs only when it's not possible or reasonable to +support all desired devices with a single APK
        • +
        + +

        In this document

        +
          +
        1. Publishing Concepts +
            +
          1. Active APKs
          2. +
          3. Simple mode and advanced mode
          4. +
          +
        2. +
        3. How Multiple APKs Work +
            +
          1. Supported filters
          2. +
          3. Rules for multiple APKs
          4. +
          +
        4. +
        5. Creating Multiple APKs +
            +
          1. Assigning version codes
          2. +
          +
        6. +
        7. Using a Single APK Instead +
            +
          1. Supporting multiple GL textures
          2. +
          3. Supporting multiple screens
          4. +
          5. Supporting multiple API levels
          6. +
          +
        8. +
        + +

        See also

        +
          +
        1. Filters on Google Play
        2. +
        3. Supporting Multiple Screens
        4. +
        5. Compatibility +Package
        6. +
        7. Android API Levels
        8. +
        + +
        +
        + +

        Multiple APK support is a feature on Google Play that allows you to publish different APKs +for your application that are each targeted to different device configurations. Each APK is a +complete and independent version of your application, but they share the same application listing on +Google Play and must share the same package name and be signed with the same release key. This +feature is useful for cases in which your application cannot reach all desired devices with a single +APK.

        + +

        Android-powered devices may differ in several ways and it's important +to the success of your application that you make it available to as many devices as possible. +Android applications usually run on most compatible devices with a single APK, by supplying +alternative resources for different configurations (for example, different layouts for different +screen sizes) and the Android system selects the appropriate resources for the device at runtime. In +a few cases, however, a single APK is unable to support all device configurations, because +alternative resources make the APK file too big (greater than 50MB) or other technical challenges +prevent a single APK from working on all devices.

        + +

        Although we encourage you to develop and publish a single APK that supports as +many device configurations as possible, doing so is sometimes not possible. To help +you publish your application for as many devices as possible, Google Play allows you to +publish multiple APKs under the same application listing. Google Play then supplies each APK to +the appropriate devices based on configuration support you've declared in the manifest file of each +APK.

        + +

        By publishing your application with multiple APKs, you can:

        + +
          +
        • Support different OpenGL texture compression formats with each APK.
        • +
        • Support different screen configurations with each APK.
        • +
        • Support different platform versions with each APK.
        • +
        + +

        Currently, these are the only device characteristics that Google Play supports for publishing +multiple APKs as the same application.

        + +

        Note: You should generally use multiple APKs to support +different device configurations only when your APK is too large (greater than +50MB). Using a single APK to support different configurations is always the best practice, +because it makes the path for application updates simple and clear for users (and also makes +your life simpler by avoiding development and publishing complexity). Read the section below about +Using a Single APK Instead to +consider your options before publishing multiple APKs.

        + + +

        Publishing Concepts

        + +

        Before you start publishing multiple APKs on Google Play, you must understand a few +concepts regarding how the Google Play publisher site works.

        + +

        Active APKs

        + + + + +

        Before you can publish your application (whether publishing one or multiple APKs), you +must "activate" your APK(s) from the APK files tab. When you activate an APK, it +moves into the list of Active APKs. This list allows you to preview which APK(s) +you're about to publish.

        + +

        If there are no errors, any "active" APK will be published to +Google Play when you click the Publish button (if the application is +unpublished) or when you click the Save button (if the application is +already published).

        + + +

        Simple mode and advanced mode

        + +

        The Google Play publisher site provides two modes for managing the APKs associated with +your application: simple mode and advanced mode. You can switch between these by +clicking the +link at the top-right corner of the APK files tab.

        + +

        Simple mode is the traditional way to publish an application, using one APK at a time. In +simple mode, only one APK can be activated at a time. If you upload a new APK to update +the application, clicking "Activate" on the new APK deactivates the currently +active APK (you must then click Save to publish the new APK).

        + +

        Advanced mode allows you to activate and publish multiple APKs that are each designed for a +specific set of device configurations. However, there are several rules based on the manifest +declarations in each APK that determine whether you're allowed to activate each APK along with +others. When you activate an APK and it violates one of the rules, you will receive an error or +warning message. If it's an error, you cannot publish until you resolve the problem; if it's a +warning, you can publish the activated APKs, but there might be unintended consequences as to +whether your application is available for different devices. These rules are discussed more +below.

        + + +

        How Multiple APKs Work

        + +

        The concept for using multiple APKs on Google Play is that you have just one entry in +Google Play for your application, but different devices might download a different APK. This +means that:

        + +
          +
        • You maintain only one set of product details (app description, icons, screenshots, etc.). +This also means you cannot charge a different price for different APKs.
        • +
        • All users see only one version of your application on Google Play, so they are not +confused by different versions you may have published that are "for tablets" or +"for phones."
        • +
        • All user reviews are applied to the same application listing, even though users on different +devices may have different APKs.
        • +
        • If you publish different APKs for different versions of Android (for different API levels), +then when a user's device receives a system update that qualifies them for a different APK you've +published, Google Play updates the user's application to the APK designed for the higher version +of Android. Any system data associated with the application is retained (the same as with normal +application updates when using a single APK).
        • +
        + +

        To publish multiple APKs for the same application, you must enable Advanced mode +in your application's APK files tab (as discussed in the previous section). Once +in advanced mode, you can upload, activate, then publish multiple APKs for the same application. The +following sections describe more about how it works.

        + + +

        Supported filters

        + +

        Which devices receive each APK is determined by Google Play filters that are specified by +elements in the manifest file of each APK. However, Google Play allows you to publish multiple +APKs only when each APK uses filters to support a variation of the following +device characteristics:

        + +
          +
        • OpenGL texture compression formats +

          This is based on your manifest file's {@code +<supports-gl-texture>} element(s).

          +

          For example, when developing a game that uses OpenGL ES, you can provide one APK for +devices that support ATI texture compression and a separate APK for devices +that support PowerVR compression (among many others).

          +
          +
        • + +
        • Screen size (and, optionally, screen density) +

          This is based on your manifest file's {@code +<supports-screens>} or {@code +<compatible-screens>} element. You should never use both elements and you should use only +{@code +<supports-screens>} when possible.

          +

          For example, you can provide one APK that supports small and normal size screens and another +APK that supports large and xlarge screens.

          + +

          Note: The Android system provides strong support for +applications to support all screen configurations with a single APK. You should avoid creating +multiple APKs to support different screens unless absolutely necessary and instead follow the guide +to Supporting Multiple +Screens so that your application is flexible and can adapt to all screen configurations +with a single APK.

          +

          Caution: By default, all screen size attributes in the {@code +<supports-screens>} element are "true" if you do not declare them otherwise. However, +because the {@code android:xlargeScreens} attribute was added in Android 2.3 (API level +9), Google Play will assume that it is "false" if your application does not set either {@code +android:minSdkVersion} or {@code +android:targetSdkVersion} to "9" or higher.

          +

          Caution: You should not combine both {@code +<supports-screens>} and {@code +<compatible-screens>} elements in your manifest file. Using both increases the chances +that you'll introduce an error due to conflicts between them. For help deciding which to use, read +Distributing to Specific Screens. +If you can't avoid using both, be aware that for any conflicts in agreement between a given size, +"false" will win.

          +
          +
        • + +
        • API level +

          This is based on your manifest file's {@code <uses-sdk>} element. +You +can use both the {@code +android:minSdkVersion} and {@code android:maxSdkVersion} +attributes to specify support for different API levels.

          +

          For example, you can publish your application with one APK that supports API levels 4 - 7 +(Android 1.6 - 2.1)—using only APIs available since API level 4 or lower—and another +APK that supports API levels 8 and above (Android 2.2+)—using APIs available since API level 8 +or lower.

          +
          +

          Note:

          +
            +
          • If you use this characteristic as the factor to distinguish multiple APKs, then the APK +with a higher {@code +android:minSdkVersion} value must have a higher {@code android:versionCode} +value. This is also true if two APKs overlap their device support based on a different supported +filter. This ensures that when a device receives a system update, Google Play can offer the user +an update for your application (because updates are based on an increase in the app version code). +This requirement is described further in the section below about Rules for +multiple APKs.
          • +
          • You should avoid using {@code +android:maxSdkVersion} in general, because as long as you've properly developed your +application with public APIs, it is always compatible with future versions of Android. If you want +to publish a different APK for higher API levels, you still do not need to specify the +maximum version, because if the {@code +android:minSdkVersion} is {@code "4"} in one APK and {@code "8"} in another, devices that +support API level 8 or higher will always receive the second APK (because it's version code is +higher, as per the previous note).
          • +
          +
          +
        • +
        + +

        Other manifest elements that enable Google Play filters—but are not +listed above—are still applied for each APK as usual. However, Google Play does not allow +you to publish multiple APKs based on variations of them. Thus, you cannot publish +multiple APKs if the above listed filters are the same for each APK (but the APKs differ based on +other characteristics in the manifest file). For +example, you cannot provide different APKs that differ purely on the {@code +<uses-configuration>} characteristics.

        + + + +

        Rules for multiple APKs

        + +

        Before you enable advanced mode to publish multiple APKs for your application, you need to +understand the following rules that define how publishing multiple APKs works:

        + +
          +
        • All APKs you publish for the same application must have the same package +name and be signed with the same certificate key.
        • + +
        • Each APK must have a different version code, specified by the +{@code +android:versionCode} attribute.
        • + +
        • Each APK must not exactly match the configuration support of another APK. +

          That is, each APK must declare slightly different support for at least one of +the supported Google Play filters (listed above).

          +

          Usually, you will differentiate your APKs based on a specific characteristic (such as the +supported texture compression formats), and thus, each APK will declare support for different +devices. However, it's OK to publish multiple APKs that overlap their support slightly. When two +APKs do overlap (they support some of the same device configurations), a device that falls within +that overlap range will receive the APK with a higher version code (defined by {@code +android:versionCode}).

        • + +
        • You cannot activate a new APK that has a version code lower than that of the APK it's +replacing. For example, say you have an active APK for screen sizes small - normal with version code +0400, then try to replace it with an APK for the same screen sizes with version code 0300. This +raises an error, because it means users of the previous APK will not be able to update the +application.
        • + +
        • An APK that requires a higher API level must have a higher +version code. +

          This is true only when either: the APKs differ based only on the +supported API levels (no other supported filters +distinguish the APKs from each other) or when the APKs do use another supported filter, but +there is an overlap between the APKs within that filter.

          +

          This is important because a user's device receives an application update from +Google Play only if the version code for the APK on Google Play is higher than the version +code of the APK currently on the device. This ensures that if a device receives a system update that +then qualifies it to install the APK for higher API levels, the device receives an application +update because the version code increases.

          +

          Note: The size of the version code increase is irrelevant; it +simply needs to be larger in the version that supports higher API levels.

          +

          Here are some examples:

          +
            +
          • If an APK you've uploaded for API levels 4 and above (Android 1.6+) has a version code of +{@code 0400}, then an APK for API levels 8 and above (Android 2.2+) must be {@code 0401} or +greater. In this case, the API level is the only supported filter used, so the version codes +must increase in correlation with the API level support for each APK, so that users +get an update when they receive a system update.
          • +
          • If you have one APK that's for API level 4 (and above) and small - +large screens, and another APK for API level 8 (and above) and large - xlarge screens, then +the version codes must increase. In this case, the API level filter is used to +distinguish each APK, but so is the screen size. Because the screen sizes overlap (both APKs +support large screens), the version codes must still be in order. This ensures that a large screen +device that receives a system update to API level 8 will receive an update for the second +APK.
          • +
          • If you have one APK that's for API level 4 (and above) and small - +normal screens, and another APK for API level 8 (and above) and large - xlarge +screens, then the version codes do not need to increase in correlation with the API +levels. Because there is no overlap within the screen size filter, there are no devices that +could potentially move between these two APKs, so there's no need for the version codes to +increase from the lower API level to the higher API level.
          • +
          +
        • + +
        + +

        Failure to abide by the above rules results in an error on the Google Play publisher site +when you activate your APKs—you will be unable to publish your application until you +resolve the error.

        + +

        There are other conflicts that might occur when you activate your APKs, but which will result +in warnings rather than errors. Warnings can be caused by the following:

        + +
          +
        • When you modify an APK to "shrink" the support for a device's characteristics and no other +APKs support the devices that then fall outside the supported range. For example, if an APK +currently supports small and normal size screens and you change it to support only small screens, +then you have shrunk the pool of supported devices and some devices will no longer see your +application on Google Play. You can resolve this by adding another APK that supports normal size +screens so that all previously-supported devices are still supported.
        • + +
        • When there are "overlaps" between two or more APKs. For example, if an APK supports screen +sizes small, normal, and large, while another APK supports sizes large and xlarge, there is an +overlap, because both APKs support large screens. If you do not resolve this, then devices that +qualify for both APKs (large screen devices in the example) will receive whichever APK has the +highest version code.
        • +
        + +

        When such conflicts occur, you will see a warning message, but you can still publish your +application.

        + + + +

        Creating Multiple APKs

        + +

        Once you decide to publish multiple APKs, you probably need to create separate +Android projects for each APK you intend to publish so that you can appropriately develop them +separately. You can do this by simply duplicating your existing project and give it a new name. +(Alternatively, you might use a build system that can output different resources—such +as textures—based on the build configuration.)

        + +

        Tip: One way to avoid duplicating large portions of your +application code is to use a library project. A library +project holds shared code and resources, which you can include in your actual application +projects.

        + +

        When creating multiple projects for the same application, it's a good practice to identify each +one with a name that indicates the device restrictions to be placed on the APK, so you can +easily identify them. For example, "HelloWorld_8" might be a good name for an +application designed for API level 8 and above.

        + +

        Note: All APKs you publish for the same application +must have the same package name and be signed with the same certificate key. Be +sure you also understand each of the Rules for multiple APKs.

        + + +

        Assigning version codes

        + +

        Each APK for the same application must have a unique version code, specified by +the {@code +android:versionCode} attribute. You must be careful about assigning version codes when +publishing multiple APKs, because they must each be different, but in some +cases, must or should be defined in a specific order, based on the configurations that each APK +supports.

        + +

        Ordering version codes

        + +

        An APK that requires a higher API level must usually have a higher version code. For example, if +you create two APKs to support different API levels, the APK for the higher API levels must have the +higher version code. This ensures that if a device receives a system update that then qualifies it +to install the APK for higher API levels, the user receives a notification to update the app. For +more information about how this requirement applies, see the section above about Rules for multiple APKs.

        + +

        You should also consider how the order of version codes might affect which APK your users +receive either due to overlap between coverage of different APKs or future changes you might make to +your APKs.

        + +

        For example, if you have different APKs based on screen size, such as one for small - normal and +one for large - xlarge, but foresee a time when you will change the APKs to be one for small and one +for normal - xlarge, then you should make the version code for the large - xlarge APK be higher. +That way, a normal size device will receive the appropriate update when you make the change, because +the version code increases from the existing APK to the new APK that now supports the device.

        + +

        Also, when creating multiple APKs that differ based on support for different OpenGL texture +compression formats, be aware that many devices support multiple formats. Because a device +receives the APK with the highest version code when there is an overlap in coverage between two +APKs, you should order the version codes among your APKs so that the APK with the +preferred compression format has the highest version code. For example, you might want to perform +separate builds for your app using PVRTC, ATITC, and ETC1 compression formats. If you prefer these +formats in this exact order, then the APK that uses PVRTC should have the highest version code, the +APK that uses ATITC has a lower version code, and the version with ETC1 has the lowest. Thus, if a +device supports both PVRTC and ETC1, it receives the APK with PVRTC, because it has the highest +version code.

        + + +

        Using a version code scheme

        + +

        In order to allow different APKs to update their version codes independent of others (for +example, when you fix a bug in only one APK, so don't need to update all APKs), you should use a +scheme for your version codes that +provides sufficient room between each APK so that you can increase the code in one without requiring +an increase in others. You should also include your actual version name in the code (that is, the +user visible version assigned to {@code android:versionName}), +so that it's easy for you to associate the version code and version name.

        + +

        Note: When you increase the version code for an APK, Google +Play will prompt users of the previous version to update the application. Thus, to avoid +unnecessary updates, you should not increase the version code for APKs that do not actually +include changes.

        + +

        We suggest using a version code with at least 7 digits: integers that represent +the supported configurations are in the higher order bits, and the version name (from {@code +android:versionName}) is in the lower order bits. For example, when the application version +name is 3.1.0, version codes for an API level 4 +APK and an API level 11 APK would be something like 0400310 and 1100310, respectively. The first +two digits are reserved for the API Level (4 and 11, respectively), the middle two digits are for +either screen sizes or GL texture formats (not used in these examples), and the last three digits +are for the application's version name (3.1.0). Figure 1 shows two examples that split based on both +the platform version (API Level) and screen size.

        + + +

        Figure 1. A suggested scheme for your version codes, +using the first two digits for the API Level, the second and third digits for the minimum and +maximum screen size (1 - 4 indicating each of the four sizes) or to denote the texture formats +and the last three digits for the app version.

        + +

        This scheme for version codes is just a suggestion for how you should establish a +pattern that is scalable as your application evolves. In particular, this scheme doesn't +demonstrate a solution for identifying different texture compression formats. One option might be +to define your own table that specifies a different integer to each of the different +compression formats your application supports (for example, 1 might correspond to ETC1 and 2 is +ATITC, and so on).

        + +

        You can use any scheme you want, but you should carefully consider how future versions of your +application will need to increase their version codes and how devices can receive updates when +either the device configuration changes (for example, due to a system update) or when you modify the +configuration support for one or several of the APKs.

        + + + + +

        Using a Single APK Instead

        + +

        Creating multiple APKs for your application is not the normal procedure for +publishing an application on Google Play. In most cases, you should be able to publish your +application to most users with a single APK and we encourage that you do so. When you encounter +a situation in which using a single APK becomes difficult, you should carefully consider all your +options before deciding to publish multiple APKs.

        + +

        First of all, there are a few key benefits to developing a single APK that supports all +devices:

        + +
          +
        • Publishing and managing your application is easier. +

          With only one APK to worry about at any given time, you're less likely to become confused by +which APK is what. You also don't have to keep track of multiple version codes for each +APK—by using only one APK, you can simply increase the version code with each release and +be done.

        • +
        • You need to manage only a single code base. +

          Although you can use a library project +to share code between multiple Android projects, it's still likely that you'll reproduce some code +across each project and this could become difficult to manage, especially when resolving +bugs.

        • +
        • Your application can adapt to device configuration changes. +

          By creating a single APK that contains all the resources for each device configuration, your +application can adapt to configuration changes that occur at runtime. For example, if the user docks +or otherwise connects a handset device to a larger screen, there's a chance that this will invoke a +system configuration change to support the larger screen. If you include all resources for different +screen configurations in the same APK, then your application will load alternative resources and +optimize the user experience for the new interface.

          +
        • +
        • App restore across devices just works. +

          If a user has enabled data backup on his or her current device and then buys a new device +that has a different configuration, then when the user's apps are automatically restored during +setup, the user receives your application and it runs using the resources optimized for that device. +For example, on a new tablet, the user receives your application and it runs with your +tablet-optimized resources. This restore +process does not work across different APKs, because each APK can potentially have different +permissions that the user has not agreed to, so Google Play may not restore the application at +all. (If you use multiple APKs, the user receives either the exact same APK if it's compatible or +nothing at all and must manually download your application to get the APK designed for the new +device.)

        • +
        + +

        The following sections describe some of the other options you should use to support multiple +device configurations before deciding to publish multiple APKs.

        + + + +

        Supporting multiple GL textures

        + +

        To support multiple types of GL textures with a single APK, your application should query the GL +texture formats supported on the device and then use the appropriate resources or download +them from a web server. For example, in order to keep the size of your APK small, you can query the +device's support for different GL texture formats when the application starts for the first time and +then download only the textures you need for that device.

        + +

        For maximum performance and compatibility, your application should use ETC1 textures wherever it +doesn't impact the visual quality. However, because ETC1 cannot deal with images that have drastic +chroma changes, such as line art and (most) text, and doesn't support alpha, it may not the best +format for all textures.

        + +

        With a single APK, you should try to use ETC1 textures and uncompressed textures whenever +reasonable, and consider the use of PVRTC, ATITC, or DXTC as a last resort when ETC1 does not +suffice.

        + +

        Here's an example query for supported texture compression formats from inside a +{@link android.opengl.GLSurfaceView.Renderer GLSurfaceView.Renderer}:

        + +
        +public void onSurfaceChanged(GL10 gl, int w, int h) {
        +    String extensions = gl.glGetString(GL10.GL_EXTENSIONS);
        +    Log.d("ExampleActivity", extensions);
        +}
        +
        + +

        This returns a string that lists each of the supported compression formats.

        + + + +

        Supporting multiple screens

        + +

        Unless your APK file exceeds the Google Play size limit of 50MB, supporting multiple screens +should always be done with a single APK. Since Android 1.6, the Android system manages most of the +work required for your application to run successfully on a variety of screen sizes and +densities.

        + +

        To further optimize your application for different screen sizes and densities, you should provide +alternative +resources such as bitmap drawables at different resolutions and different layout designs for +different screen sizes.

        + +

        For more information about how to support multiple screens with a single APK, read Supporting Multiple Screens.

        + +

        Additionally, you should consider using a support library from the Compatibility Package so that you can add Fragments to your activity designs +when running on larger screens such as tablets.

        + + + +

        Supporting multiple API levels

        + +

        If you want to support as many versions of the Android platform as possible, you should use +only APIs available in the lowest reasonable version. For example, your application may not require +APIs newer than Android 2.1 (API Level 7), which makes an application available to +over 95% of Android-powered devices (as indicated by the Platform Versions dashboard).

        + +

        By using a support library from the Compatibility Package, you can also use APIs +from some of the latest versions (such as Android 3.0) while +still supporting versions as low as Android 1.6. The support library includes APIs for Fragments, Loaders, and more. Using the fragment +APIs is particularly valuable so that you can optimize your user interface for large devices such as +tablets.

        + +

        Alternatively, if you want to use some APIs that are available only in newer versions of Android +(which your application can still function without), then you should consider using reflection. By +using reflection, you can check whether the current device supports certain APIs. If the APIs are +not available, your application can gracefully disable and hide the feature.

        + +

        Another way to use new APIs only when running on a version that supports them is to check the +API level of the current device. That is, you can query the value of {@link +android.os.Build.VERSION#SDK_INT} and create different code paths depending on the API level +supported by the device. For example:

        + +
        +if (android.os.Build.VERSION.SDK_INT >= 11) {
        +    // Use APIs supported by API level 11 (Android 3.0) and up
        +} else {
        +    // Do something different to support older versions
        +}
        +
        + diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs index 62d18aee3f9a..44b977e327dd 100644 --- a/docs/html/guide/guide_toc.cs +++ b/docs/html/guide/guide_toc.cs @@ -5,236 +5,80 @@ Below are template spans for adding localized doc titles. Please ensure that localized titles are added in the language order specified below. ?> -
    + + + + + + - -
  • - - +
  • -
  • - + +
  • - -
  • - - -
  • - - - -
  • - - Publishing - - - - - - - - +
  • + + - -
  • - +
  • + + + + + + + + + + + + + diff --git a/docs/html/guide/index.jd b/docs/html/guide/index.jd index 8378472ec62f..fea7027d3684 100644 --- a/docs/html/guide/index.jd +++ b/docs/html/guide/index.jd @@ -1,88 +1,56 @@ -page.title=The Developer's Guide -@jd:body - -

    -Welcome to the Android Dev Guide! The Dev Guide provides -a practical introduction to developing applications for Android and documentation about major -platform features. It explores the concepts behind Android, the framework for -constructing an application, and the tools for developing, -testing, and publishing software for the platform. -

    - -

    -The Dev Guide holds most of the documentation for the Android -platform, except for reference material on the framework API. -For API specifications, go to the -Reference. -

    - -

    -As you can see in the panel on the left, the Dev Guide is -divided into several sections: -

    - -

    -
    Android Basics
    -
    An initial orientation to Android — what it is, -what it offers, and how your application fits in.
    - -
    Framework Topics
    -
    Discussions of particular parts of the Android framework -and API. For an introduction to the framework, begin with -Application -Fundamentals. Then explore other topics — from -designing a user interface and setting up resources to storing -data and using permissions — as needed.
    - -
    Google Play Topics
    -
    Documentation for topics that concern publishing and monetizing applications on Google Play, -such as how to enforce licensing policies and implement in-app billing.
    - -
    Developing
    -
    Directions for using Android's development and debugging tools, -and for testing the results.
    +page.title=App Components +page.landing=true +page.landing.intro=Android's application framework lets you create extremely rich and innovative apps using a set of reusable components. This section explains how Android apps work and how you use components to build them. +page.landing.image=images/ui/ui_index.png -
    Publishing
    -
    Instructions on how to prepare your application for deployment -and how to publish it when it's ready.
    - -
    Best Practices
    -
    Recommendations on preferred techniques for writing -applications that perform efficiently and work well for the -user.
    - -
    Web Applications
    -
    Documentation about how to create web applications that work seamlessly on Android-powered -devices and create Android applications that embed web-based content.
    - -
    Appendix
    -
    Reference information and specifications, as well as FAQs, -a glossary of terms, and other information.
    -
    - -

    -The first step in programming for Android is downloading the SDK -(software development kit). For instructions and information, visit the SDK tab. -

    - -

    -After you have the SDK, begin by looking through the Dev Guide. -If you want to start by getting a quick look at some code, the -Hello World -tutorial walks you through a standard "Hello, World" application to introduce some basics of an -Android application. The -Application -Fundamentals document is a good place to start learning the basics about the application -framework. -

    - - -

    -For additional help, consider joining one or more of the Android -discussion groups. Go to the -Developer Forums page -for more information. -

    +@jd:body -

    To return to this page later, just click the "Dev Guide" tab while any Dev Guide page is loaded.

    \ No newline at end of file +
    + + + + + +
    \ No newline at end of file diff --git a/docs/html/guide/market/billing/billing_about.html b/docs/html/guide/market/billing/billing_about.html deleted file mode 100644 index d8395df3bb67..000000000000 --- a/docs/html/guide/market/billing/billing_about.html +++ /dev/null @@ -1,12 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click -here.

    - - \ No newline at end of file diff --git a/docs/html/guide/market/billing/billing_admin.jd b/docs/html/guide/market/billing/billing_admin.jd deleted file mode 100755 index 0f869ab78795..000000000000 --- a/docs/html/guide/market/billing/billing_admin.jd +++ /dev/null @@ -1,517 +0,0 @@ -page.title=Administering In-app Billing -parent.title=In-app Billing -parent.link=index.html -@jd:body - - - -

    In-app billing frees you from processing financial transactions, but you still need to perform a -few administrative tasks, including setting up and maintaining your product list on the publisher -site, registering test accounts, and handling refunds when necessary.

    - -

    You must have a Google Play publisher account to register test accounts. And you must have a -Google Checkout merchant account to create a product list and issue refunds to your users. If you -already have a publisher account on Google Play, you can use your existing account. You do not -need to register for a new account to support in-app billing. If you do not have a publisher -account, you can register as a Google Play developer and set up a publisher account at the -Google Play publisher site. If you do not have a -Google Checkout merchant account, you can register for one at the Google Checkout site.

    - -

    Creating a Product List

    - -

    The Google Play publisher site provides a product list for each of your published -applications. You can sell an item using Google Play's in-app billing feature only if the item is -listed on an application's product list. Each application has its own product list; you cannot sell -items that are listed in another application's product list.

    - -

    You can access an application's product list by clicking the In-App Products -link that appears under each of the applications that are listed for your publisher account (see -figure 1). The In-App Products link appears only if you have a Google Checkout -merchant account and an application's manifest includes the com.android.vending.BILLING -permission.

    - - -

    - Figure 1. You can access an application's product list by clicking the - In-App Products link. -

    - -

    A product list contains information about the items you are selling, such as a product id, -product description, and price (see figure 2). The product list stores only metadata about the items -you are selling in your application. It does not store any digital content. You are responsible for -storing and delivering the digital content that you sell in your applications.

    - - -

    - Figure 2. An application's product list. -

    - -

    You can create a product list for any published application or any draft application that's been -uploaded and saved to the Google Play site. However, you must have a Google Checkout merchant -account and the application's manifest must include the com.android.vending.BILLING -permission. If an application's manifest does not include this permission, you will be able to edit -existing items in the product list but you will not be able to add new items to the list. For more -information about this permission, see -Updating Your -Application's Manifest.

    - -

    In addition, an application package can have only one product list. If you create a product -list for an application, and you use the multiple APK feature to distribute -more than one APK for that application, the product list applies to all APK versions that are -associated with the application listing. You cannot create individual product lists for each APK if -you are using the multiple APK feature.

    - -

    You can add items to a product list two ways: you can add items one at a time by using the In-app -Products UI (see figure 3), or you can add a batch of items by importing the items from a -comma-separated values (CSV) file (see figure 2). Adding items one at a time is useful if your -application has only a few in-app items or you are adding only a few items to a -product list for testing purposes. The CSV file method is useful if your application has a large -number of in-app items.

    - -

    Adding items one at a time to a product list

    - -

    To add an item to a product list using the In-app Products UI, follow these steps:

    - -
      -
    1. Log in to your publisher account.
    2. -
    3. In the All Google Play listings panel, under the application name, click - In-app Products.
    4. -
    5. On the In-app Products List page, click Add in-app product.
    6. -
    7. On the Create New In-app Product page (see figure 3), provide details about the item you are - selling and then click Save or Publish.
    8. -
    - - -

    - Figure 3. The Create New In-app Product page lets you add items to an - application's product list. -

    - -

    You must enter the following information for each item in a product list:

    -
      -
    • In-app Product ID -

      Product IDs are unique across an application's namespace. A product ID must start with a - lowercase letter or a number, and must be composed using only lowercase letters (a-z), numbers - (0-9), underlines (_), and dots (.). The product ID "android.test" is reserved, as are all - product IDs that start with "android.test."

      -

      In addition, you cannot modify an item's product ID after it is created, and you cannot reuse - a product ID.

      -
    • -
    • Purchase Type -

      The purchase type can be Managed per user account or - Unmanaged. You can never change an item's purchase type after you set it. For more - information, see Choosing a purchase type later in this - document.

      -
    • -
    • Publishing State -

      An item's publishing state can be Published or Unpublished - . To be visible to a user during checkout, an item's publishing state must be set to - Published and the item's application must be published on Google Play.

      -

      Note: This is not true for test accounts. An item is visible to - a test account if the application is not published and the item is published. See Testing In-app - Billing for more information.

      -
    • -
    • Language -

      The language setting determines which languages are used to display the item title and - item description during checkout. A product list inherits its default language from the - parent application. You can add more languages by clicking add language. You - can also choose to have the title and description automatically translated from the default - language by selecting the Fill fields with auto translation checkbox (see - figure 4). If you do not use the auto translation feature, you must provide the translated - versions of the title and description.

      -
    • -
    • Title -

      The title is a short descriptor for the item. For example, "Sleeping potion." Titles must be - unique across an application's namespace. Every item must have a title. The title is visible to - users during checkout. For optimum appearance, titles should be no longer than 25 characters; - however, titles can be up to 55 characters in length.

      -
    • -
    • Description -

      The description is a long descriptor for the item. For example, "Instantly puts creatures to - sleep. Does not work on angry elves." Every item must have a description. The description is - visible to users during checkout. Descriptions can be up to 80 characters in length.

      -
    • -
    • Price -

      You must provide a default price in your home currency. You can also provide prices in other - currencies, but you can do this only if a currency's corresponding country is listed as a - target country for your application. You can specify target countries on the Edit Application - page in the Google Play developer console.

      -

      To specify prices in other currencies, you can manually enter the price for each - currency or you can click Auto Fill and let Google Play do a one-time - conversion from your home currency to the currencies you are targeting (see figure 4).

      -
    • -
    - -

    - Figure 4. Specifying additional currencies and additional languages for the - item title and description. -

    - -

    For more information about product IDs and product lists, see Creating In-App Product -IDs. For more information about pricing, see In-App Billing -Pricing.

    - -

    Note: Be sure to plan your product ID namespace. You cannot reuse -or modify product IDs after you save them.

    - -

    Adding a batch of items to a product list

    - -

    To add a batch of items to a product list using a CSV file, you first need to create your CSV -file. The data values that you specify in the CSV file represent the same data values you specify -manually through the In-app Products UI (see Adding items one at a time -to a product list). The CSV file uses commas (,) and semi-colons (;) to separate data values. -Commas are used to separate primary data values, and semi-colons are used to separate subvalues. For -example, the syntax for the CSV file is as follows:

    - -

    "product_id","publish_state","purchase_type","autotranslate -","locale; title; description","autofill","country; -price" -

    - -

    Descriptions and usage details are provided below.

    - -
      -
    • product_id -

      This is equivalent to the In-app Product ID setting in the In-app Products UI. If you specify - a product_id that already exists in a product list, and you choose to overwrite - the product list while importing the CSV file, the data for the existing item is overwritten with - the values specified in the CSV file. The overwrite feature does not delete items that are on a - product list but not present in the CSV file.

      -
    • -
    • publish_state -

      This is equivalent to the Publishing State setting in the In-app Products UI. Can be - published or unpublished.

      -
    • -
    • purchase_type -

      This is equivalent to the Purchase Type setting in the In-app Products UI. Can be - managed_by_android, which is equivalent to Managed per user account - in the In-app Products UI, or managed_by_publisher, which is equivalent - to Unmanaged in the In-app Products UI.

      -
    • -
    • autotranslate -

      This is equivalent to selecting the Fill fields with auto translation - checkbox in the In-app Products UI. Can be true or false.

      -
    • -
    • locale -

      This is equivalent to the Language setting in the In-app Products UI. You must have an entry - for the default locale. The default locale must be the first entry in the list of - locales, and it must include a title and description. If you want to provide - translated versions of the title and description in addition to the default, - you must use the following syntax rules:

      -

      If autotranslate is true, you must specify the default locale, - default title, default description, and other locales using the following format:

      -

      "true,"default_locale; default_locale_title; - default_locale_description; locale_2; locale_3, ..."

      -

      If autotranslate is false, you must specify the default locale, - default title, and default description as well as the translated titles and descriptions using - the following format:

      -

      "false,"default_locale; default_locale_title; - default_locale_description; locale_2; locale_2_title; - local_2_description; locale_3; locale_3_title; - locale_3_description; ..."

      -

      See table 1 for a list of the language codes you can use with the locale field.

      -
    • -
    • title -

      This is equivalent to the Title setting in the In-app Products UI. If the title - contains a semicolon, it must be escaped with a backslash (for example, "\;"). A backslash - should also be escaped with a backslash (for example, "\\">.

      -
    • -
    • description -

      This is equivalent to the Description in the In-app Products UI. If the description - contains a semicolon, it must be escaped with a backslash (for example, "\;"). A backslash - should also be escaped with a backslash (for example, "\\">.

      -
    • -
    • autofill -

      This is equivalent to clicking Auto Fill in the In-app Products UI. Can be - true or false. The syntax for specifying the country - and price varies depending on which autofill setting you use.

      -

      If autofill is set to true, you need to specify only the default - price in your home currency and you must use this syntax:

      -

      "true","default_price_in_home_currency" -

      If autofill is set to false, you need to specify a country - and a price for each currency and you must use the following syntax:

      -

      "false", "home_country; default_price_in_home_currency; country_2; - country_2_price; country_3; country_3_price; ..."

      -
    • -
    • country -

      The country for which you are specifying a price. You can only list countries that your - application is targeting. The country codes are two-letter uppercase - ISO country codes (such as "US") as defined by - ISO 3166-2.

      -
    • -
    • price -

      This is equivalent to the Price in the In-app Products UI. The price must be specified in - micro-units. To convert a currency value to micro-units, you multiply the real value by 1,000,000. - For example, if you want to sell an in-app item for $1.99 you specify 1990000 in the - price field.

      -
    • -
    - -

    Table 1. Language codes you can use -with the locale field.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    LanguageCodeLanguageCode
    Chinesezh_TWItalianit_IT
    Czechcs_CZJapaneseja_JP
    Danishda_DKKoreanko_KR
    Dutchnl_NLNorwegianno_NO
    Englishen_USPolishpl_PL
    Frenchfr_FRPortuguesept_PT
    Finnishfi_FIRussianru_RU
    Germande_DESpanishes_ES
    Hebrewiw_ILSwedishsv_SE
    Hindihi_IN----
    - -

    To import the items that are specified in your CSV file, do the following:

    - -
      -
    1. Log in to your publisher account.
    2. -
    3. In the All Google Play listings panel, under the application name, click - In-app Products.
    4. -
    5. On the In-app Products List page, click Choose File and select your CSV -file. -

      The CSV file must be on your local computer or on a local disk that is connected to your - computer.

      -
    6. -
    7. Select the Overwrite checkbox if you want to overwrite existing items in - your product list. -

      This option overwrites values of existing items only if the value of the product_id - in the CSV file matches the In-app Product ID for an existing item in the product list. - Overwriting does not delete items that are on a product list but not present in the CSV - file.

      -
    8. -
    9. On the In-app Products List page, click Import from CSV.
    10. -
    - -

    You can also export an existing product list to a CSV file by clicking Export to CSV - on the In-app Product List page. This is useful if you have manually added items to -a product list and you want to start managing the product list through a CSV file.

    - -

    Choosing a Purchase Type

    - -

    An item's purchase type controls how Google Play manages the purchase of the item. There are -two purchase types: "managed per user account" and "unmanaged."

    - -

    Items that are managed per user account can be purchased only once per user account. When an item -is managed per user account, Google Play permanently stores the transaction information for each -item on a per-user basis. This enables you to query Google Play with the -RESTORE_TRANSACTIONS request and restore the state of the items a specific user has -purchased.

    - -

    If a user attempts to purchase a managed item that has already been purchased, Google Play -displays an "Item already purchased" error. This occurs during checkout, when Google Play -displays the price and description information on the checkout page. When the user dismisses the -error message, the checkout page disappears and the user returns to your user interface. As a best -practice, your application should prevent the user from seeing this error. The sample application -demonstrates how you can do this by keeping track of items that are managed and already purchased -and not allowing users to select those items from the list. Your application should do something -similar—either graying out the item or hiding it so that it cannot be selected.

    - -

    The "manage by user account" purchase type is useful if you are selling items such as game levels -or application features. These items are not transient and usually need to be restored whenever a -user reinstalls your application, wipes the data on their device, or installs your application on a -new device.

    - -

    Items that are unmanaged do not have their transaction information stored on Google Play, -which means you cannot query Google Play to retrieve transaction information for items whose -purchase type is listed as unmanaged. You are responsible for managing the transaction information -of unmanaged items. Also, unmanaged items can be purchased multiple times as far as Google Play -is concerned, so it's also up to you to control how many times an unmanaged item can be -purchased.

    - -

    The "unmanaged" purchase type is useful if you are selling consumable items, such as fuel or -magic spells. These items are consumed within your application and are usually purchased multiple -times.

    - -

    Handling Refunds

    - -

    In-app billing does not allow users to send a refund request to Google Play. Refunds for -in-app purchases must be directed to you (the application developer). You can then process the -refund through your Google Checkout merchant account. When you do this, Google Play receives a -refund notification from Google Checkout, and Google Play sends a refund message to your -application. For more information, see Handling -IN_APP_NOTIFY messages and In-app Billing -Pricing.

    - -

    Important: You cannot use the Google Checkout API to issue -refunds or cancel in-app billing transactions. You must do this manually through your Google -Checkout merchant account. However, you can use the Google Checkout API to retrieve order -information.

    - -

    Setting Up Test Accounts

    - -

    The Google Play publisher site lets you set up one or more test accounts. A test account is a -regular Google account that you register on the publisher site as a test account. Test accounts are -authorized to make in-app purchases from applications that you have uploaded to the Google Play -site but have not yet published.

    - -

    You can use any Google account as a test account. Test accounts are useful if you want to let -multiple people test in-app billing on applications without giving them access to your publisher -account's sign-in credentials. If you want to own and control the test accounts, you can create the -accounts yourself and distribute the credentials to your developers or testers.

    - -

    Test accounts have three limitations:

    - -
      -
    • Test account users can make purchase requests only within applications that are already - uploaded to your publisher account (although the application doesn't need to be published).
    • -
    • Test accounts can only be used to purchase items that are listed (and published) in an - application's product list.
    • -
    • Test account users do not have access to your publisher account and cannot upload applications - to your publisher account.
    • -
    - -

    To add test accounts to your publisher account, follow these steps:

    - -
      -
    1. Log in to your publisher account.
    2. -
    3. On the upper left part of the page, under your name, click Edit profile.
    4. -
    5. On the Edit Profile page, scroll down to the Licensing & In-app Billing panel (see figure - 5).
    6. -
    7. In Test Accounts, add the email addresses for the test accounts you want to register, - separating each account with a comma.
    8. -
    9. Click Save to save your profile changes.
    10. -
    - - -

    - Figure 5. The Licensing and In-app Billing panel of your account's Edit Profile - page lets you register test accounts. -

    - -

    Where to Get Support

    - -

    If you have questions or encounter problems while implementing in-app billing, contact the -support resources listed in the following table (see table 2). By directing your queries to the -correct forum, you can get the support you need more quickly.

    - -

    Table 2. Developer support resources -for Google Play in-app billing.

    - - - - - - - - - - - - - - - - - - - - - -
    Support TypeResourceRange of Topics
    Development and testing issuesGoogle Groups: android-developers In-app billing integration questions, user experience ideas, handling of responses, -obfuscating code, IPC, test environment setup.
    Stack Overflow: http://stackoverflow.com/questions/tagged/ -android
    Billing issue trackerBilling -project issue trackerBug and issue reports related specifically to in-app billing sample code.
    - -

    For general information about how to post to the groups listed above, see Developer Forums document in the Resources -tab.

    - - - diff --git a/docs/html/guide/market/billing/billing_best_practices.jd b/docs/html/guide/market/billing/billing_best_practices.jd deleted file mode 100755 index e100ce581303..000000000000 --- a/docs/html/guide/market/billing/billing_best_practices.jd +++ /dev/null @@ -1,111 +0,0 @@ -page.title=Security and Design -parent.title=In-app Billing -parent.link=index.html -@jd:body - - - -

    As you design your in-app billing implementation, be sure to follow the security and design -guidelines that are discussed in this document. These guidelines are recommended best practices for -anyone who is using Google Play's in-app billing service.

    - -

    Security Best Practices

    - -

    Perform signature verification tasks on a server

    -

    If practical, you should perform signature verification on a remote server and not on a device. -Implementing the verification process on a server makes it difficult for attackers to break the -verification process by reverse engineering your .apk file. If you do offload security processing to -a remote server, be sure that the device-server handshake is secure.

    - -

    Protect your unlocked content

    -

    To prevent malicious users from redistributing your unlocked content, do not bundle it in your -.apk file. Instead, do one of the following:

    -
      -
    • Use a real-time service to deliver your content, such as a content feed. Delivering content - through a real-time service allows you to keep your content fresh.
    • -
    • Use a remote server to deliver your content.
    • -
    -

    When you deliver content from a remote server or a real-time service, you can store the unlocked -content in device memory or store it on the device's SD card. If you store content on an SD card, be -sure to encrypt the content and use a device-specific encryption key.

    - -

    Obfuscate your code

    -

    You should obfuscate your in-app billing code so it is difficult for an attacker to reverse -engineer security protocols and other application components. At a minimum, we recommend that you -run an obfuscation tool like Proguard on your -code.

    -

    In addition to running an obfuscation program, we recommend that you use the following techniques -to obfuscate your in-app billing code.

    -
      -
    • Inline methods into other methods.
    • -
    • Construct strings on the fly instead of defining them as constants.
    • -
    • Use Java reflection to call methods.
    • -
    -

    Using these techniques can help reduce the attack surface of your application and help minimize -attacks that can compromise your in-app billing implementation.

    -
    -

    Note: If you use Proguard to obfuscate your code, you must add the following - line to your Proguard configuration file:

    -

    -keep class com.android.vending.billing.**

    -
    - -

    Modify all sample application code

    -

    The in-app billing sample application is publicly distributed and can be downloaded by anyone, -which means it is relatively easy for an attacker to reverse engineer your application if you use -the sample code exactly as it is published. The sample application is intended to be used only as an -example. If you use any part of the sample application, you must modify it before you publish it or -release it as part of a production application.

    -

    In particular, attackers look for known entry points and exit points in an application, so it is -important that you modify these parts of your code that are identical to the sample application.

    - -

    Use secure random nonces

    -

    Nonces must not be predictable or reused. Always use a cryptographically secure random number -generator (like {@link java.security.SecureRandom}) when you generate nonces. This can help reduce -replay attacks.

    -

    Also, if you are performing nonce verification on a server, make sure that you generate the -nonces on the server.

    - -

    Take action against trademark and copyright infringement

    -

    If you see your content being redistributed on Google Play, act quickly and decisively. File a -trademark notice -of infringement or a copyright notice of -infringement.

    - -

    Implement a revocability scheme for unlocked content

    -

    If you are using a remote server to deliver or manage content, have your application verify the -purchase state of the unlocked content whenever a user accesses the content. This allows you to -revoke use when necessary and minimize piracy.

    - -

    Protect your Google Play public key

    -

    To keep your public key safe from malicious users and hackers, do not embed it in any code as a -literal string. Instead, construct the string at runtime from pieces or use bit manipulation (for -example, XOR with some other string) to hide the actual key. The key itself is not secret -information, but you do not want to make it easy for a hacker or malicious user to replace the -public key with another key.

    - diff --git a/docs/html/guide/market/billing/billing_integrate.jd b/docs/html/guide/market/billing/billing_integrate.jd deleted file mode 100755 index 4b3650fcc6d5..000000000000 --- a/docs/html/guide/market/billing/billing_integrate.jd +++ /dev/null @@ -1,1092 +0,0 @@ -page.title=Implementing In-app Billing -parent.title=In-app Billing -parent.link=index.html -@jd:body - - - -

    In-app Billing on Google Play provides a straightforward, simple interface for sending in-app -billing requests and managing in-app billing transactions using Google Play. This document helps -you implement in-app billing by stepping through the primary implementation tasks, using the in-app -billing sample application as an example.

    - -

    Before you implement in-app billing in your own application, be sure that you read Overview of In-app Billing and Security and Design. These -documents provide background information that will make it easier for you to implement in-app -billing.

    - -

    To implement in-app billing in your application, you need to do the following:

    -
      -
    1. Download the in-app billing sample application.
    2. -
    3. Add the IMarketBillingService.aidl file to your project.
    4. -
    5. Update your AndroidManifest.xml file.
    6. -
    7. Create a Service and bind it to the - MarketBillingService so your application can send billing requests and receive - billing responses from Google Play.
    8. -
    9. Create a BroadcastReceiver to handle broadcast - intents from Google Play.
    10. -
    11. Create a security processing component to verify the - integrity of the transaction messages that are sent by Google Play.
    12. -
    13. Modify your application code to support in-app billing.
    14. -
    - -

    Downloading the Sample Application

    - -

    The in-app billing sample application shows you how to perform several tasks that are common to -all in-app billing implementations, including:

    - -
      -
    • Sending in-app billing requests to Google Play.
    • -
    • Handling synchronous responses from Google Play.
    • -
    • Handling broadcast intents (asynchronous responses) from Google Play.
    • -
    • Using in-app billing security mechanisms to verify the integrity of billing responses.
    • -
    • Creating a user interface that lets users select items for purchase.
    • -
    - -

    The sample application includes an application file (Dungeons.java), the AIDL file -for the MarketBillingService (IMarketBillingService.aidl), and several -classes that demonstrate in-app billing messaging. It also includes a class that demonstrates basic -security tasks, such as signature verification.

    - -

    Table 1 lists the source files that are included with the sample application.

    -

    Table 1. In-app billing sample -application source files.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    FileDescription
    IMarketBillingService.aidlAndroid Interface Definition Library (AIDL) file that defines the IPC interface to Google -Play's in-app billing service (MarketBillingService).
    Dungeons.javaSample application file that provides a UI for making purchases and displaying purchase -history.
    PurchaseDatabase.javaA local database for storing purchase information.
    BillingReceiver.javaA {@link android.content.BroadcastReceiver} that receives asynchronous response messages - (broadcast intents) from Google Play. Forwards all messages to the - BillingService.
    BillingService.javaA {@link android.app.Service} that sends messages to Google Play on behalf of the - application by connecting (binding) to the MarketBillingService.
    ResponseHandler.javaA {@link android.os.Handler} that contains methods for updating the purchases database and the - UI.
    PurchaseObserver.javaAn abstract class for observing changes related to purchases.
    Security.javaProvides various security-related methods.
    Consts.javaDefines various Google Play constants and sample application constants. All constants that -are defined by Google Play must be defined the same way in your application.
    Base64.java and Base64DecoderException.javaProvides conversion services from binary to Base64 encoding. The Security class -relies on these utility classes.
    - -

    The in-app billing sample application is available as a downloadable component of the Android -SDK. To download the sample application component, launch the Android SDK Manager and then -select the Google Market Billing package component (see figure 1), and click Install -Selected to begin the download.

    - - - -

    - Figure 1. The Google Market Billing package contains the sample application and - the AIDL file. -

    - -

    When the download is complete, the Android SDK Manager saves the component into the -following directory:

    - -

    <sdk>/extras/google/market_billing/

    - -

    If you want to see an end-to-end demonstration of in-app billing before you integrate in-app -billing into your own application, you can build and run the sample application. Building and -running the sample application involves three tasks:

    - -
      -
    • Configuring and building the sample application.
    • -
    • Uploading the sample application to Google Play.
    • -
    • Setting up test accounts and running the sample application.
    • -
    - -

    Note: Building and running the sample application is necessary only -if you want to see a demonstration of in-app billing. If you do not want to run the sample -application, you can skip to the next section, Adding the AIDL file to -your project.

    - -

    Configuring and building the sample application

    - -

    Before you can run the sample application, you need to configure it and build it by doing the -following:

    - -
      -
    1. Add your Google Play public key to the sample application code. -

      This enables the application to verify the signature of the transaction information that is - returned from Google Play. To add your public key to the sample application code, do the - following:

      -
        -
      1. Log in to your Google Play publisher - account.
      2. -
      3. On the upper left part of the page, under your name, click Edit - Profile.
      4. -
      5. On the Edit Profile page, scroll down to the Licensing & In-app - Billing panel.
      6. -
      7. Copy your public key.
      8. -
      9. Open src/com/example/dungeons/Security.java in the editor of your choice. -

        You can find this file in the sample application's project folder.

        -
      10. -
      11. Add your public key to the following line of code: -

        String base64EncodedPublicKey = "your public key here";

        -
      12. -
      13. Save the file.
      14. -
      -
    2. -
    3. Change the package name of the sample application. -

      The current package name is com.example.dungeons. Google Play does not let - you upload applications with package names that contain com.example, so you must - change the package name to something else.

      -
    4. -
    5. Build the sample application in release mode and sign it. -

      To learn how to build and sign applications, see Building and Running.

      -
    6. -
    - -

    Uploading the sample application

    - -

    After you build a release version of the sample application and sign it, you need to upload it as -a draft to the Google Play publisher site. You also need to create a product list for the in-app -items that are available for purchase in the sample application. The following instructions show you -how to do this.

    -
      -
    1. Upload the release version of the sample application to Google Play. -

      Do not publish the sample application; leave it as an unpublished draft application. The - sample application is for demonstration purposes only and should not be made publicly available - on Google Play. To learn how to upload an application to Google Play, see Uploading - applications.

      -
    2. -
    3. Create a product list for the sample application. -

      The sample application lets you purchase two items: a two-handed sword - (sword_001) and a potion (potion_001). We recommend that you set up - your product list so that sword_001 has a purchase type of "Managed per user - account" and potion_001 has a purchase type of "Unmanaged" so you can see how these - two purchase types behave. To learn how to set up a product list, see Creating a Product - List.

      -

      Note: You must publish the items in your product - list (sword_001 and potion_001) even though you are not publishing the - sample application. Also, you must have a Google Checkout Merchant account to add items to the - sample application's product list.

      -
    4. -
    - -

    Running the sample application

    - -

    You cannot run the sample application in the emulator. You must install the sample application -onto a device to run it. To run the sample application, do the following:

    - -
      -
    1. Make sure you have at least one test account registered under your Google Play - publisher account. -

      You cannot purchase items from yourself (Google Checkout prohibits this), so you need to - create at least one test account that you can use to purchase items in the sample application. - To learn how to set up a test account, see Setting up Test - Accounts.

      -
    2. -
    3. Verify that your device is running a supported version of the Google Play - application or the MyApps application. -

      If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of - the MyApps application. If your device is running any other version of Android, in-app billing - requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the - version of the Google Play application, see Updating Google - Play.

      -
    4. -
    5. Install the application onto your device. -

      Even though you uploaded the application to Google Play, the application is not published, - so you cannot download it from Google Play to a device. Instead, you must install the - application onto your device. To learn how to install an application onto a device, see Running on a - device.

      -
    6. -
    7. Make one of your test accounts the primary account on your device. -

      The primary account on your device must be one of the test accounts - that you registered on the Google Play publisher site. If the primary account on your device is not a - test account, you must do a factory reset of the device and then sign in with one of your test - accounts. To perform a factory reset, do the following:

      -
        -
      1. Open Settings on your device.
      2. -
      3. Touch Privacy.
      4. -
      5. Touch Factory data reset.
      6. -
      7. Touch Reset phone.
      8. -
      9. After the phone resets, be sure to sign in with one of your test accounts during the - device setup process.
      10. -
      -
    8. -
    9. Run the application and purchase the sword or the potion. -

      When you use a test account to purchase items, the test account is billed through Google - Checkout and your Google Checkout Merchant account receives a payout for the purchase. - Therefore, you may want to refund purchases that are made with test accounts, otherwise the - purchases will show up as actual payouts to your merchant account.

      -
    - -

    Note: Debug log messages are turned off by default in the -sample application. You can turn them on by setting the variable DEBUG -to true in the Consts.java file.

    - -

    Adding the AIDL file to your project

    - -

    The sample application contains an Android Interface Definition Language (AIDL) file, which -defines the interface to Google Play's in-app billing service -(MarketBillingService). When you add this file to your project, the Android build -environment creates an interface file (IMarketBillingService.java). You can then use -this interface to make billing requests by invoking IPC method calls.

    - -

    If you are using the ADT plug-in with Eclipse, you can just add this file to your -/src directory. Eclipse will automatically generate the interface file when you build -your project (which should happen immediately). If you are not using the ADT plug-in, you can put -the AIDL file into your project and use the Ant tool to build your project so that the -IMarketBillingService.java file gets generated.

    - -

    To add the IMarketBillingService.aidl file to your project, do the following:

    - -
      -
    1. Create the following directory in your application's /src directory: -

      com/android/vending/billing/

      -
    2. -
    3. Copy the IMarketBillingService.aidl file into the - sample/src/com/android/vending/billing/ directory.
    4. -
    5. Build your application.
    6. -
    - -

    You should now find a generated interface file named IMarketBillingService.java in -the gen folder of your project.

    - -

    Updating Your Application's Manifest

    - -

    In-app billing relies on the Google Play application, which handles all communication between -your application and the Google Play server. To use the Google Play application, your -application must request the proper permission. You can do this by adding the -com.android.vending.BILLING permission to your AndroidManifest.xml file. If your -application does not declare the in-app billing permission, but attempts to send billing requests, -Google Play will refuse the requests and respond with a RESULT_DEVELOPER_ERROR -response code.

    - -

    In addition to the billing permission, you need to declare the {@link -android.content.BroadcastReceiver} that you will use to receive asynchronous response messages -(broadcast intents) from Google Play, and you need to declare the {@link android.app.Service} -that you will use to bind with the IMarketBillingService and send messages to Google -Play. You must also declare intent filters for the {@link -android.content.BroadcastReceiver} so that the Android system knows how to handle the broadcast -intents that are sent from the Google Play application.

    - -

    For example, here is how the in-app billing sample application declares the billing permission, -the {@link android.content.BroadcastReceiver}, the {@link android.app.Service}, and the intent -filters. In the sample application, BillingReceiver is the {@link -android.content.BroadcastReceiver} that handles broadcast intents from the Google Play -application and BillingService is the {@link android.app.Service} that sends requests -to the Google Play application.

    - -
    -<?xml version="1.0" encoding="utf-8"?>
    -<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    -  package="com.example.dungeons"
    -  android:versionCode="1"
    -  android:versionName="1.0">
    -
    -  <uses-permission android:name="com.android.vending.BILLING" />
    -
    -  <application android:icon="@drawable/icon" android:label="@string/app_name">
    -    <activity android:name=".Dungeons" android:label="@string/app_name">
    -      <intent-filter>
    -        <action android:name="android.intent.action.MAIN" />
    -        <category android:name="android.intent.category.LAUNCHER" />
    -      </intent-filter>
    -    </activity>
    -
    -    <service android:name="BillingService" />
    -
    -    <receiver android:name="BillingReceiver">
    -      <intent-filter>
    -        <action android:name="com.android.vending.billing.IN_APP_NOTIFY" />
    -        <action android:name="com.android.vending.billing.RESPONSE_CODE" />
    -        <action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" />
    -      </intent-filter>
    -    </receiver>
    -
    -  </application>
    -</manifest>
    -
    - -

    Creating a Local Service

    - -

    Your application must have a local {@link android.app.Service} to facilitate messaging between -your application and Google Play. At a minimum, this service must do the following:

    - -
      -
    • Bind to the MarketBillingService. -
    • Send billing requests (as IPC method calls) to the Google Play application. The five types - of billing requests include: -
        -
      • CHECK_BILLING_SUPPORTED requests
      • -
      • REQUEST_PURCHASE requests
      • -
      • GET_PURCHASE_INFORMATION requests
      • -
      • CONFIRM_NOTIFICATIONS requests
      • -
      • RESTORE_TRANSACTIONS requests
      • -
      -
    • -
    • Handle the synchronous response messages that are returned with each billing request.
    • -
    - -

    Binding to the MarketBillingService

    - -

    Binding to the MarketBillingService is relatively easy if you've already added the -IMarketBillingService.aidl file to your project. The following code sample shows how to -use the {@link android.content.Context#bindService bindService()} method to bind a service to the -MarketBillingService. You could put this code in your service's {@link -android.app.Activity#onCreate onCreate()} method.

    - -
    -try {
    -  boolean bindResult = mContext.bindService(
    -    new Intent("com.android.vending.billing.MarketBillingService.BIND"), this,
    -    Context.BIND_AUTO_CREATE);
    -  if (bindResult) {
    -    Log.i(TAG, "Service bind successful.");
    -  } else {
    -    Log.e(TAG, "Could not bind to the MarketBillingService.");
    -  }
    -} catch (SecurityException e) {
    -  Log.e(TAG, "Security exception: " + e);
    -}
    -
    - -

    After you bind to the service, you need to create a reference to the -IMarketBillingService interface so you can make billing requests via IPC method calls. -The following code shows you how to do this using the {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method.

    - -
    -/**
    -  * The Android system calls this when we are connected to the MarketBillingService.
    -  */
    -  public void onServiceConnected(ComponentName name, IBinder service) {
    -    Log.i(TAG, "MarketBillingService connected.");
    -    mService = IMarketBillingService.Stub.asInterface(service);
    -  }
    -
    - -

    You can now use the mService reference to invoke the -sendBillingRequest() method.

    - -

    For a complete implementation of a service that binds to the MarketBillingService, -see the BillingService class in the sample application.

    - -

    Sending billing requests to the MarketBillingService

    - -

    Now that your {@link android.app.Service} has a reference to the -IMarketBillingService interface, you can use that reference to send billing requests -(via IPC method calls) to the MarketBillingService. The -MarketBillingService IPC interface exposes a single public method -(sendBillingRequest()), which takes a single {@link android.os.Bundle} parameter. The -Bundle that you deliver with this method specifies the type of request you want to perform, using -various key-value pairs. For instance, one key indicates the type of request you are making, another -indicates the item being purchased, and another identifies your application. The -sendBillingRequest() method immediately returns a Bundle containing an initial response -code. However, this is not the complete purchase response; the complete response is delivered with -an asynchronous broadcast intent. For more information about the various Bundle keys that are -supported by the MarketBillingService, see In-app Billing -Service Interface.

    - -

    You can use the sendBillingRequest() method to send five types of billing requests. -The five request types are specified using the BILLING_REQUEST Bundle key. This Bundle -key can have the following five values:

    - -
      -
    • CHECK_BILLING_SUPPORTED—verifies that the Google Play application - supports in-app billing.
    • -
    • REQUEST_PURCHASE—sends a purchase request for an in-app item.
    • -
    • GET_PURCHASE_INFORMATION—retrieves transaction information for a purchase - or refund.
    • -
    • CONFIRM_NOTIFICATIONS—acknowledges that you received the transaction - information for a purchase or refund.
    • -
    • RESTORE_TRANSACTIONS—retrieves a user's transaction history for managed - purchases.
    • -
    - -

    To make any of these billing requests, you first need to build an initial {@link -android.os.Bundle} that contains the three keys that are required for all requests: -BILLING_REQUEST, API_VERSION, and PACKAGE_NAME. The following -code sample shows you how to create a helper method named makeRequestBundle() that does -this.

    - -
    -protected Bundle makeRequestBundle(String method) {
    -  Bundle request = new Bundle();
    -  request.putString(BILLING_REQUEST, method);
    -  request.putInt(API_VERSION, 1);
    -  request.putString(PACKAGE_NAME, getPackageName());
    -  return request;
    -
    - -

    To use this helper method, you pass in a String that corresponds to one of the five -types of billing requests. The method returns a Bundle that has the three required keys defined. The -following sections show you how to use this helper method when you send a billing request.

    - -

    Important: You must make all in-app billing requests from your -application's main thread.

    - -

    Verifying that in-app billing is supported (CHECK_BILLING_SUPPPORTED)

    - -

    The following code sample shows how to verify whether the Google Play application supports -in-app billing. In the sample, mService is an instance of the -MarketBillingService interface.

    - -
    -/**
    -* Request type is CHECK_BILLING_SUPPORTED
    -*/
    -  Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED");
    -  Bundle response = mService.sendBillingRequest(request);
    -  // Do something with this response.
    -}
    -
    -

    The makeRequestBundle() method constructs an initial Bundle, which contains the -three keys that are required for all requests: BILLING_REQUEST, -API_VERSION, and PACKAGE_NAME. The request returns a synchronous {@link -android.os.Bundle} response, which contains only a single key: RESPONSE_CODE. The -RESPONSE_CODE key can have the following values:

    -
      -
    • RESULT_OK—in-app billing is supported.
    • -
    • RESULT_BILLING_UNAVAILABLE—in-app billing is not available because the API - version you specified is not recognized or the user is not eligible to make in-app purchases (for - example, the user resides in a country that prohibits in-app purchases).
    • -
    • RESULT_ERROR—there was an error connecting with the Google Play - application.
    • -
    • RESULT_DEVELOPER_ERROR—the application is trying to make an in-app billing - request but the application has not declared the com.android.vending.BILLING - permission in its manifest. Can also indicate that an application is not properly signed, or that - you sent a malformed request.
    • -
    - -

    The CHECK_BILLING_SUPPORTED request does not trigger any asynchronous responses -(broadcast intents).

    - -

    We recommend that you invoke the CHECK_BILLING_SUPPORTED request within a -RemoteException block. When your code throws a RemoteException it -indicates that the remote method call failed, which means that the Google Play application is out -of date and needs to be updated. In this case, you can provide users with an error message that -contains a link to the Updating Google Play -Help topic.

    - -

    The sample application demonstrates how you can handle this error condition (see -DIALOG_CANNOT_CONNECT_ID in Dungeons.java).

    - -

    Making a purchase request (REQUEST_PURCHASE)

    - -

    To make a purchase request you must do the following:

    - -
      -
    • Send the REQUEST_PURCHASE request.
    • -
    • Launch the {@link android.app.PendingIntent} that is returned from the Google Play - application.
    • -
    • Handle the broadcast intents that are sent by the Google Play application.
    • -
    - -
    Making the request
    - -

    You must specify four keys in the request {@link android.os.Bundle}. The following code sample -shows how to set these keys and make a purchase request for a single in-app item. In the sample, -mProductId is the Google Play product ID of an in-app item (which is listed in the -application's product -list), and mService is an instance of the MarketBillingService -interface.

    - -
    -/**
    -* Request type is REQUEST_PURCHASE
    -*/
    -  Bundle request = makeRequestBundle("REQUEST_PURCHASE");
    -  request.putString(ITEM_ID, mProductId);
    -  // Note that the developer payload is optional.
    -  if (mDeveloperPayload != null) {
    -    request.putString(DEVELOPER_PAYLOAD, mDeveloperPayload);
    -  }
    -  Bundle response = mService.sendBillingRequest(request);
    -  // Do something with this response.
    -
    -

    The makeRequestBundle() method constructs an initial Bundle, which contains the -three keys that are required for all requests: BILLING_REQUEST, -API_VERSION, and PACKAGE_NAME. The ITEM_ID key is then added -to the Bundle prior to invoking the sendBillingRequest() method.

    - -

    The request returns a synchronous {@link android.os.Bundle} response, which contains three keys: -RESPONSE_CODE, PURCHASE_INTENT, and REQUEST_ID. The -RESPONSE_CODE key provides you with the status of the request and the -REQUEST_ID key provides you with a unique request identifier for the request. The -PURCHASE_INTENT key provides you with a {@link android.app.PendingIntent}, which you -can use to launch the checkout UI.

    - -
    Using the pending intent
    - -

    How you use the pending intent depends on which version of Android a device is running. On -Android 1.6, you must use the pending intent to launch the checkout UI in its own separate task -instead of your application's activity stack. On Android 2.0 and higher, you can use the pending -intent to launch the checkout UI on your application's activity stack. The following code shows you -how to do this. You can find this code in the PurchaseObserver.java file in the sample -application.

    - -
    -void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) {
    -  if (mStartIntentSender != null) {
    -    // This is on Android 2.0 and beyond.  The in-app checkout page activity
    -    // will be on the activity stack of the application.
    -    try {
    -      // This implements the method call:
    -      // mActivity.startIntentSender(pendingIntent.getIntentSender(),
    -      //     intent, 0, 0, 0);
    -      mStartIntentSenderArgs[0] = pendingIntent.getIntentSender();
    -      mStartIntentSenderArgs[1] = intent;
    -      mStartIntentSenderArgs[2] = Integer.valueOf(0);
    -      mStartIntentSenderArgs[3] = Integer.valueOf(0);
    -      mStartIntentSenderArgs[4] = Integer.valueOf(0);
    -      mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs);
    -    } catch (Exception e) {
    -      Log.e(TAG, "error starting activity", e);
    -      }
    -  } else {
    -    // This is on Android 1.6. The in-app checkout page activity will be on its
    -    // own separate activity stack instead of on the activity stack of
    -    // the application.
    -    try {
    -      pendingIntent.send(mActivity, 0 /* code */, intent);
    -    } catch (CanceledException e) {
    -      Log.e(TAG, "error starting activity", e);
    -      }
    -  }
    -}
    -
    - -

    Important: You must launch the pending intent from an activity -context and not an application context. Also, you cannot use the singleTop launch mode to launch the -pending intent. If you do either of these, the Android system will not attach the pending intent to -your application process. Instead, it will bring Google Play to the foreground, disrupting your -application.

    - -
    Handling broadcast intents
    - -

    A REQUEST_PURCHASE request also triggers two asynchronous responses (broadcast -intents). First, the Google Play application sends a RESPONSE_CODE broadcast intent, -which provides error information about the request. If the request does not generate an -error, the RESPONSE_CODE broadcast intent returns RESULT_OK, which -indicates that the request was successfully sent. (To be clear, a RESULT_OK response -does not indicate that the requested purchase was successful; it indicates that the request was sent -successfully to Google Play.)

    - -

    Next, when the requested transaction changes state (for example, the purchase is successfully -charged to a credit card or the user cancels the purchase), the Google Play application sends an -IN_APP_NOTIFY broadcast intent. This message contains a notification ID, which you can -use to retrieve the transaction details for the REQUEST_PURCHASE request.

    - -

    Note: The Google Play application also sends -an IN_APP_NOTIFY for refunds. For more information, see Handling -IN_APP_NOTIFY messages.

    - -

    Because the purchase process is not instantaneous and can take several seconds (or more), you -must assume that a purchase request is pending from the time you receive a RESULT_OK -message until you receive an IN_APP_NOTIFY message for the transaction. While the -transaction is pending, the Google Play checkout UI displays an "Authorizing purchase..." -notification; however, this notification is dismissed after 60 seconds and you should not rely on -this notification as your primary means of conveying transaction status to users. Instead, we -recommend that you do the following:

    - -
      -
    • Add an {@link android.app.Activity} to your application that shows users the status of pending -and completed in-app purchases.
    • -
    • Use a status -bar notification to keep users informed about the progress of a purchase.
    • -
    - -

    To use these two UI elements, you could invoke a status bar notification with a ticker-text -message that says "Purchase pending" when your application receives a RESULT_OK -message. Then, when your application receives an IN_APP_NOTIFY message, you could -update the notification with a new message that says "Purchase succeeded" or "Purchase failed." When -a user touches the expanded status bar notification, you could launch the activity that shows the -status of pending and completed in-app purchases.

    - -

    If you use some other UI technique to inform users about the state of a pending transaction, -be sure that your pending status UI does not block your application. For example, you should avoid -using a hovering progress wheel to convey the status of a pending transaction because a pending -transaction could last a long time, particularly if a device loses network connectivity and cannot -receive transaction updates from Google Play.

    - -

    Important: If a user purchases a managed item, you must prevent -the user from purchasing the item again while the original transaction is pending. If a user -attempts to purchase a managed item twice, and the first transaction is still pending, Google -Play will display an error to the user; however, Google Play will not send an error to your -application notifying you that the second purchase request was canceled. This might cause your -application to get stuck in a pending state while it waits for an IN_APP_NOTIFY message -for the second purchase request.

    - -

    Retrieving transaction information for a purchase or refund (GET_PURCHASE_INFORMATION)

    - -

    You retrieve transaction information in response to an IN_APP_NOTIFY broadcast -intent. The IN_APP_NOTIFY message contains a notification ID, which you can use to -retrieve transaction information.

    - -

    To retrieve transaction information for a purchase or refund you must specify five keys in the -request {@link android.os.Bundle}. The following code sample shows how to set these keys and make -the request. In the sample, mService is an instance of the -MarketBillingService interface.

    - -
    -/**
    -* Request type is GET_PURCHASE_INFORMATION
    -*/
    -  Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION");
    -  request.putLong(REQUEST_NONCE, mNonce);
    -  request.putStringArray(NOTIFY_IDS, mNotifyIds);
    -  Bundle response = mService.sendBillingRequest(request);
    -  // Do something with this response.
    -}
    -
    -

    The makeRequestBundle() method constructs an initial Bundle, which contains the -three keys that are required for all requests: BILLING_REQUEST, -API_VERSION, and PACKAGE_NAME. The additional keys are then added to the -bundle prior to invoking the sendBillingRequest() method. The -REQUEST_NONCE key contains a cryptographically secure nonce (number used once) that you -must generate. The Google Play application returns this nonce with the -PURCHASE_STATE_CHANGED broadcast intent so you can verify the integrity of the -transaction information. The NOTIFY_IDS key contains an array of notification IDs, -which you received in the IN_APP_NOTIFY broadcast intent.

    - -

    The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: -RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides -you with the status of the request and the REQUEST_ID key provides you with a unique -request identifier for the request.

    - -

    A GET_PURCHASE_INFORMATION request also triggers two asynchronous responses -(broadcast intents). First, the Google Play application sends a RESPONSE_CODE -broadcast intent, which provides status and error information about the request. Next, if the -request was successful, the Google Play application sends a PURCHASE_STATE_CHANGED -broadcast intent. This message contains detailed transaction information. The transaction -information is contained in a signed JSON string (unencrypted). The message includes the signature -so you can verify the integrity of the signed string.

    - -

    Acknowledging transaction information (CONFIRM_NOTIFICATIONS)

    - -

    To acknowledge that you received transaction information you send a -CONFIRM_NOTIFICATIONS request. You must specify four keys in the request {@link -android.os.Bundle}. The following code sample shows how to set these keys and make the request. In -the sample, mService is an instance of the MarketBillingService -interface.

    - -
    -/**
    -* Request type is CONFIRM_NOTIFICATIONS
    -*/
    -  Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS");
    -  request.putStringArray(NOTIFY_IDS, mNotifyIds);
    -  Bundle response = mService.sendBillingRequest(request);
    -  // Do something with this response.
    -}
    -
    -

    The makeRequestBundle() method constructs an initial Bundle, which contains the -three keys that are required for all requests: BILLING_REQUEST, -API_VERSION, and PACKAGE_NAME. The additional NOTIFY_IDS key -is then added to the bundle prior to invoking the sendBillingRequest() method. The -NOTIFY_IDS key contains an array of notification IDs, which you received in an -IN_APP_NOTIFY broadcast intent and also used in a GET_PURCHASE_INFORMATION -request.

    - -

    The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: -RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides -you with the status of the request and the REQUEST_ID key provides you with a unique -request identifier for the request.

    - -

    A CONFIRM_NOTIFICATIONS request triggers a single asynchronous response—a -RESPONSE_CODE broadcast intent. This broadcast intent provides status and error -information about the request.

    - -

    You must send a confirmation when you receive transaction information from Google Play. If you -don't send a confirmation message, Google Play will continue sending -IN_APP_NOTIFY messages for the transactions you have not confirmed. Also, -your application must be able to handle IN_APP_NOTIFY messages that contain multiple -orders.

    - -

    In addition, as a best practice, you should not send a CONFIRM_NOTIFICATIONS request -for a purchased item until you have delivered the item to the user. This way, if your application -crashes or something else prevents your application from delivering the product, your application -will still receive an IN_APP_NOTIFY broadcast intent from Google Play indicating -that you need to deliver the product.

    - -

    Restoring transaction information (RESTORE_TRANSACTIONS)

    - -

    To restore a user's transaction information, you send a RESTORE_TRANSACTIONS -request. You must specify four keys in the request {@link android.os.Bundle}. The following code -sample shows how to set these keys and make the request. In the sample, mService is an -instance of the MarketBillingService interface.

    - -
    -/**
    -* Request type is RESTORE_TRANSACTIONS
    -*/
    -  Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS");
    -  request.putLong(REQUEST_NONCE, mNonce);
    -  Bundle response = mService.sendBillingRequest(request);
    -  // Do something with this response.
    -}
    -
    -

    The makeRequestBundle() method constructs an initial Bundle, which contains the -three keys that are required for all requests: BILLING_REQUEST, -API_VERSION, and PACKAGE_NAME. The additional REQUEST_NONCE -key is then added to the bundle prior to invoking the sendBillingRequest() method. The -REQUEST_NONCE key contains a cryptographically secure nonce (number used once) that you -must generate. The Google Play application returns this nonce with the transactions information -contained in the PURCHASE_STATE_CHANGED broadcast intent so you can verify the -integrity of the transaction information.

    - -

    The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: -RESPONSE_CODE and REQUEST_ID. The RESPONSE_CODE key provides -you with the status of the request and the REQUEST_ID key provides you with a unique -request identifier for the request.

    - -

    A RESTORE_TRANSACTIONS request also triggers two asynchronous responses (broadcast -intents). First, the Google Play application sends a RESPONSE_CODE broadcast intent, -which provides status and error information about the request. Next, if the request was successful, -the Google Play application sends a PURCHASE_STATE_CHANGED broadcast intent. This -message contains the detailed transaction information. The transaction information is contained in a -signed JSON string (unencrypted). The message includes the signature so you can verify the integrity -of the signed string.

    - -

    Note: You should use the RESTORE_TRANSACTIONS -request type only when your application is installed for the first time on a device or when your -application has been removed from a device and reinstalled.

    - -

    Other service tasks

    - -

    You may also want your {@link android.app.Service} to receive intent messages from your {@link -android.content.BroadcastReceiver}. You can use these intent messages to convey the information that -was sent asynchronously from the Google Play application to your {@link -android.content.BroadcastReceiver}. To see an example of how you can send and receive these intent -messages, see the BillingReceiver.java and BillingService.java files in -the sample application. You can use these samples as a basis for your own implementation. However, -if you use any of the code from the sample application, be sure you follow the guidelines in Security and Design.

    - -

    Creating a BroadcastReceiver

    - -

    The Google Play application uses broadcast intents to send asynchronous billing responses to -your application. To receive these intent messages, you need to create a {@link -android.content.BroadcastReceiver} that can handle the following intents:

    - -
      -
    • com.android.vending.billing.RESPONSE_CODE -

      This broadcast intent contains a Google Play response code, and is sent after you make an - in-app billing request. For more information about the response codes that are sent with this - response, see Google Play Response - Codes for In-app Billing.

      -
    • -
    • com.android.vending.billing.IN_APP_NOTIFY -

      This response indicates that a purchase has changed state, which means a purchase succeeded, - was canceled, or was refunded. For more information about notification messages, see In-app Billing - Broadcast Intents

      -
    • -
    • com.android.vending.billing.PURCHASE_STATE_CHANGED -

      This broadcast intent contains detailed information about one or more transactions. For more - information about purchase state messages, see In-app Billing - Broadcast Intents

      -
    • -
    - -

    Each of these broadcast intents provide intent extras, which your {@link -android.content.BroadcastReceiver} must handle. The intent extras are listed in the following table -(see table 1).

    - -

    Table 1. Description of broadcast intent extras that are -sent in response to billing requests.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    IntentExtraDescription
    com.android.vending.billing.RESPONSE_CODErequest_idA long representing a request ID. A request ID identifies a specific billing - request and is returned by Google Play at the time a request is made.
    com.android.vending.billing.RESPONSE_CODEresponse_codeAn int representing the actual Google Play server response code.
    com.android.vending.billing.IN_APP_NOTIFYnotification_idA String representing the notification ID for a given purchase state change. - Google Play notifies you when there is a purchase state change and the notification includes a - unique notification ID. To get the details of the purchase state change, you send the notification - ID with the GET_PURCHASE_INFORMATION request.
    com.android.vending.billing.PURCHASE_STATE_CHANGEDinapp_signed_dataA String representing the signed JSON string. The JSON string contains - information about the billing transaction, such as order number, amount, and the item that was - purchased or refunded.
    com.android.vending.billing.PURCHASE_STATE_CHANGEDinapp_signatureA String representing the signature of the JSON string.
    - -

    The following code sample shows how to handle these broadcast intents and intent extras within a -{@link android.content.BroadcastReceiver}. The BroadcastReceiver in this case is named -BillingReceiver, just as it is in the sample application.

    - -
    -public class BillingReceiver extends BroadcastReceiver {
    -
    -  private static final String TAG = "BillingReceiver";
    -
    -  // Intent actions that we receive in the BillingReceiver from Google Play.
    -  // These are defined by Google Play and cannot be changed.
    -  // The sample application defines these in the Consts.java file.
    -  public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
    -  public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE";
    -  public static final String ACTION_PURCHASE_STATE_CHANGED =
    -    "com.android.vending.billing.PURCHASE_STATE_CHANGED";
    -
    -  // The intent extras that are passed in an intent from Google Play.
    -  // These are defined by Google Play and cannot be changed.
    -  // The sample application defines these in the Consts.java file.
    -  public static final String NOTIFICATION_ID = "notification_id";
    -  public static final String INAPP_SIGNED_DATA = "inapp_signed_data";
    -  public static final String INAPP_SIGNATURE = "inapp_signature";
    -  public static final String INAPP_REQUEST_ID = "request_id";
    -  public static final String INAPP_RESPONSE_CODE = "response_code";
    -
    -
    -  @Override
    -  public void onReceive(Context context, Intent intent) {
    -    String action = intent.getAction();
    -    if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
    -      String signedData = intent.getStringExtra(INAPP_SIGNED_DATA);
    -      String signature = intent.getStringExtra(INAPP_SIGNATURE);
    -      // Do something with the signedData and the signature.
    -    } else if (ACTION_NOTIFY.equals(action)) {
    -      String notifyId = intent.getStringExtra(NOTIFICATION_ID);
    -      // Do something with the notifyId.
    -    } else if (ACTION_RESPONSE_CODE.equals(action)) {
    -      long requestId = intent.getLongExtra(INAPP_REQUEST_ID, -1);
    -      int responseCodeIndex = intent.getIntExtra(INAPP_RESPONSE_CODE,
    -        ResponseCode.RESULT_ERROR.ordinal());
    -      // Do something with the requestId and the responseCodeIndex.
    -    } else {
    -      Log.w(TAG, "unexpected action: " + action);
    -    }
    -  }
    -  // Perform other processing here, such as forwarding intent messages to your local service.
    -}
    -
    - -

    In addition to receiving broadcast intents from the Google Play application, your {@link -android.content.BroadcastReceiver} must handle the information it received in the broadcast intents. -Usually, your {@link android.content.BroadcastReceiver} does this by sending the information to a -local service (discussed in the next section). The BillingReceiver.java file in the -sample application shows you how to do this. You can use this sample as a basis for your own {@link -android.content.BroadcastReceiver}. However, if you use any of the code from the sample application, -be sure you follow the guidelines that are discussed in Security and Design .

    - -

    Verifying Signatures and Nonces

    - -

    Google Play's in-app billing service uses two mechanisms to help verify the integrity of the -transaction information you receive from Google Play: nonces and signatures. A nonce (number used -once) is a cryptographically secure number that your application generates and sends with every -GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS request. The nonce is -returned with the PURCHASE_STATE_CHANGED broadcast intent, enabling you to verify that -any given PURCHASE_STATE_CHANGED response corresponds to an actual request that you -made. Every PURCHASE_STATE_CHANGED broadcast intent also includes a signed JSON string -and a signature, which you can use to verify the integrity of the response.

    - -

    Your application must provide a way to generate, manage, and verify nonces. The following sample -code shows some simple methods you can use to do this.

    - -
    -  private static final SecureRandom RANDOM = new SecureRandom();
    -  private static HashSet<Long> sKnownNonces = new HashSet<Long>();
    -
    -  public static long generateNonce() {
    -    long nonce = RANDOM.nextLong();
    -    sKnownNonces.add(nonce);
    -    return nonce;
    -  }
    -
    -  public static void removeNonce(long nonce) {
    -    sKnownNonces.remove(nonce);
    -  }
    -
    -  public static boolean isNonceKnown(long nonce) {
    -    return sKnownNonces.contains(nonce);
    -  }
    -
    - -

    Your application must also provide a way to verify the signatures that accompany every -PURCHASE_STATE_CHANGED broadcast intent. The Security.java file in the -sample application shows you how to do this. If you use this file as a basis for your own security -implementation, be sure to follow the guidelines in Security and Design and -obfuscate your code.

    - -

    You will need to use your Google Play public key to perform the signature verification. The -following procedure shows you how to retrieve Base64-encoded public key from the Google Play -publisher site.

    - -
      -
    1. Log in to your publisher account.
    2. -
    3. On the upper left part of the page, under your name, click Edit profile.
    4. -
    5. On the Edit Profile page, scroll down to the Licensing & In-app Billing panel (see figure - 2).
    6. -
    7. Copy your public key.
    8. -
    - -

    Important: To keep your public key safe from malicious users and -hackers, do not embed your public key as an entire literal string. Instead, construct the string at -runtime from pieces or use bit manipulation (for example, XOR with some other string) to hide the -actual key. The key itself is not secret information, but you do not want to make it easy for a -hacker or malicious user to replace the public key with another key.

    - - -

    - Figure 2. The Licensing and In-app Billing panel of your account's Edit Profile - page lets you see your public key. -

    - -

    Modifying Your Application Code

    - -

    After you finish adding in-app billing components to your project, you are ready to modify your -application's code. For a typical implementation, like the one that is demonstrated in the sample -application, this means you need to write code to do the following:

    - -
      -
    • Create a storage mechanism for storing users' purchase information.
    • -
    • Create a user interface that lets users select items for purchase.
    • -
    - -

    The sample code in Dungeons.java shows you how to do both of these tasks.

    - -

    Creating a storage mechanism for storing purchase information

    - -

    You must set up a database or some other mechanism for storing users' purchase information. The -sample application provides an example database (PurchaseDatabase.java); however, the example -database has been simplified for clarity and does not exhibit the security best practices that we -recommend. If you have a remote server, we recommend that you store purchase information on your -server instead of in a local database on a device. For more information about security best -practices, see Security and -Design.

    - -

    Note: If you store any purchase information on a device, be sure to -encrypt the data and use a device-specific encryption key. Also, if the purchase type for any of -your items is "unmanaged," we recommend that you back up the purchase information for these items to -a remote server or use Android's data -backup framework to back up the purchase information. Backing up purchase information for -unmanaged items is important because unmanaged items cannot be restored by using the -RESTORE_TRANSACTIONS request type.

    - -

    Creating a user interface for selecting items

    - -

    You must provide users with a means for selecting items that they want to purchase. Google -Play provides the checkout user interface (which is where the user provides a form of payment and -approves the purchase), but your application must provide a control (widget) that invokes the -sendBillingRequest() method when a user selects an item for purchase.

    - -

    You can render the control and trigger the sendBillingRequest() method any way you -want. The sample application uses a spinner widget and a button to present items to a user and -trigger a billing request (see Dungeons.java). The user interface also shows a list of -recently purchased items.

    - diff --git a/docs/html/guide/market/billing/billing_overview.jd b/docs/html/guide/market/billing/billing_overview.jd deleted file mode 100755 index b59381140eca..000000000000 --- a/docs/html/guide/market/billing/billing_overview.jd +++ /dev/null @@ -1,469 +0,0 @@ -page.title=In-app Billing Overview -parent.title=In-app Billing -parent.link=index.html -@jd:body - - - -

    In-app Billing is a Google Play service that provides checkout processing for -in-app purchases. To use the service, your application sends a billing request for a specific in-app -product. The service then handles all of the checkout details for the transaction, including -requesting and validating the form of payment and processing the financial transaction. When the -checkout process is complete, the service sends your application the purchase details, such as the -order number, the order date and time, and the price paid. At no point does your application have to -handle any financial transactions; that role is provided by Google Play's in-app billing -service.

    - -

    In-app Billing Architecture

    - -

    In-app billing uses an asynchronous message loop to convey billing requests and billing responses -between your application and the Google Play server. In practice, your application never directly -communicates with the Google Play server (see figure 1). Instead, your application sends billing -requests to the Google Play application over interprocess communication (IPC) and receives -purchase responses from the Google Play application in the form of asynchronous broadcast -intents. Your application does not manage any network connections between itself and the Google -Play server or use any special APIs from the Android platform.

    - -

    Some in-app billing implementations may also use a private remote server to deliver content or -validate transactions, but a remote server is not required to implement in-app billing. A remote -server can be useful if you are selling digital content that needs to be delivered to a user's -device, such as media files or photos. You might also use a remote server to store users' -transaction history or perform various in-app billing security tasks, such as signature -verification. Although you can handle all security-related tasks in your application, performing -those tasks on a remote server is recommended because it helps make your application less vulnerable -to security attacks.

    - -
    - -

    - Figure 1. Your application sends and receives billing messages through the - Google Play application, which handles all communication with the Google Play server.

    -
    - -

    A typical in-app billing implementation relies on three components:

    -
      -
    • A {@link android.app.Service} (named BillingService in the sample application), - which processes purchase messages from the application and sends billing requests to the Google - Play in-app billing service.
    • -
    • A {@link android.content.BroadcastReceiver} (named BillingReceiver in the sample - application), which receives all asynchronous billing responses from the Google Play - application.
    • -
    • A security component (named Security in the sample application), which performs - security-related tasks, such as signature verification and nonce generation. For more information - about in-app billing security, see Security controls later in this - document.
    • -
    - -

    You may also want to incorporate two other components to support in-app billing:

    -
      -
    • A response {@link android.os.Handler} (named ResponseHandler in the sample - application), which provides application-specific processing of purchase notifications, errors, - and other status messages.
    • -
    • An observer (named PurchaseObserver in the sample application), which is - responsible for sending callbacks to your application so you can update your user interface with - purchase information and status.
    • -
    - -

    In addition to these components, your application must provide a way to store information about -users' purchases and some sort of user interface that lets users select items to purchase. You do -not need to provide a checkout user interface. When a user initiates an in-app purchase, the Google -Play application presents the checkout user interface to your user. When the user completes the -checkout process, your application resumes.

    - -

    In-app Billing Messages

    - -

    When the user initiates a purchase, your application sends billing messages to Google Play's -in-app billing service (named MarketBillingService) using simple IPC method calls. The -Google Play application responds to all billing requests synchronously, providing your -application with status notifications and other information. The Google Play application also -responds to some billing requests asynchronously, providing your application with error messages and -detailed transaction information. The following section describes the basic request-response -messaging that takes place between your application and the Google Play application.

    - -

    In-app billing requests

    - -

    Your application sends in-app billing requests by invoking a single IPC method -(sendBillingRequest()), which is exposed by the MarketBillingService -interface. This interface is defined in an Android Interface Definition Language file -(IMarketBillingService.aidl). You can download this AIDL -file with the in-app billing sample application.

    - -

    The sendBillingRequest() method has a single {@link android.os.Bundle} parameter. -The Bundle that you deliver must include several key-value pairs that specify various parameters for -the request, such as the type of billing request you are making, the item that is being purchased, -and the application that is making the request. For more information about the Bundle keys that are -sent with a request, see In-app Billing -Service Interface. - -

    One of the most important keys that every request Bundle must have is the -BILLING_REQUEST key. This key lets you specify the type of billing request you are -making. Google Play's in-app billing service supports the following five types of billing -requests:

    - -
      -
    • CHECK_BILLING_SUPPORTED -

      This request verifies that the Google Play application supports in-app billing. You - usually send this request when your application first starts up. This request is useful if you - want to enable or disable certain UI features that are relevant only to in-app billing.

      -
    • -
    • REQUEST_PURCHASE -

      This request sends a purchase message to the Google Play application and is the foundation - of in-app billing. You send this request when a user indicates that he or she wants to purchase - an item in your application. Google Play then handles the financial transaction by displaying - the checkout user interface.

      -
    • -
    • GET_PURCHASE_INFORMATION -

      This request retrieves the details of a purchase state change. A purchase changes state when - a requested purchase is billed successfully or when a user cancels a transaction during - checkout. It can also occur when a previous purchase is refunded. Google Play notifies your - application when a purchase changes state, so you only need to send this request when there is - transaction information to retrieve.

      -
    • -
    • CONFIRM_NOTIFICATIONS -

      This request acknowledges that your application received the details of a purchase state - change. Google Play sends purchase state change notifications to your application until you - confirm that you received them.

      -
    • -
    • RESTORE_TRANSACTIONS -

      This request retrieves a user's transaction status for managed - purchases. You should send this request only when you need to retrieve a user's transaction - status, which is usually only when your application is reinstalled or installed for the first - time on a device.

      -
    • -
    - -

    In-app Billing Responses

    - -

    The Google Play application responds to in-app billing requests with both synchronous and -asynchronous responses. The synchronous response is a {@link android.os.Bundle} with the following -three keys:

    - -
      -
    • RESPONSE_CODE -

      This key provides status information and error information about a request.

      -
    • -
    • PURCHASE_INTENT -

      This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout - activity.

      -
    • -
    • REQUEST_ID -

      This key provides you with a request identifier, which you can use to match asynchronous - responses with requests.

      -
    • -
    -

    Some of these keys are not relevant to every request. For more information, see Messaging sequence later in this document.

    - -

    The asynchronous response messages are sent in the form of individual broadcast intents and -include the following:

    - -
      -
    • com.android.vending.billing.RESPONSE_CODE -

      This response contains a Google Play server response code, and is sent after you make an - in-app billing request. A server response code can indicate that a billing request was - successfully sent to Google Play or it can indicate that some error occurred during a billing - request. This response is not used to report any purchase state changes (such as refund - or purchase information). For more information about the response codes that are sent with this - response, see Server Response Codes - for In-app Billing.

      -
    • -
    • com.android.vending.billing.IN_APP_NOTIFY -

      This response indicates that a purchase has changed state, which means a purchase succeeded, - was canceled, or was refunded. This response contains one or more notification IDs. Each - notification ID corresponds to a specific server-side message, and each messages contains - information about one or more transactions. After your application receives an - IN_APP_NOTIFY broadcast intent, you send a GET_PURCHASE_INFORMATION - request with the notification IDs to retrieve message details.

      -
    • -
    • com.android.vending.billing.PURCHASE_STATE_CHANGED -

      This response contains detailed information about one or more transactions. The transaction - information is contained in a JSON string. The JSON string is signed and the signature is sent - to your application along with the JSON string (unencrypted). To help ensure the security of - your in-app billing messages, your application can verify the signature of this JSON string.

      -
    • -
    - -

    The JSON string that is returned with the PURCHASE_STATE_CHANGED intent provides -your application with the details of one or more billing transactions. An example of this JSON -string is shown below:

    -
    -{ "nonce" : 1836535032137741465,
    -  "orders" :
    -    { "notificationId" : "android.test.purchased",
    -      "orderId" : "transactionId.android.test.purchased",
    -      "packageName" : "com.example.dungeons",
    -      "productId" : "android.test.purchased",
    -      "developerPayload" : "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
    -      "purchaseTime" : 1290114783411,
    -      "purchaseState" : 0 }
    -}
    -
    - -

    For more information about the fields in this JSON string, see In-app Billing -Broadcast Intents.

    - -

    Messaging sequence

    - -

    The messaging sequence for a typical purchase request is shown in figure 2. Request types for -each sendBillingRequest() method are shown in bold, broadcast intents -are shown in italic. For clarity, figure 2 does not show the RESPONSE_CODE -broadcast intents that are sent for every request.

    - -

    The basic message sequence for an in-app purchase request is as follows:

    - -
      -
    1. Your application sends a purchase request (REQUEST_PURCHASE type), specifying a - product ID and other parameters.
    2. -
    3. The Google Play application sends your application a Bundle with the following keys: - RESPONSE_CODE, PURCHASE_INTENT, and REQUEST_ID. The - PURCHASE_INTENT key provides a {@link android.app.PendingIntent}, which your - application uses to start the checkout UI for the given product ID.
    4. -
    5. Your application launches the pending intent, which launches the checkout UI. -

      Note: You must launch the pending intent from an activity - context and not an application context.

      -
    6. -
    7. When the checkout flow finishes (that is, the user successfully purchases the item or cancels - the purchase), Google Play sends your application a notification message (an - IN_APP_NOTIFY broadcast intent). The notification message includes a notification ID, - which references the transaction.
    8. -
    9. Your application requests the transaction information by sending a - GET_PURCHASE_STATE_CHANGED request, specifying the notification ID for the - transaction.
    10. -
    11. The Google Play application sends a Bundle with a RESPONSE_CODE key and a - REQUEST_ID key. -
    12. Google Play sends the transaction information to your application in a - PURCHASE_STATE_CHANGED broadcast intent.
    13. -
    14. Your application confirms that you received the transaction information for the given - notification ID by sending a confirmation message (CONFIRM_NOTIFICATIONS type), - specifying the notification ID for which you received transaction information.
    15. -
    16. The Google Play application sends your application a Bundle with a - RESPONSE_CODE key and a REQUEST_ID key.
    17. -
    - - -

    - Figure 2. Message sequence for a purchase request. -

    - -

    Keep in mind, you must send a confirmation when you receive transaction information from Google -Play (step 8 in figure 2). If you don't send a confirmation message, Google Play will -continue sending IN_APP_NOTIFY messages for the transactions you have not -confirmed. As a best practice, you should not send a CONFIRM_NOTIFICATIONS request for -a purchased item until you have delivered the item to the user. This way, if your application -crashes or something else prevents your application from delivering the product, your application -will still receive an IN_APP_NOTIFY broadcast intent from Google Play indicating -that you need to deliver the product. Also, as a best practice, your application must be able to -handle IN_APP_NOTIFY messages that contain multiple orders.

    - -

    The messaging sequence for a restore transaction request is shown in figure 3. Request types for -each sendBillingRequest() method are shown in bold, broadcast intents -are shown in italic. For clarity, figure 3 does not show the RESPONSE_CODE -broadcast intents that are sent for every request.

    - -
    - -

    - Figure 3. Message sequence for a restore transactions request. -

    -
    - -

    The request triggers three responses. The first is a {@link android.os.Bundle} with a -RESPONSE_CODE key and a REQUEST_ID key. Next, the Google Play -application sends a RESPONSE_CODE broadcast intent, which provides status information -or error information about the request. As always, the RESPONSE_CODE message references -a specific request ID, so you can determine which request a RESPONSE_CODE message -pertains to.

    - -

    The RESTORE_TRANSACTIONS request type also triggers a -PURCHASE_STATE_CHANGED broadcast intent, which contains the same type of transaction -information that is sent during a purchase request, although you do not need to respond to this -intent with a CONFIRM_NOTIFICATIONS message.

    - -

    Note: You should use the RESTORE_TRANSACTIONS request -type only when your application is installed for the first time on a device or when your -application has been removed from a device and reinstalled.

    - -

    The messaging sequence for checking whether in-app billing is supported is shown in figure 4. The -request type for the sendBillingRequest() method is shown in bold.

    - -
    - -

    - Figure 4. Message sequence for checking whether in-app billing is supported. -

    -
    - -

    The synchronous response for a CHECK_BILLING_SUPPORTED request provides a Bundle -with a server response code. A RESULT_OK response code indicates that in-app billing -is supported; a RESULT_BILLING_UNAVAILABLE response code indicates that in-app billing -is unavailable because the API version you specified is unrecognized or the user is not eligible to -make in-app purchases (for example, the user resides in a country that does not allow in-app -billing). A SERVER_ERROR can also be returned, indicating that there was a problem with -the Google Play server.

    - -

    Handling IN_APP_NOTIFY messages

    - -

    Usually, your application receives an IN_APP_NOTIFY broadcast intent from Google -Play in response to a REQUEST_PURCHASE message (see figure 2). The -IN_APP_NOTIFY broadcast intent informs your application that the state of a requested -purchase has changed. To retrieve the details of that purchase, your application sends a -GET_PURCHASE_INFORMATION request. Google Play responds with a -PURCHASE_STATE_CHANGED broadcast intent, which contains the details of the purchase -state change. Your application then sends a CONFIRM_NOTIFICATIONS message, informing -Google Play that you have received the purchase state change information.

    - -

    In some special cases, you may receive multiple IN_APP_NOTIFY messages even though -you have confirmed receipt of the purchase information, or you may receive -IN_APP_NOTIFY messages for a purchase change even though you never initiated the -purchase. Your application must handle both of these special cases.

    - -

    Handling multiple IN_APP_NOTIFY messages

    - -

    When Google Play receives a CONFIRM_NOTIFICATIONS message for a given -PURCHASE_STATE_CHANGED message, it usually stops sending IN_APP_NOTIFY -intents for that PURCHASE_STATE_CHANGED message. Sometimes, however, Google -Play may send repeated IN_APP_NOTIFY intents for a -PURCHASE_STATE_CHANGED message even though your application has sent a -CONFIRM_NOTIFICATIONS message. This can occur if a device loses network connectivity -while you are sending the CONFIRM_NOTIFICATIONS message. In this case, Google Play -might not receive your CONFIRM_NOTIFICATIONS message and it could send multiple -IN_APP_NOTIFY messages until it receives acknowledgement that you received the -transaction message. Therefore, your application must be able to recognize that the subsequent -IN_APP_NOTIFY messages are for a previously processed transaction. You can do this by -checking the orderID that's contained in the JSON string because every transaction has -a unique orderId.

    - -

    Handling refunds and other unsolicited IN_APP_NOTIFY messages

    - -

    There are two cases where your application may receive IN_APP_NOTIFY broadcast -intents even though your application has not sent a REQUEST_PURCHASE message. Figure 5 -shows the messaging sequence for both of these cases. Request types for each -sendBillingRequest() method are shown in bold, broadcast intents are -shown in italic. For clarity, figure 5 does not show the RESPONSE_CODE -broadcast intents that are sent for every request.

    - -
    - -

    - Figure 5. Message sequence for refunds and other unsolicited -IN_APP_NOTIFY messages.

    -
    - -

    In the first case, your application may receive an IN_APP_NOTIFY broadcast intent -when a user has your application installed on two (or more) devices and the user makes an in-app -purchase from one of the devices. In this case, Google Play sends an IN_APP_NOTIFY -message to the second device, informing the application that there is a purchase state change. Your -application can handle this message the same way it handles the response from an -application-initiated REQUEST_PURCHASE message, so that ultimately your application -receives a PURCHASE_STATE_CHANGED broadcast intent message that includes information -about the item that has been purchased. This applies only to items that have their purchase type set -to "managed per user account."

    - -

    In the second case, your application can receive an IN_APP_NOTIFY broadcast intent -when Google Play receives a refund notification from Google Checkout. In this case, Google -Play sends an IN_APP_NOTIFY message to your application. Your application can handle -this message the same way it handles responses from an application-initiated -REQUEST_PURCHASE message so that ultimately your application receives a -PURCHASE_STATE_CHANGED message that includes information about the item that has been -refunded. The refund information is included in the JSON string that accompanies the -PURCHASE_STATE_CHANGED broadcast intent. Also, the purchaseState field in -the JSON string is set to 2.

    - -

    Important: You cannot use the Google Checkout API to -issue refunds or cancel in-app billing transactions. You must do this manually through your -Google Checkout merchant account. However, you can use the Google Checkout API to retrieve order -information.

    - -

    Security Controls

    - -

    To help ensure the integrity of the transaction information that is sent to your application, -Google Play signs the JSON string that is contained in the PURCHASE_STATE_CHANGED -broadcast intent. Google Play uses the private key that is associated with your publisher account -to create this signature. The publisher site generates an RSA key pair for each publisher account. -You can find the public key portion of this key pair on your account's profile page. It is the same -public key that is used with Google Play licensing.

    - -

    When Google Play signs a billing response, it includes the signed JSON string (unencrypted) -and the signature. When your application receives this signed response you can use the public key -portion of your RSA key pair to verify the signature. By performing signature verification you can -help detect responses that have been tampered with or that have been spoofed. You can perform this -signature verification step in your application; however, if your application connects to a secure -remote server then we recommend that you perform the signature verification on that server.

    - -

    In-app billing also uses nonces (a random number used once) to help verify the integrity of the -purchase information that's returned from Google Play. Your application must generate a nonce and -send it with a GET_PURCHASE_INFORMATION request and a RESTORE_TRANSACTIONS -request. When Google Play receives the request, it adds the nonce to the JSON string that -contains the transaction information. The JSON string is then signed and returned to your -application. When your application receives the JSON string, you need to verify the nonce as well as -the signature of the JSON string.

    - -

    For more information about best practices for security and design, see Security and Design.

    - -

    In-app Billing Requirements and Limitations

    - -

    Before you get started with in-app billing, be sure to review the following requirements and -limitations.

    - -
      -
    • In-app billing can be implemented only in applications that you publish through Google - Play.
    • -
    • You must have a Google Checkout Merchant account to use Google Play In-app Billing.
    • -
    • If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of - the MyApps application. If your device is running any other version of Android, in-app billing - requires version 2.3.4 (or higher) of the Google Play application.
    • -
    • An application can use in-app billing only if the device is running Android 1.6 (API level 4) - or higher.
    • -
    • You can use in-app billing to sell only digital content. You cannot use in-app billing to sell - physical goods, personal services, or anything that requires physical delivery.
    • -
    • Google Play does not provide any form of content delivery. You are responsible for - delivering the digital content that you sell in your applications.
    • -
    • You cannot implement in-app billing on a device that never connects to the network. To - complete in-app purchase requests, a device must be able to access the Google Play server over - the network.
    • -
    - -

    For more information about in-app billing requirements, see In-App Billing Availability -and Policies.

    diff --git a/docs/html/guide/market/billing/billing_reference.jd b/docs/html/guide/market/billing/billing_reference.jd deleted file mode 100755 index e8cf2ee86ec9..000000000000 --- a/docs/html/guide/market/billing/billing_reference.jd +++ /dev/null @@ -1,418 +0,0 @@ -page.title=In-app Billing Reference -parent.title=In-app Billing -parent.link=index.html -@jd:body - - - -

    The following document provides technical reference information for the following:

    - - - -

    Google Play Server Response Codes for In-app Billing

    - -

    The following table lists all of the server response codes that are sent from Google Play to -your application. Google Play sends these response codes asynchronously as -response_code extras in the com.android.vending.billing.RESPONSE_CODE -broadcast intent. Your application must handle all of these response codes.

    - -

    Table 1. Summary of response -codes returned by Google Play.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Response CodeValueDescription
    RESULT_OK0Indicates that the request was sent to the server successfully. When this code is returned in - response to a CHECK_BILLING_SUPPORTED request, indicates that billing is - supported.
    RESULT_USER_CANCELED1Indicates that the user pressed the back button on the checkout page instead of buying the - item.
    RESULT_SERVICE_UNAVAILABLE2Indicates that the network connection is down.
    RESULT_BILLING_UNAVAILABLE3Indicates that in-app billing is not available because the API_VERSION that you - specified is not recognized by the Google Play application or the user is ineligible for in-app - billing (for example, the user resides in a country that prohibits in-app purchases).
    RESULT_ITEM_UNAVAILABLE4Indicates that Google Play cannot find the requested item in the application's product - list. This can happen if the product ID is misspelled in your REQUEST_PURCHASE - request or if an item is unpublished in the application's product list.
    RESULT_DEVELOPER_ERROR5Indicates that an application is trying to make an in-app billing request but the application - has not declared the com.android.vending.BILLING permission in its manifest. Can also indicate - that an application is not properly signed, or that you sent a malformed request, such as a - request with missing Bundle keys or a request that uses an unrecognized request type.
    RESULT_ERROR6Indicates an unexpected server error. For example, this error is triggered if you try to -purchase an item from yourself, which is not allowed by Google Checkout.
    - -

    In-app Billing Service Interface

    - -

    The following section describes the interface for Google Play's in-app billing service. The -interface is defined in the IMarketBillingService.aidl file, which is included with the -in-app billing sample -application.

    -

    The interface consists of a single request method sendBillingRequest(). This method -takes a single {@link android.os.Bundle} parameter. The Bundle parameter includes several key-value -pairs, which are summarized in table 2.

    - -

    Table 2. Description of Bundle keys passed in a -sendBillingRequest() request.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    KeyTypePossible ValuesRequired?Description
    BILLING_REQUESTStringCHECK_BILLING_SUPPORTED, REQUEST_PURCHASE, - GET_PURCHASE_INFORMATION, CONFIRM_NOTIFICATIONS, or - RESTORE_TRANSACTIONSYesThe type of billing request you are making with the sendBillingRequest() request. - The possible values are discussed more below this table.
    API_VERSIONint1YesThe version of Google Play's in-app billing service you are using. The current version is - 1.
    PACKAGE_NAMEStringA valid package name.YesThe name of the application that is making the request.
    ITEM_IDStringAny valid product identifier.Required for REQUEST_PURCHASE requests.The product ID of the item you are making a billing request for. Every in-app item that you - sell using Google Play's in-app billing service must have a unique product ID, which you - specify on the Google Play publisher site.
    NONCElongAny valid long value.Required for GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS - requests.A number used once. Your application must generate and send a nonce with each - GET_PURCHASE_INFORMATION and RESTORE_TRANSACTIONS request. The nonce is - returned with the PURCHASE_STATE_CHANGED broadcast intent, so you can use this value - to verify the integrity of transaction responses form Google Play.
    NOTIFY_IDSArray of long valuesAny valid array of long valuesRequired for GET_PURCHASE_INFORMATION and CONFIRM_NOTIFICATIONS - requests.An array of notification identifiers. A notification ID is sent to your application in an - IN_APP_NOTIFY broadcast intent every time a purchase changes state. You use the - notification to retrieve the details of the purchase state change.
    DEVELOPER_PAYLOADStringAny valid String less than 256 characters long.NoA developer-specified string that can be specified when you make a - REQUEST_PURCHASE request. This field is returned in the JSON string that contains - transaction information for an order. You can use this key to send supplemental information with - an order. For example, you can use this key to send index keys with an order, which is useful if - you are using a database to store purchase information. We recommend that you do not use this key - to send data or content.
    - -

    The BILLING_REQUEST key can have the following values:

    - -
      -
    • CHECK_BILLING_SUPPORTED -

      This request verifies that the Google Play application supports in-app billing. You - usually send this request when your application first starts up. This request is useful if you - want to enable or disable certain UI features that are relevant only to in-app billing.

      -
    • -
    • REQUEST_PURCHASE -

      This request sends a purchase message to the Google Play application and is the foundation - of in-app billing. You send this request when a user indicates that he or she wants to purchase - an item in your application. Google Play then handles the financial transaction by displaying - the checkout user interface.

      -
    • -
    • GET_PURCHASE_INFORMATION -

      This request retrieves the details of a purchase state change. A purchase state change can - occur when a purchase request is billed successfully or when a user cancels a transaction during - checkout. It can also occur when a previous purchase is refunded. Google Play notifies your - application when a purchase changes state, so you only need to send this request when there is - transaction information to retrieve.

      -
    • -
    • CONFIRM_NOTIFICATIONS -

      This request acknowledges that your application received the details of a purchase state - change. That is, this message confirms that you sent a GET_PURCHASE_INFORMATION - request for a given notification and that you received the purchase information for the - notification.

      -
    • -
    • RESTORE_TRANSACTIONS -

      This request retrieves a user's transaction status for managed purchases (see Choosing a - Purchase Type for more information). You should send this message only when you need to - retrieve a user's transaction status, which is usually only when your application is reinstalled - or installed for the first time on a device.

      -
    • -
    - -

    Every in-app billing request generates a synchronous response. The response is a {@link -android.os.Bundle} and can include one or more of the following keys:

    - -
      -
    • RESPONSE_CODE -

      This key provides status information and error information about a request.

      -
    • -
    • PURCHASE_INTENT -

      This key provides a {@link android.app.PendingIntent}, which you use to launch the checkout - activity.

      -
    • -
    • REQUEST_ID -

      This key provides you with a request identifier, which you can use to match asynchronous - responses with requests.

      -
    • -
    - -

    Some of these keys are not relevant to certain types of requests. Table 3 shows which keys are -returned for each request type.

    - -

    Table 3. Description of Bundle keys that are returned with -each in-app billing request type.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Request TypeKeys ReturnedPossible Response Codes
    CHECK_BILLING_SUPPORTEDRESPONSE_CODERESULT_OK, RESULT_BILLING_UNAVAILABLE, RESULT_ERROR, - RESULT_DEVELOPER_ERROR
    REQUEST_PURCHASERESPONSE_CODE, PURCHASE_INTENT, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
    GET_PURCHASE_INFORMATIONRESPONSE_CODE, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
    CONFIRM_NOTIFICATIONSRESPONSE_CODE, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
    RESTORE_TRANSACTIONSRESPONSE_CODE, REQUEST_IDRESULT_OK, RESULT_ERROR, RESULT_DEVELOPER_ERROR
    - -

    In-app Billing Broadcast Intents

    - -

    The following section describes the in-app billing broadcast intents that are sent by the Google -Play application. These broadcast intents inform your application about in-app billing actions -that have occurred. Your application must implement a {@link android.content.BroadcastReceiver} to -receive these broadcast intents, such as the BillingReceiver that's shown in the in-app -billing sample -application.

    - -

    com.android.vending.billing.RESPONSE_CODE

    - -

    This broadcast intent contains a Google Play response code, and is sent after you make an -in-app billing request. A server response code can indicate that a billing request was successfully -sent to Google Play or it can indicate that some error occurred during a billing request. This -intent is not used to report any purchase state changes (such as refund or purchase information). -For more information about the response codes that are sent with this response, see Google Play Response Codes for In-app Billing. The sample application -assigns this broadcast intent to a constant named ACTION_RESPONSE_CODE.

    - -
    Extras
    - -
      -
    • request_id—a long representing a request ID. A request ID - identifies a specific billing request and is returned by Google Play at the time a request is - made.
    • -
    • response_code—an int representing the Google Play server - response code.
    • -
    - -

    com.android.vending.billing.IN_APP_NOTIFY

    - -

    This response indicates that a purchase has changed state, which means a purchase succeeded, was -canceled, or was refunded. This response contains one or more notification IDs. Each notification ID -corresponds to a specific server-side message, and each messages contains information about one or -more transactions. After your application receives an IN_APP_NOTIFY broadcast intent, -you send a GET_PURCHASE_INFORMATION request with the notification IDs to retrieve the -message details. The sample application assigns this broadcast intent to a constant named -ACTION_NOTIFY.

    - -
    Extras
    - -
      -
    • notification_id—a String representing the notification ID for - a given purchase state change. Google Play notifies you when there is a purchase state change - and the notification includes a unique notification ID. To get the details of the purchase state - change, you send the notification ID with the GET_PURCHASE_INFORMATION request.
    • -
    - -

    com.android.vending.billing.PURCHASE_STATE_CHANGED

    - -

    This broadcast intent contains detailed information about one or more transactions. The -transaction information is contained in a JSON string. The JSON string is signed and the signature -is sent to your application along with the JSON string (unencrypted). To help ensure the security of -your in-app billing messages, your application can verify the signature of this JSON string. The -sample application assigns this broadcast intent to a constant named -ACTION_PURCHASE_STATE_CHANGED.

    - -
    Extras
    - -
      -
    • inapp_signed_data—a String representing the signed JSON - string.
    • -
    • inapp_signature—a String representing the signature.
    • -
    - -

    Note: Your application should map the broadcast intents and extras -to constants that are unique to your application. See the Consts.java file in the -sample application to see how this is done.

    - -

    The fields in the JSON string are described in the following table (see table 4):

    - -

    Table 4. Description of JSON fields that are returned with -a PURCHASE_STATE_CHANGED intent.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    FieldDescription
    nonceA number used once. Your application generates the nonce and sends it with the - GET_PURCHASE_INFORMATION request. Google Play sends the nonce back as part of the - JSON string so you can verify the integrity of the message.
    notificationIdA unique identifier that is sent with an IN_APP_NOTIFY broadcast intent. Each - notificationId corresponds to a specify message that is waiting to be retrieved on - the Google Play server. Your application sends back the notificationId with the - GET_PURCHASE_INFORMATION message so Google Play can determine which messages you - are retrieving.
    orderIdA unique order identifier for the transaction. This corresponds to the Google Checkout Order - ID.
    packageNameThe application package from which the purchase originated.
    productIdThe item's product identifier. Every item has a product ID, which you must specify in the - application's product list on the Google Play publisher site.
    purchaseTimeThe time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).
    purchaseStateThe purchase state of the order. Possible values are 0 (purchased), 1 (canceled), or 2 - (refunded).
    developerPayloadA developer-specified string that contains supplemental information about an order. You can - specify a value for this field when you make a REQUEST_PURCHASE request.
    diff --git a/docs/html/guide/market/billing/billing_testing.jd b/docs/html/guide/market/billing/billing_testing.jd deleted file mode 100755 index 77aa3edc51f7..000000000000 --- a/docs/html/guide/market/billing/billing_testing.jd +++ /dev/null @@ -1,293 +0,0 @@ -page.title=Testing In-app Billing -parent.title=In-app Billing -parent.link=index.html -@jd:body - - - -

    The Google Play publisher site provides several tools that help you test your in-app billing -implementation before it is published. You can use these tools to create test accounts and purchase -special reserved items that send static billing responses to your application.

    - -

    To test in-app billing in an application you must install the application on an Android-powered -device. You cannot use the Android emulator to test in-app billing. The device you use for testing -must run a standard version of the Android 1.6 or later platform (API level 4 or higher), and have -the most current version of the Google Play application installed. If a device is not running the -most current Google Play application, your application won't be able to send in-app billing -requests to Google Play. For general information about how to set up a device for use in -developing Android applications, see Using Hardware -Devices.

    - -

    The following section shows you how to set up and use the in-app billing test tools.

    - -

    Testing in-app purchases with static responses

    - -

    We recommend that you first test your in-app billing implementation using static responses from -Google Play. This enables you to verify that your application is handling the primary Google -Play responses correctly and that your application is able to verify signatures correctly.

    - -

    To test your implementation with static responses, you make an in-app billing request using a -special item that has a reserved product ID. Each reserved product ID returns a specific static -response from Google Play. No money is transferred when you make in-app billing requests with the -reserved product IDs. Also, you cannot specify the form of payment when you make a billing request -with a reserved product ID. Figure 1 shows the checkout flow for the reserved item that has the -product ID android.test.purchased.

    - - -

    - Figure 1. Checkout flow for the special reserved item android.test.purchased. -

    - -

    You do not need to list the reserved products in your application's product list. Google Play -already knows about the reserved product IDs. Also, you do not need to upload your application to -the publisher site to perform static response tests with the reserved product IDs. You can simply -install your application on a device, log into the device, and make billing requests using the -reserved product IDs.

    - -

    There are four reserved product IDs for testing static in-app billing responses:

    - -
      -
    • android.test.purchased -

      When you make an in-app billing request with this product ID, Google Play responds as - though you successfully purchased an item. The response includes a JSON string, which contains - fake purchase information (for example, a fake order ID). In some cases, the JSON string is - signed and the response includes the signature so you can test your signature verification - implementation using these responses.

      -
    • -
    • android.test.canceled -

      When you make an in-app billing request with this product ID Google Play responds as - though the purchase was canceled. This can occur when an error is encountered in the order - process, such as an invalid credit card, or when you cancel a user's order before it is - charged.

      -
    • -
    • android.test.refunded -

      When you make an in-app billing request with this product ID, Google Play responds as - though the purchase was refunded. Refunds cannot be initiated through Google Play's in-app - billing service. Refunds must be initiated by you (the merchant). After you process a refund - request through your Google Checkout account, a refund message is sent to your application by - Google Play. This occurs only when Google Play gets notification from Google Checkout that - a refund has been made. For more information about refunds, see Handling - IN_APP_NOTIFY messages and In-app Billing - Pricing.

      -
    • -
    • android.test.item_unavailable -

      When you make an in-app billing request with this product ID, Google Play responds as - though the item being purchased was not listed in your application's product list.

      -
    • -
    - -

    In some cases, the reserved items may return signed static responses, which lets you test -signature verification in your application. To test signature verification with the special reserved -product IDs, you may need to set up test accounts or -upload your application as a unpublished draft application. Table 1 shows you the conditions under -which static responses are signed.

    - -

    Table 1. -Conditions under which static responses are signed.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Application ever been published?Draft application uploaded and unpublished?User who is running the applicationStatic response signature
    NoNoAnyUnsigned
    NoNoDeveloperSigned
    YesNoAnyUnsigned
    YesNoDeveloperSigned
    YesNoTest accountSigned
    YesYesAnySigned
    - -

    To make an in-app billing request with a reserved product ID, you simply construct a normal -REQUEST_PURCHASE request, but instead of using a real product ID from your -application's product list you use one of the reserved product IDs.

    - -

    To test your application using the reserved product IDs, follow these steps:

    - -
      -
    1. Install your application on an Android-powered device. -

      You cannot use the emulator to test in-app billing; you must install your application on a - device to test in-app billing.

      -

      To learn how to install an application on a device, see Running on a - device.

      -
    2. -
    3. Sign in to your device with your developer account. -

      You do not need to use a test account if you are testing only with the reserved product - IDs.

      -
    4. -
    5. Verify that your device is running a supported version of the Google Play - application or the MyApps application. -

      If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of - the MyApps application. If your device is running any other version of Android, in-app billing - requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the - version of the Google Play application, see Updating Google - Play.

      -
    6. -
    7. Run your application and purchase the reserved product IDs.
    8. -
    - -

    Note: Making in-app billing requests with the reserved product IDs -overrides the usual Google Play production system. When you send an in-app billing request for a -reserved product ID, the quality of service will not be comparable to the production -environment.

    - -

    Testing In-app Purchases Using Your Own Product IDs

    - -

    After you finish your static response testing, and you verify that signature verification is -working in your application, you can test your in-app billing implementation by making actual in-app -purchases. Testing real in-app purchases enables you to test the end-to-end in-app billing -experience, including the actual responses from Google Play and the actual checkout flow that -users will experience in your application.

    - -

    Note: You do not need to publish your application to do end-to-end -testing. You only need to upload your application as a draft application to perform end-to-end -testing.

    - -

    To test your in-app billing implementation with actual in-app purchases, you will need to -register at least one test account on the Google Play publisher site. You cannot use your -developer account to test the complete in-app purchase process because Google Checkout does not let -you buy items from yourself. If you have not set up test accounts before, see Setting up test -accounts.

    - -

    Also, a test account can purchase an item in your product list only if the item is published. The -application does not need to be published, but the item does need to be published.

    - -

    When you use a test account to purchase items, the test account is billed through Google Checkout -and your Google Checkout Merchant account receives a payout for the purchase. Therefore, you may -want to refund purchases that are made with test accounts, otherwise the purchases will show up as -actual payouts to your merchant account.

    - -

    To test your in-app billing implementation with actual purchases, follow these steps:

    - -
      -
    1. Upload your application as a draft application to the publisher site. -

      You do not need to publish your application to perform end-to-end testing with real product - IDs; you only need to upload your application as a draft application. However, you must sign - your application with your release key before you upload it as a draft application. Also, the - version number of the uploaded application must match the version number of the application you - load to your device for testing. To learn how to upload an application to Google Play, see - Uploading - applications.

      -
    2. -
    3. Add items to the application's product list. -

      Make sure that you publish the items (the application can remain unpublished). See Creating a product - list to learn how to do this.

      -
    4. -
    5. Install your application on an Android-powered device. -

      You cannot use the emulator to test in-app billing; you must install your application on a - device to test in-app billing.

      -

      To learn how to install an application on a device, see Running on a - device.

      -
    6. -
    7. Make one of your test accounts the primary account on your device. -

      To perform end-to-end testing of in-app billing, the primary account on your device must be - one of the test accounts - that you registered on the Google Play site. If the primary account on your device is not a - test account, you must do a factory reset of the device and then sign in with one of your test - accounts. To perform a factory reset, do the following:

      -
        -
      1. Open Settings on your device.
      2. -
      3. Touch Privacy.
      4. -
      5. Touch Factory data reset.
      6. -
      7. Touch Reset phone.
      8. -
      9. After the phone resets, be sure to sign in with one of your test accounts during the - device setup process.
      10. -
      -
    8. -
    9. Verify that your device is running a supported version of the Google Play - application or the MyApps application. -

      If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of - the MyApps application. If your device is running any other version of Android, in-app billing - requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the - version of the Google Play application, see Updating Google - Play.

      -
    10. -
    11. Make in-app purchases in your application.
    12. -
    - -

    Note: The only way to change the primary account on a device is to -do a factory reset, making sure you log on with your primary account first.

    - -

    When you are finished testing your in-app billing implementation, you are ready to -publish your application on Google Play. You can follow the normal steps for preparing, signing, and publishing your application. -

    - diff --git a/docs/html/guide/market/billing/index.jd b/docs/html/guide/market/billing/index.jd deleted file mode 100755 index 036761f4e099..000000000000 --- a/docs/html/guide/market/billing/index.jd +++ /dev/null @@ -1,94 +0,0 @@ -page.title=In-app Billing -@jd:body - - - -

    Google Play In-app Billing is a Google Play service that lets you sell digital content in -your applications. You can use the service to sell a wide range of content, including downloadable -content such as media files or photos, and virtual content such as game levels or potions.

    - -

    When you use Google Play's in-app billing service to sell an item, Google Play handles all -checkout details so your application never has to directly process any financial transactions. -Google Play uses the same checkout service that is used for application purchases, so your users -experience a consistent and familiar purchase flow (see figure 1). Also, the transaction fee for -in-app purchases is the same as the transaction fee for application purchases (30%).

    - -

    Any application that you publish through Google Play can implement in-app billing. No special -account or registration is required other than a Google Play app publisher account and a Google -Checkout Merchant account. Also, because the service uses no dedicated framework APIs, you can add -in-app billing to any application that uses a minimum API level of 4 or higher.

    - -

    To help you integrate in-app billing into your application, the Android SDK provides a sample -application that demonstrates a simple implementation of in-app billing. The sample application -contains examples of billing-related classes you can use to implement in-app billing in your -application. It also contains examples of the database, user interface, and business logic you might -use to implement in-app billing.

    - -

    Important: Although the sample application is a working example -of how you can implement in-app billing, we strongly recommend that you modify and -obfuscate the sample code before you use it in a production application. For more information, see -Security and Design.

    - - -

    - Figure 1. Applications initiate in-app billing requests through their own UI - (first screen). Google Play responds to the request by providing the checkout user interface - (middle screen). When checkout is complete, the application resumes. -

    - -

    To learn more about Google Play's in-app billing service and start integrating it into your -applications, read the following documents:

    - -
    -
    Overview of In-app - Billing
    -
    Learn how the service works and what a typical in-app billing implementation looks - like.
    -
    Implementing - In-app Billing
    -
    Use this step-by-step guide to start incorporating in-app billing into your - application.
    -
    Security - and Design
    -
    Review these best practices to help ensure that your in-app billing implementation is - secure and well designed.
    -
    Testing In-app - Billing
    -
    Understand how the in-app billing test tools work and learn how to test your in-app billing - implementation.
    -
    Administering - In-app Billing
    -
    Learn how to set up your product list, register test accounts, and handle refunds.
    -
    In-app Billing - Reference
    -
    Get detailed information about Google Play response codes and the in-app billing - interface.
    -
    - diff --git a/docs/html/guide/market/expansion-files.jd b/docs/html/guide/market/expansion-files.jd deleted file mode 100644 index 36b8f9ca043e..000000000000 --- a/docs/html/guide/market/expansion-files.jd +++ /dev/null @@ -1,1270 +0,0 @@ -page.title=APK Expansion Files -@jd:body - - -
    -
    -

    Quickview

    -
      -
    • Recommended for most apps that exceed the 50MB APK limit
    • -
    • You can provide up to 4GB of additional data for each APK
    • -
    • Google Play hosts and serves the expansion files at no charge
    • -
    • The files can be any file type you want and are saved to the device's shared storage
    • -
    - -

    In this document

    -
      -
    1. Overview -
        -
      1. File name format
      2. -
      3. Storage location
      4. -
      5. Download process
      6. -
      7. Development checklist
      8. -
      -
    2. -
    3. Rules and Limitations
    4. -
    5. Downloading the Expansion Files -
        -
      1. About the Downloader Library
      2. -
      3. Preparing to use the Downloader Library
      4. -
      5. Declaring user permissions
      6. -
      7. Implementing the downloader service
      8. -
      9. Implementing the alarm receiver
      10. -
      11. Starting the download
      12. -
      13. Receiving download progress
      14. -
      -
    6. -
    7. Using APKExpansionPolicy
    8. -
    9. Reading the Expansion File -
        -
      1. Getting the file names
      2. -
      3. Using the APK Expansion Zip Library
      4. -
      -
    10. -
    11. Testing Your Expansion Files -
        -
      1. Testing file reads
      2. -
      3. Testing file downloads
      4. -
      -
    12. -
    13. Updating Your Application
    14. -
    - -

    See also

    -
      -
    1. Application Licensing
    2. -
    3. Multiple -APK Support
    4. -
    -
    -
    - - - -

    Google Play currently requires that your APK file be no more than 50MB. For most -applications, this is plenty of space for all the application's code and assets. -However, some apps need more space for high-fidelity graphics, media files, or other large assets. -Previously, if your app exceeded 50MB, you had to host and download the additional resources -yourself when the user opens the app. Hosting and serving the extra files can be costly, and the -user experience is often less than ideal. To make this process easier for you and more pleasant -for users, Google Play allows you to attach two large expansion files that supplement your -APK.

    - -

    Google Play hosts the expansion files for your application and serves them to the device at -no cost to you. The expansion files are saved to the device's shared storage location (the -SD card or USB-mountable partition; also known as the "external" storage) where your app can access -them. On most devices, Google Play downloads the expansion file(s) at the same time it -downloads the APK, so your application has everything it needs when the user opens it for the -first time. In some cases, however, your application must download the files from Google Play -when your application starts.

    - - - -

    Overview

    - -

    Each time you upload an APK using the Google Play Android Developer Console, you have the option to -add one or two expansion files to the APK. Each file can be up to 2GB and it can be any format you -choose, but we recommend you use a compressed file to conserve bandwidth during the download. -Conceptually, each expansion file plays a different role:

    - -
      -
    • The main expansion file is the -primary expansion file for additional resources required by your application.
    • -
    • The patch expansion file is optional and intended for small updates to the -main expansion file.
    • -
    - -

    While you can use the two expansion files any way you wish, we recommend that the main -expansion file deliver the primary assets and should rarely if ever updated; the patch expansion -file should be smaller and serve as a “patch carrier,” getting updated with each major -release or as necessary.

    - -

    However, even if your application update requires only a new patch expansion file, you still must -upload a new APK with an updated {@code -versionCode} in the manifest. (The -Developer Console does not allow you to upload an expansion file to an existing APK.)

    - -

    Note: The patch expansion file is semantically the same as the -main expansion file—you can use each file any way you want. The system does -not use the patch expansion file to perform patching for your app. You must perform patching -yourself or be able to distinguish between the two files.

    - - - -

    File name format

    - -

    Each expansion file you upload can be any format you choose (ZIP, PDF, MP4, etc.). Regardless of -the file type, Google Play considers them opaque binary blobs and renames the files -using the following scheme:

    - -
    -[main|patch].<expansion-version>.<package-name>.obb
    -
    - -

    There are three components to this scheme:

    - -
    -
    {@code main} or {@code patch}
    -
    Specifies whether the file is the main or patch expansion file. There can be -only one main file and one patch file for each APK.
    -
    {@code <expansion-version>}
    -
    This is an integer that matches the version code of the APK with which the expansion is -first associated (it matches the application's {@code android:versionCode} -value). -

    "First" is emphasized because although the Developer Console allows you to -re-use an uploaded expansion file with a new APK, the expansion file's name does not change—it -retains the version applied to it when you first uploaded the file.

    -
    {@code <package-name>}
    -
    Your application's Java-style package name.
    -
    - -

    For example, suppose your APK version is 314159 and your package name is com.example.app. If you -upload a main expansion file, the file is renamed to:

    -
    main.314159.com.example.app.obb
    - - -

    Storage location

    - -

    When Google Play downloads your expansion files to a device, it saves them to the system's -shared storage location. To ensure proper behavior, you must not delete, move, or rename the -expansion files. In the event that your application must perform the download from Google Play -itself, you must save the files to the exact same location.

    - -

    The specific location for your expansion files is:

    - -
    -<shared-storage>/Android/obb/<package-name>/
    -
    - -
      -
    • {@code <shared-storage>} is the path to the shared storage space, available from -{@link android.os.Environment#getExternalStorageDirectory()}.
    • -
    • {@code <package-name>} is your application's Java-style package name, available -from {@link android.content.Context#getPackageName()}.
    • -
    - -

    For each application, there are never more than two expansion files in this directory. -One is the main expansion file and the other is the patch expansion file (if necessary). Previous -versions are overwritten when you update your application with new expansion files.

    - -

    If you must unpack the contents of your expansion files, do not delete the -{@code .obb} expansion files afterwards and do not save the unpacked data -in the same directory. You should save your unpacked files in the directory -specified by {@link android.content.Context#getExternalFilesDir getExternalFilesDir()}. However, -if possible, it's best if you use an expansion file format that allows you to read directly from -the file instead of requiring you to unpack the data. For example, we've provided a library -project called the APK Expansion Zip Library that reads your data directly -from the ZIP file.

    - -

    Note: Unlike APK files, any files saved on the shared storage can -be read by the user and other applications.

    - -

    Tip: If you're packaging media files into a ZIP, you can use media -playback calls on the files with offset and length controls (such as {@link -android.media.MediaPlayer#setDataSource(FileDescriptor,long,long) MediaPlayer.setDataSource()} and -{@link android.media.SoundPool#load(FileDescriptor,long,long,int) SoundPool.load()}) without the -need to unpack your ZIP. In order for this to work, you must not perform additional compression on -the media files when creating the ZIP packages. For example, when using the zip tool, -you should use the -n option to specify the file suffixes that should not be -compressed:
    -zip -n .mp4;.ogg main_expansion media_files

    - - -

    Download process

    - -

    Most of the time, Google Play downloads and saves your expansion files at the same time it -downloads the APK to the device. However, in some cases Google Play -cannot download the expansion files or the user might have deleted previously downloaded expansion -files. To handle these situations, your app must be able to download the files -itself when the main activity starts, using a URL provided by Google Play.

    - -

    The download process from a high level looks like this:

    - -
      -
    1. User selects to install your app from Google Play.
    2. -
    3. If Google Play is able to download the expansion files (which is the case for most -devices), it downloads them along with the APK. -

      If Google Play is unable to download the expansion files, it downloads the -APK only.

      -
    4. -
    5. When the user launches your application, your app must check whether the expansion files are -already saved on the device. -
        -
      1. If yes, your app is ready to go.
      2. -
      3. If no, your app must download the expansion files over HTTP from Google Play. Your app -must send a request to the Google Play client using the Google Play's Application Licensing service, which -responds with the name, file size, and URL for each expansion file. With this information, you then -download the files and save them to the proper storage location.
      4. -
      -
    6. -
    - -

    Caution: It is critical that you include the necessary code to -download the expansion files from Google Play in the event that the files are not already on the -device when your application starts. As discussed in the following section about Downloading the Expansion Files, we've made a library available to you that -greatly simplifies this process and performs the download from a service with a minimal amount of -code from you.

    - - - - -

    Development checklist

    - -

    Here's a summary of the tasks you should perform to use expansion files with your -application:

    - -
      -
    1. First determine whether your application absolutely requires more than 50MB per installation. -Space is precious and you should keep your total application size as small as possible. If your app -uses more than 50MB in order to provide multiple versions of your graphic assets for multiple screen -densities, consider instead publishing multiple APKs in which each APK -contains only the assets required for the screens that it targets.
    2. -
    3. Determine which application resources to separate from your APK and package them in a -file to use as the main expansion file. -

      Normally, you should only use the second patch expansion file when performing updates to -the main expansion file. However, if your resources exceed the 2GB limit for the main -expansion file, you can use the patch file for the rest of your assets.

      -
    4. -
    5. Develop your application such that it uses the resources from your expansion files in the -device's shared storage location. -

      Remember that you must not delete, move, or rename the expansion files.

      -

      If your application doesn't demand a specific format, we suggest you create ZIP files for -your expansion files, then read them using the APK Expansion Zip -Library.

      -
    6. -
    7. Add logic to your application's main activity that checks whether the expansion files -are on the device upon start-up. If the files are not on the device, use Google Play's Application Licensing service to request URLs -for the expansion files, then download and save them. -

      To greatly reduce the amount of code you must write and ensure a good user experience -during the download, we recommend you use the Downloader -Library to implement your download behavior.

      -

      If you build your own download service instead of using the library, be aware that you -must not change the name of the expansion files and must save them to the proper -storage location.

    8. -
    - -

    Once you've finished your application development, follow the guide to Testing -Your Expansion Files.

    - - - - - - -

    Rules and Limitations

    - -

    Adding APK expansion files is a feature available when you upload your application using the -Developer Console. When uploading your application for the first time or updating an -application that uses expansion files, you must be aware of the following rules and limitations:

    - -
      -
    1. Each expansion file can be no more than 2GB.
    2. -
    3. In order to download your expansion files from Google Play, the user must have -acquired your application from Google Play. Google Play will not -provide the URLs for your expansion files if the application was installed by other means.
    4. -
    5. When performing the download from within your application, the URL that Google Play -provides for each file is unique for every download and each one expires shortly after it is given -to your application.
    6. -
    7. If you update your application with a new APK or upload multiple APKs for the same -application, you can select expansion files that you've uploaded for a previous APK. The -expansion file's name does not change—it retains the version received by the APK to -which the file was originally associated.
    8. -
    9. If you use expansion files in combination with multiple APKs in order to -provide different expansion files for different devices, you still must upload separate APKs -for each device in order to provide a unique {@code versionCode} -value and declare different filters for -each APK.
    10. -
    11. You cannot issue an update to your application by changing the expansion files -alone—you must upload a new APK to update your app. If your changes only -concern the assets in your expansion files, you can update your APK simply by changing the {@code versionCode} (and -perhaps also the {@code -versionName}).

    12. -
    13. Do not save other data into your obb/ -directory. If you must unpack some data, save it into the location specified by {@link -android.content.Context#getExternalFilesDir getExternalFilesDir()}.
    14. -
    15. Do not delete or rename the {@code .obb} expansion file (unless you're -performing an update). Doing so will cause Google Play (or your app itself) to repeatedly -download the expansion file.
    16. -
    17. When updating an expansion file manually, you must delete the previous expansion file.
    18. -
    - - - - - - - - - -

    Downloading the Expansion Files

    - -

    In most cases, Google Play downloads and saves your expansion files to the device at the same -time it installs or updates the APK. This way, the expansion files are available when your -application launches for the first time. However, in some cases your app must download the -expansion files itself by requesting them from a URL provided to you in a response -from Google Play's Application Licensing service.

    - -

    The basic logic you need to download your expansion files is the following:

    - -
      -
    1. When your application starts, look for the expansion files on the shared storage location (in the -Android/obb/<package-name>/ directory). -
        -
      1. If the expansion files are there, you're all set and your application can continue.
      2. -
      3. If the expansion files are not there: -
          -
        1. Perform a request using Google Play's Application Licensing to get your -app's expansion file names, sizes, and URLs.
        2. -
        3. Use the URLs provided by Google Play to download the expansion files and save -the expansion files. You must save the files to the shared storage location -(Android/obb/<package-name>/) and use the exact file name provided -by Google Play's response. -

          Note: The URL that Google Play provides for your -expansion files is unique for every download and each one expires shortly after it is given to -your application.

          -
        4. -
        -
      4. -
      -
    2. -
    - - -

    If your application is free (not a paid app), then you probably haven't used the Application Licensing service. It's primarily -designed for you to enforce -licensing policies for your application and ensure that the user has the right to -use your app (he or she rightfully paid for it on Google Play). In order to facilitate the -expansion file functionality, the licensing service has been enhanced to provide a response -to your application that includes the URL of your application's expansion files that are hosted -on Google Play. So, even if your application is free for users, you need to include the -License Verification Library (LVL) to use APK expansion files. Of course, if your application -is free, you don't need to enforce license verification—you simply need the -library to perform the request that returns the URL of your expansion files.

    - -

    Note: Whether your application is free or not, Google Play -returns the expansion file URLs only if the user acquired your application from Google Play.

    - -

    In addition to the LVL, you need a set of code that downloads the expansion files -over an HTTP connection and saves them to the proper location on the device's shared storage. -As you build this procedure into your application, there are several issues you should take into -consideration:

    - -
      -
    • The device might not have enough space for the expansion files, so you should check -before beginning the download and warn the user if there's not enough space.
    • -
    • File downloads should occur in a background service in order to avoid blocking the user -interaction and allow the user to leave your app while the download completes.
    • -
    • A variety of errors might occur during the request and download that you must -gracefully handle.
    • -
    • Network connectivity can change during the download, so you should handle such changes and -if interrupted, resume the download when possible.
    • -
    • While the download occurs in the background, you should provide a notification that -indicates the download progress, notifies the user when it's done, and takes the user back to -your application when selected.
    • -
    - - -

    To simplify this work for you, we've built the Downloader Library, -which requests the expansion file URLs through the licensing service, downloads the expansion files, -performs all of the tasks listed above, and even allows your activity to pause and resume the -download. By adding the Downloader Library and a few code hooks to your application, almost all the -work to download the expansion files is already coded for you. As such, in order to provide the best -user experience with minimal effort on your behalf, we recommend you use the Downloader Library to -download your expansion files. The information in the following sections explain how to integrate -the library into your application.

    - -

    If you'd rather develop your own solution to download the expansion files using the Google -Play URLs, you must follow the Application -Licensing documentation to perform a license request, then retrieve the expansion file names, -sizes, and URLs from the response extras. You should use the {@code -APKExpansionPolicy} class (included in the License Verification Library) as your licensing -policy, which captures the expansion file names, sizes, and URLs from the licensing service..

    - - - -

    About the Downloader Library

    - -

    To use APK expansion files with your application and provide the best user experience with -minimal effort on your behalf, we recommend you use the Downloader Library that's included in the -Google Market Apk Expansion package. This library downloads your expansion files in a -background service, shows a user notification with the download status, handles network -connectivity loss, resumes the download when possible, and more.

    - -

    To implement expansion file downloads using the Downloader Library, all you need to do is:

    - -
      -
    • Extend a special {@link android.app.Service} subclass and {@link -android.content.BroadcastReceiver} subclass that each require just a few -lines of code from you.
    • -
    • Add some logic to your main activity that checks whether the expansion files have -already been downloaded and, if not, invokes the download process and displays a -progress UI.
    • -
    • Implement a callback interface with a few methods in your main activity that -receives updates about the download progress.
    • -
    - -

    The following sections explain how to set up your app using the Downloader Library.

    - - -

    Preparing to use the Downloader Library

    - -

    To use the Downloader Library, you need to -download two packages from the SDK Manager and add the appropriate libraries to your -application.

    - -

    First, open the Android SDK Manager, expand -Extras and download:

    -
      -
    • Google Market Licensing package
    • -
    • Google Market Apk Expansion package
    • -
    - -

    If you're using Eclipse, create a project for each library and add it to your app:

    -
      -
    1. Create a new Library Project for the License Verification Library and Downloader -Library. For each library: -
        -
      1. Begin a new Android project.
      2. -
      3. Select Create project from existing -source and choose the library from the {@code <sdk>/extras/google/} directory -({@code market_licensing/} for the License Verification Library or {@code -market_apk_expansion/downloader_library/} for the Downloader Library).
      4. -
      5. Specify a Project Name such as "Google Play License Library" and "Google Play -Downloader -Library"
      6. -
      7. Click Finish.
      8. -
      -

      Note: The Downloader Library depends on the License -Verification Library. Be sure to add the License -Verification Library to the Downloader Library's project properties (same process as -steps 2 and 3 below).

      -
    2. -
    3. Right-click the Android project in which you want to use APK expansion files and -select Properties.
    4. -
    5. In the Library panel, click Add to select and add each of the -libraries to your application.
    6. -
    - -

    Or, from a command line, update your project to include the libraries:

    -
      -
    1. Change directories to the <sdk>/tools/ directory.
    2. -
    3. Execute android update project with the {@code --library} option to add both the -LVL and the Downloader Library to your project. For example: -
      -android update project --path ~/Android/MyApp \
      ---library ~/android_sdk/extras/google/market_licensing \
      ---library ~/android_sdk/extras/google/market_apk_expansion/downloader_library
      -
      -
    4. -
    - -

    With both the License Verification Library and Downloader Library added to your -application, you'll be able to quickly integrate the ability to download expansion files from -Google Play. The format that you choose for the expansion files and how you read them -from the shared storage is a separate implementation that you should consider based on your -application needs.

    - -

    Tip: The Apk Expansion package includes a sample -application -that shows how to use the Downloader Library in an app. The sample uses a third library -available in the Apk Expansion package called the APK Expansion Zip Library. If -you plan on -using ZIP files for your expansion files, we suggest you also add the APK Expansion Zip Library to -your application. For more information, see the section below -about Using the APK Expansion Zip Library.

    - - - -

    Declaring user permissions

    - -

    In order to download the expansion files, the Downloader Library -requires several permissions that you must declare in your application's manifest file. They -are:

    - -
    -<manifest ...>
    -    <!-- Required to access Google Play Licensing -->
    -    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
    -
    -    <!-- Required to download files from Google Play -->
    -    <uses-permission android:name="android.permission.INTERNET" />
    -
    -    <!-- Required to keep CPU alive while downloading files (NOT to keep screen awake) -->
    -    <uses-permission android:name="android.permission.WAKE_LOCK" />
    -
    -    <!-- Required to poll the state of the network connection and respond to changes -->
    -    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    -
    -    <!-- Required to check whether Wi-Fi is enabled -->
    -    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    -
    -    <!-- Required to read and write the expansion files on shared storage -->
    -    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    -    ...
    -</manifest>
    -
    - -

    Note: By default, the Downloader Library requires API -level 4, but the APK Expansion Zip Library requires API level 5.

    - - -

    Implementing the downloader service

    - -

    In order to perform downloads in the background, the Downloader Library provides its -own {@link android.app.Service} subclass called {@code DownloaderService} that you should extend. In -addition to downloading the expansion files for you, the {@code DownloaderService} also:

    - -
      -
    • Registers a {@link android.content.BroadcastReceiver} that listens for changes to the -device's network connectivity (the {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} -broadcast) in order to pause the download when necessary (such as due to connectivity loss) and -resume the download when possible (connectivity is acquired).
    • -
    • Schedules an {@link android.app.AlarmManager#RTC_WAKEUP} alarm to retry the download for -cases in which the service gets killed.
    • -
    • Builds a custom {@link android.app.Notification} that displays the download progress and -any errors or state changes.
    • -
    • Allows your application to manually pause and resume the download.
    • -
    • Verifies that the shared storage is mounted and available, that the files don't already exist, -and that there is enough space, all before downloading the expansion files. Then notifies the user -if any of these are not true.
    • -
    - -

    All you need to do is create a class in your application that extends the {@code -DownloaderService} class and override three methods to provide specific application details:

    - -
    -
    {@code getPublicKey()}
    -
    This must return a string that is the Base64-encoded RSA public key for your publisher -account, available from the profile page on the Developer Console (see Setting Up for Licensing).
    -
    {@code getSALT()}
    -
    This must return an array of random bytes that the licensing {@code Policy} uses to -create an {@code -Obfuscator}. The salt ensures that your obfuscated {@link android.content.SharedPreferences} -file in which your licensing data is saved will be unique and non-discoverable.
    -
    {@code getAlarmReceiverClassName()}
    -
    This must return the class name of the {@link android.content.BroadcastReceiver} in -your application that should receive the alarm indicating that the download should be -restarted (which might happen if the downloader service unexpectedly stops).
    -
    - -

    For example, here's a complete implementation of {@code DownloaderService}:

    - -
    -public class SampleDownloaderService extends DownloaderService {
    -    // You must use the public key belonging to your publisher account
    -    public static final String BASE64_PUBLIC_KEY = "YourLVLKey";
    -    // You should also modify this salt
    -    public static final byte[] SALT = new byte[] { 1, 42, -12, -1, 54, 98,
    -            -100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84
    -    };
    -
    -    @Override
    -    public String getPublicKey() {
    -        return BASE64_PUBLIC_KEY;
    -    }
    -
    -    @Override
    -    public byte[] getSALT() {
    -        return SALT;
    -    }
    -
    -    @Override
    -    public String getAlarmReceiverClassName() {
    -        return SampleAlarmReceiver.class.getName();
    -    }
    -}
    -
    - -

    Notice: You must update the {@code BASE64_PUBLIC_KEY} value -to be the public key belonging to your publisher account. You can find the key in the Developer -Console under your profile information. This is necessary even when testing -your downloads.

    - -

    Remember to declare the service in your manifest file:

    -
    -<application ...>
    -    <service android:name=".SampleDownloaderService" />
    -    ...
    -</application>
    -
    - - - -

    Implementing the alarm receiver

    - -

    In order to monitor the progress of the file downloads and restart the download if necessary, the -{@code DownloaderService} schedules an {@link android.app.AlarmManager#RTC_WAKEUP} alarm that -delivers an {@link android.content.Intent} to a {@link android.content.BroadcastReceiver} in your -application. You must define the {@link android.content.BroadcastReceiver} to call an API -from the Downloader Library that checks the status of the download and restarts -it if necessary.

    - -

    You simply need to override the {@link android.content.BroadcastReceiver#onReceive -onReceive()} method to call {@code -DownloaderClientMarshaller.startDownloadServiceIfRequired()}.

    - -

    For example:

    - -
    -public class SampleAlarmReceiver extends BroadcastReceiver {
    -    @Override
    -    public void onReceive(Context context, Intent intent) {
    -        try {
    -            DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent,
    -                    SampleDownloaderService.class);
    -        } catch (NameNotFoundException e) {
    -            e.printStackTrace();
    -        }      
    -    }
    -}
    -
    - -

    Notice that this is the class for which you must return the name -in your service's {@code getAlarmReceiverClassName()} method (see the previous section).

    - -

    Remember to declare the receiver in your manifest file:

    -
    -<application ...>
    -    <receiver android:name=".SampleAlarmReceiver" />
    -    ...
    -</application>
    -
    - - - -

    Starting the download

    - -

    The main activity in your application (the one started by your launcher icon) is -responsible for verifying whether the expansion files are already on the device and initiating -the download if they are not.

    - -

    Starting the download using the Downloader Library requires the following -procedures:

    - -
      -
    1. Check whether the files have been downloaded. -

      The Downloader Library includes some APIs in the {@code Helper} class to -help with this process:

      -
        -
      • {@code getExtendedAPKFileName(Context, c, boolean mainFile, int -versionCode)}
      • -
      • {@code doesFileExist(Context c, String fileName, long fileSize)}
      • -
      -

      For example, the sample app provided in the Apk Expansion package calls the -following method in the activity's {@link android.app.Activity#onCreate onCreate()} method to check -whether the expansion files already exist on the device:

      -
      -boolean expansionFilesDelivered() {
      -    for (XAPKFile xf : xAPKS) {
      -        String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsBase, xf.mFileVersion);
      -        if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
      -            return false;
      -    }
      -    return true;
      -}        
      -
      -

      In this case, each {@code XAPKFile} object holds the version number and file size of a known -expansion file and a boolean as to whether it's the main expansion file. (See the sample -application's {@code SampleDownloaderActivity} class for details.)

      -

      If this method returns false, then the application must begin the download.

      -
    2. -
    3. Start the download by calling the static method {@code -DownloaderClientMarshaller.startDownloadServiceIfRequired(Context c, PendingIntent -notificationClient, Class<?> serviceClass)}. -

      The method takes the following parameters:

      -
        -
      • context: Your application's {@link android.content.Context}.
      • -
      • notificationClient: A {@link android.app.PendingIntent} to start your main -activity. This is used in the {@link android.app.Notification} that the {@code DownloaderService} -creates to show the download progress. When the user selects the notification, the system -invokes the {@link android.app.PendingIntent} you supply here and should open the activity -that shows the download progress (usually the same activity that started the download).
      • -
      • serviceClass: The {@link java.lang.Class} object for your implementation of -{@code DownloaderService}, required to start the service and begin the download if necessary.
      • -
      -

      The method returns an integer that indicates -whether or not the download is required. Possible values are:

      -
        -
      • {@code NO_DOWNLOAD_REQUIRED}: Returned if the files already -exist or a download is already in progress.
      • -
      • {@code LVL_CHECK_REQUIRED}: Returned if a license verification is -required in order to acquire the expansion file URLs.
      • -
      • {@code DOWNLOAD_REQUIRED}: Returned if the expansion file URLs are already known, -but have not been downloaded.
      • -
      -

      The behavior for {@code LVL_CHECK_REQUIRED} and {@code DOWNLOAD_REQUIRED} are essentially the -same and you normally don't need to be concerned about them. In your main activity that calls {@code -startDownloadServiceIfRequired()}, you can simply check whether or not the response is {@code -NO_DOWNLOAD_REQUIRED}. If the response is anything other than {@code NO_DOWNLOAD_REQUIRED}, -the Downloader Library begins the download and you should update your activity UI to -display the download progress (see the next step). If the response is {@code -NO_DOWNLOAD_REQUIRED}, then the files are available and your application can start.

      -

      For example:

      -
      -@Override
      -public void onCreate(Bundle savedInstanceState) {
      -    // Check if expansion files are available before going any further
      -    if (!expansionFilesDelivered()) {
      -        // Build an Intent to start this activity from the Notification
      -        Intent notifierIntent = new Intent(this, MainActivity.getClass());
      -        notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
      -                                Intent.FLAG_ACTIVITY_CLEAR_TOP);
      -        ...
      -        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
      -                notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
      -        
      -        // Start the download service (if required)
      -        int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
      -                        pendingIntent, SampleDownloaderService.class);
      -        // If download has started, initialize this activity to show download progress
      -        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
      -            // This is where you do set up to display the download progress (next step)
      -            ...
      -            return;
      -        } // If the download wasn't necessary, fall through to start the app
      -    }
      -    startApp(); // Expansion files are available, start the app
      -}
      -
      -
    4. -
    5. When the {@code startDownloadServiceIfRequired()} method returns anything other -than {@code NO_DOWNLOAD_REQUIRED}, create an instance of {@code IStub} by -calling {@code DownloaderClientMarshaller.CreateStub(IDownloaderClient client, Class<?> -downloaderService)}. The {@code IStub} provides a binding between your activity to the downloader -service such that your activity receives callbacks about the download progress. -

      In order to instantiate your {@code IStub} by calling {@code CreateStub()}, you must pass it -an implementation of the {@code IDownloaderClient} interface and your {@code DownloaderService} -implementation. The next section about Receiving download progress discusses -the {@code IDownloaderClient} interface, which you should usually implement in your {@link -android.app.Activity} class so you can update the activity UI when the download state changes.

      -

      We recommend that you call {@code -CreateStub()} to instantiate your {@code IStub} during your activity's {@link -android.app.Activity#onCreate onCreate()} method, after {@code startDownloadServiceIfRequired()} -starts the download.

      -

      For example, in the previous code sample for {@link android.app.Activity#onCreate -onCreate()}, you can respond to the {@code startDownloadServiceIfRequired()} result like this:

      -
      -        // Start the download service (if required)
      -        int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
      -                        pendingIntent, SampleDownloaderService.class);
      -        // If download has started, initialize activity to show progress
      -        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
      -            // Instantiate a member instance of IStub
      -            mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
      -                    SampleDownloaderService.class);
      -            // Inflate layout that shows download progress
      -            setContentView(R.layout.downloader_ui);
      -            return;
      -        }
      -
      - -

      After the {@link android.app.Activity#onCreate onCreate()} method returns, your activity -receives a call to {@link android.app.Activity#onResume onResume()}, which is where you should then -call {@code connect()} on the {@code IStub}, passing it your application's {@link -android.content.Context}. Conversely, you should call -{@code disconnect()} in your activity's {@link android.app.Activity#onStop onStop()} callback.

      -
      -@Override
      -protected void onResume() {
      -    if (null != mDownloaderClientStub) {
      -        mDownloaderClientStub.connect(this);
      -    }
      -    super.onResume();
      -}
      -
      -@Override
      -protected void onStop() {
      -    if (null != mDownloaderClientStub) {
      -        mDownloaderClientStub.disconnect(this);
      -    }
      -    super.onStop();
      -}
      -
      -

      Calling {@code connect()} on the {@code IStub} binds your activity to the {@code -DownloaderService} such that your activity receives callbacks regarding changes to the download -state through the {@code IDownloaderClient} interface.

      -
    6. -
    - - - -

    Receiving download progress

    - -

    To receive updates regarding the download progress and to interact with the {@code -DownloaderService}, you must implement the Downloader Library's {@code IDownloaderClient} interface. -Usually, the activity you use to start the download should implement this interface in order to -display the download progress and send requests to the service.

    - -

    The required interface methods for {@code IDownloaderClient} are:

    - -
    -
    {@code onServiceConnected(Messenger m)}
    -
    After you instantiate the {@code IStub} in your activity, you'll receive a call to this -method, which passes a {@link android.os.Messenger} object that's connected with your instance -of {@code DownloaderService}. To send requests to the service, such as to pause and resume -downloads, you must call {@code DownloaderServiceMarshaller.CreateProxy()} to receive the {@code -IDownloaderService} interface connected to the service. -

    A recommended implementation looks like this:

    -
    -private IDownloaderService mRemoteService;
    -...
    -
    -@Override
    -public void onServiceConnected(Messenger m) {
    -    mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
    -    mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
    -}
    -
    -

    With the {@code IDownloaderService} object initialized, you can send commands to the -downloader service, such as to pause and resume the download ({@code requestPauseDownload()} -and {@code requestContinueDownload()}).

    -
    -
    {@code onDownloadStateChanged(int newState)}
    -
    The download service calls this when a change in download state occurs, such as the -download begins or completes. -

    The newState value will be one of several possible values specified in -by one of the {@code IDownloaderClient} class's {@code STATE_*} constants.

    -

    To provide a useful message to your users, you can request a corresponding string -for each state by calling {@code Helpers.getDownloaderStringResourceIDFromState()}. This -returns the resource ID for one of the strings bundled with the Downloader -Library. For example, the string "Download paused because you are roaming" corresponds to {@code -STATE_PAUSED_ROAMING}.

    -
    {@code onDownloadProgress(DownloadProgressInfo progress)}
    -
    The download service calls this to deliver a {@code DownloadProgressInfo} object, -which describes various information about the download progress, including estimated time remaining, -current speed, overall progress, and total so you can update the download progress UI.
    -
    -

    Tip: For examples of these callbacks that update the download -progress UI, see the {@code SampleDownloaderActivity} in the sample app provided with the -Apk Expansion package.

    - -

    Some public methods for the {@code IDownloaderService} interface you might find useful are:

    - -
    -
    {@code requestPauseDownload()}
    -
    Pauses the download.
    -
    {@code requestContinueDownload()}
    -
    Resumes a paused download.
    -
    {@code setDownloadFlags(int flags)}
    -
    Sets user preferences for network types on which its OK to download the files. The -current implementation supports one flag, {@code FLAGS_DOWNLOAD_OVER_CELLULAR}, but you can add -others. By default, this flag is not enabled, so the user must be on Wi-Fi to download -expansion files. You might want to provide a user preference to enable downloads over -the cellular network. In which case, you can call: -
    -mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
    -
    -
    -
    - - - - -

    Using APKExpansionPolicy

    - -

    If you decide to build your own downloader service instead of using the Google Play -Downloader Library, you should still use the {@code -APKExpansionPolicy} that's provided in the License Verification Library. The {@code -APKExpansionPolicy} class is nearly identical to {@code ServerManagedPolicy} (available in the -Google Play License Verification Library) but includes additional handling for the APK expansion -file response extras.

    - -

    Note: If you do use the Downloader Library as discussed in the previous section, the -library performs all interaction with the {@code APKExpansionPolicy} so you don't have to use -this class directly.

    - -

    The class includes methods to help you get the necessary information about the available -expansion files:

    - -
      -
    • {@code getExpansionURLCount()}
    • -
    • {@code getExpansionURL(int index)}
    • -
    • {@code getExpansionFileName(int index)}
    • -
    • {@code getExpansionFileSize(int index)}
    • -
    - -

    For more information about how to use the {@code APKExpansionPolicy} when you're not -using the Downloader Library, see the documentation for Adding Licensing to Your App, -which explains how to implement a license policy such as this one.

    - - - - - - - -

    Reading the Expansion File

    - -

    Once your APK expansion files are saved on the device, how you read your files -depends on the type of file you've used. As discussed in the overview, your -expansion files can be any kind of file you -want, but are renamed using a particular file name format and are saved to -{@code <shared-storage>/Android/obb/<package-name>/}.

    - -

    Regardless of how you read your files, you should always first check that the external -storage is available for reading. There's a chance that the user has the storage mounted to a -computer over USB or has actually removed the SD card.

    - -

    Note: When your application starts, you should always check whether -the external storage space is available and readable by calling {@link -android.os.Environment#getExternalStorageState()}. This returns one of several possible strings -that represent the state of the external storage. In order for it to be readable by your -application, the return value must be {@link android.os.Environment#MEDIA_MOUNTED}.

    - - -

    Getting the file names

    - -

    As described in the overview, your APK expansion files are saved -using a specific file name format:

    - -
    -[main|patch].<expansion-version>.<package-name>.obb
    -
    - -

    To get the location and names of your expansion files, you should use the -{@link android.os.Environment#getExternalStorageDirectory()} and {@link -android.content.Context#getPackageName()} methods to construct the path to your files.

    - -

    Here's a method you can use in your application to get an array containing the complete path -to both your expansion files:

    - -
    -// The shared path to all app expansion files
    -private final static String EXP_PATH = "/Android/obb/";
    -
    -static String[] getAPKExpansionFiles(Context ctx, int mainVersion, int patchVersion) {
    -    String packageName = ctx.getPackageName();
    -    Vector<String> ret = new Vector<String>();
    -    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    -        // Build the full path to the app's expansion files
    -        File root = Environment.getExternalStorageDirectory();
    -        File expPath = new File(root.toString() + EXP_PATH + packageName);
    -
    -        // Check that expansion file path exists
    -        if (expPath.exists()) {
    -            if ( mainVersion > 0 ) {
    -                String strMainPath = expPath + File.separator + "main." +
    -                        mainVersion + "." + packageName + ".obb";
    -                File main = new File(strMainPath);
    -                if ( main.isFile() ) {
    -                        ret.add(strMainPath);
    -                }
    -            }
    -            if ( patchVersion > 0 ) {
    -                String strPatchPath = expPath + File.separator + "patch." +
    -                        mainVersion + "." + packageName + ".obb";
    -                File main = new File(strPatchPath);
    -                if ( main.isFile() ) {
    -                        ret.add(strPatchPath);
    -                }
    -            }
    -        }
    -    }
    -    String[] retArray = new String[ret.size()];
    -    ret.toArray(retArray);
    -    return retArray;
    -}
    -
    - -

    You can call this method by passing it your application {@link android.content.Context} -and the desired expansion file's version.

    - -

    There are many ways you could determine the expansion file version number. One simple way is to -save the version in a {@link android.content.SharedPreferences} file when the download begins, by -querying the expansion file name with the {@code APKExpansionPolicy} class's {@code -getExpansionFileName(int index)} method. You can then get the version code by reading the {@link -android.content.SharedPreferences} file when you want to access the expansion -file.

    - -

    For more information about reading from the shared storage, see the Data Storage -documentation.

    - - - -

    Using the APK Expansion Zip Library

    - - - -

    The Google Market Apk Expansion package includes a library called the APK -Expansion Zip Library (located in {@code -<sdk>/extras/google/google_market_apk_expansion/zip_file/}). This is an optional library that -helps you read your expansion -files when they're saved as ZIP files. Using this library allows you to easily read resources from -your ZIP expansion files as a virtual file system.

    - -

    The APK Expansion Zip Library includes the following classes and APIs:

    - -
    -
    {@code APKExpansionSupport}
    -
    Provides some methods to access expansion file names and ZIP files: - -
    -
    {@code getAPKExpansionFiles()}
    -
    The same method shown above that returns the complete file path to both expansion -files.
    -
    {@code getAPKExpansionZipFile(Context ctx, int mainVersion, int -patchVersion)}
    -
    Returns a {@code ZipResourceFile} representing the sum of both the main file and -patch file. That is, if you specify both the mainVersion and the -patchVersion, this returns a {@code ZipResourceFile} that provides read access to -all the data, with the patch file's data merged on top of the main file.
    -
    -
    - -
    {@code ZipResourceFile}
    -
    Represents a ZIP file on the shared storage and performs all the work to provide a virtual -file system based on your ZIP files. You can get an instance using {@code -APKExpansionSupport.getAPKExpansionZipFile()} or with the {@code ZipResourceFile} by passing it the -path to your expansion file. This class includes a variety of useful methods, but you generally -don't need to access most of them. A couple of important methods are: - -
    -
    {@code getInputStream(String assetPath)}
    -
    Provides an {@link java.io.InputStream} to read a file within the ZIP file. The -assetPath must be the path to the desired file, relative to -the root of the ZIP file contents.
    -
    {@code getAssetFileDescriptor(String assetPath)}
    -
    Provides an {@link android.content.res.AssetFileDescriptor} for a file within the -ZIP file. The assetPath must be the path to the desired file, relative to -the root of the ZIP file contents. This is useful for certain Android APIs that require an {@link -android.content.res.AssetFileDescriptor}, such as some {@link android.media.MediaPlayer} APIs.
    -
    -
    - -
    {@code APEZProvider}
    -
    Most applications don't need to use this class. This class defines a {@link -android.content.ContentProvider} that marshals the data from the ZIP files through a content -provider {@link android.net.Uri} in order to provide file access for certain Android APIs that -expect {@link android.net.Uri} access to media files. For example, this is useful if you want to -play a video with {@link android.widget.VideoView#setVideoURI VideoView.setVideoURI()}.

    -
    - -

    Reading from a ZIP file

    - -

    When using the APK Expansion Zip Library, reading a file from your ZIP usually requires the -following:

    - -
    -// Get a ZipResourceFile representing a merger of both the main and patch files
    -ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(appContext,
    -        mainVersion, patchVersion);
    -        
    -// Get an input stream for a known file inside the expansion file ZIPs
    -InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
    -
    - -

    The above code provides access to any file that exists in either your main expansion file or -patch expansion file, by reading from a merged map of all the files from both files. All you -need to provide the {@code getAPKExpansionFile()} method is your application {@code -android.content.Context} and the version number for both the main expansion file and patch -expansion file.

    - -

    If you'd rather read from a specific expansion file, you can use the {@code -ZipResourceFile} constructor with the path to the desired expansion file:

    - -
    -// Get a ZipResourceFile representing a specific expansion file
    -ZipResourceFile expansionFile = new ZipResourceFile(filePathToMyZip);
    -
    -// Get an input stream for a known file inside the expansion file ZIPs
    -InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
    -
    - -

    For more information about using this library for your expansion files, look at -the sample application's {@code SampleDownloaderActivity} class, which includes additional code to -verify the downloaded files using CRC. Beware that if you use this sample as the basis for -your own implementation, it requires that you declare the byte size of your expansion -files in the {@code xAPKS} array.

    - - - - -

    Testing Your Expansion Files

    - -

    Before publishing your application, there are two things you should test: Reading the -expansion files and downloading the files.

    - - -

    Testing file reads

    - -

    Before you upload your application to Google Play, you -should test your application's ability to read the files from the shared storage. All you need to do -is add the files to the appropriate location on the device shared storage and launch your -application:

    - -
      -
    1. On your device, create the appropriate directory on the shared storage where Google -Play will save your files. -

      For example, if your package name is {@code com.example.android}, you need to create -the directory {@code Android/obb/com.example.android/} on the shared storage space. (Plug in -your test device to your computer to mount the shared storage and manually create this -directory.)

      -
    2. -
    3. Manually add the expansion files to that directory. Be sure that you rename your files to -match the file name format that Google Play will use. -

      For example, regardless of the file type, the main expansion file for the {@code -com.example.android} application should be {@code main.0300110.com.example.android.obb}. -The version code can be whatever value you want. Just remember:

      -
        -
      • The main expansion file always starts with {@code main} and the patch file starts with -{@code patch}.
      • -
      • The package name always matches that of the APK to which the file is attached on -Google Play. -
      -
    4. -
    5. Now that the expansion file(s) are on the device, you can install and run your application to -test your expansion file(s).
    6. -
    - -

    Here are some reminders about handling the expansion files:

    -
      -
    • Do not delete or rename the {@code .obb} expansion files (even if you unpack -the data to a different location). Doing so will cause Google Play (or your app itself) to -repeatedly download the expansion file.
    • -
    • Do not save other data into your obb/ -directory. If you must unpack some data, save it into the location specified by {@link -android.content.Context#getExternalFilesDir getExternalFilesDir()}.
    • -
    - - - -

    Testing file downloads

    - -

    Because your application must sometimes manually download the expansion files when it first -opens, it's important that you test this process to be sure your application can successfully query -for the URLs, download the files, and save them to the device.

    - -

    To test your application's implementation of the manual download procedure, you must upload -your application to Google Play as a "draft" to make your expansion files available for -download:

    - -
      -
    1. Upload your APK and corresponding expansion files using the Google Play Developer -Console.
    2. -
    3. Fill in the necessary application details (title, screenshots, etc.). You can come back and -finalize these details before publishing your application. -

      Click the Save button. Do not click Publish. This saves -the application as a draft, such that your application is not published for Google Play users, -but the expansion files are available for you to test the download process.

    4. -
    5. Install the application on your test device using the Eclipse tools or {@code adb}.
    6. -
    7. Launch the app.
    8. -
    - -

    If everything works as expected, your application should begin downloading the expansion -files as soon as the main activity starts.

    - - - - -

    Updating Your Application

    - -

    One of the great benefits to using expansion files on Google Play is the ability to -update your application without re-downloading all of the original assets. Because Google Play -allows you to provide two expansion files with each APK, you can use the second file as a "patch" -that provides updates and new assets. Doing so avoids the -need to re-download the main expansion file which could be large and expensive for users.

    - -

    The patch expansion file is technically the same as the main expansion file and neither -the Android system nor Google Play perform actual patching between your main and patch expansion -files. Your application code must perform any necessary patches itself.

    - -

    If you use ZIP files as your expansion files, the APK Expansion Zip -Library that's included with the Apk Expansion package includes the ability to merge -your -patch file with the main expansion file.

    - -

    Note: Even if you only need to make changes to the patch -expansion file, you must still update the APK in order for Google Play to perform an update. -If you don't require code changes in the application, you should simply update the {@code versionCode} in the -manifest.

    - -

    As long as you don't change the main expansion file that's associated with the APK -in the Developer Console, users who previously installed your application will not -download the main expansion file. Existing users receive only the updated APK and the new patch -expansion file (retaining the previous main expansion file).

    - -

    Here are a few issues to keep in mind regarding updates to expansion files:

    - -
      -
    • There can be only two expansion files for your application at a time. One main expansion -file and one patch expansion file. During an update to a file, Google Play deletes the -previous version (and so must your application when performing manual updates).
    • -
    • When adding a patch expansion file, the Android system does not actually patch your -application or main expansion file. You must design your application to support the patch data. -However, the Apk Expansion package includes a library for using ZIP files -as expansion files, which merges the data from the patch file into the main expansion file so -you can easily read all the expansion file data.
    • -
    - - - - diff --git a/docs/html/guide/market/licensing/adding-licensing.jd b/docs/html/guide/market/licensing/adding-licensing.jd deleted file mode 100644 index d4dd008bcf7c..000000000000 --- a/docs/html/guide/market/licensing/adding-licensing.jd +++ /dev/null @@ -1,1072 +0,0 @@ -page.title=Adding Licensing to Your App -parent.title=Application Licensing -parent.link=index.html -@jd:body - - - - - - - -

    After you've set up a publisher account and development environment (see Setting Up for Licensing), you are ready to add license verification to -your app with the License Verification Library (LVL).

    - -

    Adding license verification with the LVL involves these tasks:

    - -
      -
    1. Adding the licensing permission your application's manifest.
    2. -
    3. Implementing a Policy — you can choose one of the full implementations provided in the LVL or create your own.
    4. -
    5. Implementing an Obfuscator, if your {@code Policy} will cache any -license response data.
    6. -
    7. Adding code to check the license in your application's main -Activity.
    8. -
    9. Implementing a DeviceLimiter (optional and not recommended for -most applications).
    10. -
    - -

    The sections below describe these tasks. When you are done with the -integration, you should be able to compile your application successfully and you -can begin testing, as described in Setting Up the Test -Environment.

    - -

    For an overview of the full set of source files included in the LVL, see Summary of LVL Classes -and Interfaces.

    - - -

    Adding the Licensing Permission

    - -

    To use the Google Play application for sending a license check to the -server, your application must request the proper permission, -com.android.vending.CHECK_LICENSE. If your application does -not declare the licensing permission but attempts to initiate a license check, -the LVL throws a security exception.

    - -

    To request the licensing permission in your application, declare a <uses-permission> -element as a child of <manifest>, as follows:

    - -

    <uses-permission -android:name="com.android.vending.CHECK_LICENSE">

    - -

    For example, here's how the LVL sample application declares the permission: -

    - -
    <?xml version="1.0" encoding="utf-8"?>
    -
    -<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...">
    -    <!-- Devices >= 3 have version of Google Play that supports licensing. -->
    -    <uses-sdk android:minSdkVersion="3" />
    -    <!-- Required permission to check licensing. -->
    -    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
    -    ...
    -</manifest>
    -
    - -

    Note: Currently, you cannot declare the -CHECK_LICENSE permission in the LVL library project's manifest, -because the SDK Tools will not merge it into the manifests of dependent -applications. Instead, you must declare the permission in each dependent -application's manifest.

    - - -

    Implementing a Policy

    - - - -

    Google Play licensing service does not itself determine whether a -given user with a given license should be granted access to your application. -Rather, that responsibility is left to a {@code Policy} implementation that you provide -in your application.

    - -

    Policy is an interface declared by the LVL that is designed to hold your -application's logic for allowing or disallowing user access, based on the result -of a license check. To use the LVL, your application must provide an -implementation of {@code Policy}.

    - -

    The {@code Policy} interface declares two methods, allowAccess() and -processServerResponse(), which are called by a {@code LicenseChecker} -instance when processing a response from the license server. It also declares an -enum called LicenseResponse, which specifies the license response -value passed in calls to processServerResponse().

    - -
      -
    • processServerResponse() lets you preprocess the raw response -data received from the licensing server, prior to determining whether to grant -access. - -

      A typical implementation would extract some or all fields from the license -response and store the data locally to a persistent store, such as through -{@link android.content.SharedPreferences} storage, to ensure that the data is -accessible across application invocations and device power cycles. For example, -a {@code Policy} would maintain the timestamp of the last successful license check, the -retry count, the license validity period, and similar information in a -persistent store, rather than resetting the values each time the application is -launched.

      - -

      When storing response data locally, the {@code Policy} must ensure that the data is -obfuscated (see Implementing an Obfuscator, -below).

    • - -
    • allowAccess() determines whether to grant the user access to -your application, based on any available license response data (from the -licensing server or from cache) or other application-specific information. For -example, your implementation of allowAccess() could take into -account additional criteria, such as usage or other data retrieved from a -backend server. In all cases, an implementation of allowAccess() -should only return true if the user is licensed to use the -application, as determined by the licensing server, or if there is a transient -network or system problem that prevents the license check from completing. In -such cases, your implementation can maintain a count of retry responses and -provisionally allow access until the next license check is complete.
    • - -
    - -

    To simplify the process of adding licensing to your application and to -provide an illustration of how a {@code Policy} should be designed, the LVL includes -two full {@code Policy} implementations that you can use without modification or -adapt to your needs:

    - -
      -
    • ServerManagedPolicy, a flexible {@code Policy} -that uses server-provided settings and cached responses to manage access across -varied network conditions, and
    • -
    • StrictPolicy, which does not cache any response -data and allows access only if the server returns a licensed -response.
    • -
    - -

    For most applications, the use of ServerManagedPolicy is highly -recommended. ServerManagedPolicy is the LVL default and is integrated with -the LVL sample application.

    - - -

    Guidelines for custom policies

    - -

    In your licensing implementation, you can use one of the complete policies -provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a -custom policy. For any type of custom policy, there are several important design -points to understand and account for in your implementation.

    - -

    The licensing server applies general request limits to guard against overuse -of resources that could result in denial of service. When an application exceeds -the request limit, the licensing server returns a 503 response, which gets -passed through to your application as a general server error. This means that no -license response will be available to the user until the limit is reset, which -can affect the user for an indefinite period.

    - -

    If you are designing a custom policy, we recommend that the {@code Policy}: -

      - -
    1. Caches (and properly obfuscates) the most recent successful license response -in local persistent storage.
    2. -
    3. Returns the cached response for all license checks, for as long as the -cached response is valid, rather than making a request to the licensing server. -Setting the response validity according to the server-provided VT -extra is highly recommended. See Server Response Extras -for more information.
    4. -
    5. Uses an exponential backoff period, if retrying any requests the result in -errors. Note that the Google Play client automatically retries failed -requests, so in most cases there is no need for your {@code Policy} to retry them.
    6. -
    7. Provides for a "grace period" that allows the user to access your -application for a limited time or number of uses, while a license check is being -retried. The grace period benefits the user by allowing access until the next -license check can be completed successfully and it benefits you by placing a -hard limit on access to your application when there is no valid license response -available.
    8. -
    - -

    Designing your {@code Policy} according to the guidelines listed above is critical, -because it ensures the best possible experience for users while giving you -effective control over your application even in error conditions.

    - -

    Note that any {@code Policy} can use settings provided by the licensing server to -help manage validity and caching, retry grace period, and more. Extracting the -server-provided settings is straightforward and making use of them is highly -recommended. See the ServerManagedPolicy implementation for an example of how to -extract and use the extras. For a list of server settings and information about -how to use them, see Server Response -Extras.

    - -

    ServerManagedPolicy

    - - - -

    The LVL includes a full and recommended implementation of the {@code Policy} -interface called ServerManagedPolicy. The implementation is integrated with the -LVL classes and serves as the default {@code Policy} in the library.

    - -

    ServerManagedPolicy provides all of the handling for license and retry -responses. It caches all of the response data locally in a -{@link android.content.SharedPreferences} file, obfuscating it with the -application's {@code Obfuscator} implementation. This ensures that the license response -data is secure and persists across device power cycles. ServerManagedPolicy -provides concrete implementations of the interface methods -processServerResponse() and allowAccess() and also -includes a set of supporting methods and types for managing license -responses.

    - -

    Importantly, a key feature of ServerMangedPolicy is its use of -server-provided settings as the basis for managing licensing across an -application's refund period and through varying network and error conditions. -When an application contacts the Google Play server for a license check, the -server appends several settings as key-value pairs in the extras field of certain -license response types. For example, the server provides recommended values for the -application's license validity period, retry grace period, and maximum allowable -retry count, among others. ServerManagedPolicy extracts the values from the -license response in its processServerResponse() method and checks -them in its allowAccess() method. For a list of the server-provided -settings used by ServerManagedPolicy, see Server Response -Extras.

    - -

    For convenience, best performance, and the benefit of using license settings -from the Google Play server, using ServerManagedPolicy as your -licensing {@code Policy} is strongly recommended.

    - -

    If you are concerned about the security of license response data that is -stored locally in {@link android.content.SharedPreferences}, you can use a stronger obfuscation -algorithm or design a stricter {@code Policy} that does not store license data. The LVL -includes an example of such a {@code Policy} — see StrictPolicy for more information.

    - -

    To use ServerManagedPolicy, simply import it to your Activity, create an -instance, and pass a reference to the instance when constructing your -{@code LicenseChecker}. See Instantiate LicenseChecker and -LicenseCheckerCallback for more information.

    - -

    StrictPolicy

    - -

    The LVL includes an alternative full implementation of the {@code Policy} interface -called StrictPolicy. The StrictPolicy implementation provides a more restrictive -Policy than ServerManagedPolicy, in that it does not allow the user to access -the application unless a license response is received from the server at the -time of access that indicates that the user is licensed.

    - -

    The principal feature of StrictPolicy is that it does not store any -license response data locally, in a persistent store. Because no data is stored, -retry requests are not tracked and cached responses can not be used to fulfill -license checks. The {@code Policy} allows access only if:

    - -
      -
    • The license response is received from the licensing server, and
    • -
    • The license response indicates that the user is licensed to access the -application.
    • -
    - -

    Using StrictPolicy is appropriate if your primary concern is to ensure that, -in all possible cases, no user will be allowed to access the application unless -the user is confirmed to be licensed at the time of use. Additionally, the -Policy offers slightly more security than ServerManagedPolicy — since -there is no data cached locally, there is no way a malicious user could tamper -with the cached data and obtain access to the application.

    - -

    At the same time, this {@code Policy} presents a challenge for normal users, since it -means that they won't be able to access the application when there is no network -(cell or Wi-Fi) connection available. Another side-effect is that your -application will send more license check requests to the server, since using a -cached response is not possible.

    - -

    Overall, this policy represents a tradeoff of some degree of user convenience -for absolute security and control over access. Consider the tradeoff carefully -before using this {@code Policy}.

    - -

    To use StrictPolicy, simply import it to your Activity, create an instance, -and pass a reference to it when constructing your {@code LicenseChecker}. See -Instantiate LicenseChecker and LicenseCheckerCallback -for more information.

    - -

    Implementing an Obfuscator

    - - - -

    A typical {@code Policy} implementation needs to save the license response data for -an application to a persistent store, so that it is accessible across -application invocations and device power cycles. For example, a {@code Policy} would -maintain the timestamp of the last successful license check, the retry count, -the license validity period, and similar information in a persistent store, -rather than resetting the values each time the application is launched. The -default {@code Policy} included in the LVL, ServerManagedPolicy, stores license response -data in a {@link android.content.SharedPreferences} instance, to ensure that the -data is persistent.

    - -

    Because the {@code Policy} will use stored license response data to determine whether -to allow or disallow access to the application, it must ensure that any -stored data is secure and cannot be reused or manipulated by a root user on a -device. Specifically, the {@code Policy} must always obfuscate the data before storing -it, using a key that is unique for the application and device. Obfuscating using -a key that is both application-specific and device-specific is critical, because -it prevents the obfuscated data from being shared among applications and -devices.

    - -

    The LVL assists the application with storing its license response data in a -secure, persistent manner. First, it provides an {@code Obfuscator} -interface that lets your application supply the obfuscation algorithm of its -choice for stored data. Building on that, the LVL provides the helper class -PreferenceObfuscator, which handles most of the work of calling the -application's {@code Obfuscator} class and reading and writing the obfuscated data in a -{@link android.content.SharedPreferences} instance.

    - -

    The LVL provides a full {@code Obfuscator} implementation called -AESObfuscator that uses AES encryption to obfuscate data. You can -use AESObfuscator in your application without modification or you -can adapt it to your needs. For more information, see the next section.

    - - -

    AESObfuscator

    - -

    The LVL includes a full and recommended implementation of the {@code Obfuscator} -interface called AESObfuscator. The implementation is integrated with the -LVL sample application and serves as the default {@code Obfuscator} in the library.

    - -

    AESObfuscator provides secure obfuscation of data by using AES to -encrypt and decrypt the data as it is written to or read from storage. -The {@code Obfuscator} seeds the encryption using three data fields provided -by the application:

    - -
      -
    1. A salt — an array of random bytes to use for each (un)obfuscation.
    2. -
    3. An application identifier string, typically the package name of the application.
    4. -
    5. A device identifier string, derived from as many device-specific sources -as possible, so as to make it as unique.
    6. -
    - -

    To use AESObfuscator, first import it to your Activity. Declare a private -static final array to hold the salt bytes and initialize it to 20 randomly -generated bytes.

    - -
        ...
    -    // Generate 20 random bytes, and put them here.
    -    private static final byte[] SALT = new byte[] {
    -     -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
    -     -45, 77, -117, -36, -113, -11, 32, -64, 89
    -     };
    -    ...
    -
    - -

    Next, declare a variable to hold a device identifier and generate a value for -it in any way needed. For example, the sample application included in the LVL -queries the system settings for the -android.Settings.Secure.ANDROID_ID, which is unique to each device. -

    - -

    Note that, depending on the APIs you use, your application might need to -request additional permissions in order to acquire device-specific information. -For example, to query the {@link android.telephony.TelephonyManager} to obtain -the device IMEI or related data, the application will also need to request the -android.permission.READ_PHONE_STATE permission in its manifest.

    - -

    Before requesting new permissions for the sole purpose of acquiring -device-specific information for use in your {@code Obfuscator}, consider -how doing so might affect your application or its filtering on Google Play -(since some permissions can cause the SDK build tools to add -the associated <uses-feature>).

    - -

    Finally, construct an instance of AESObfuscator, passing the salt, -application identifier, and device identifier. You can construct the instance -directly, while constructing your {@code Policy} and {@code LicenseChecker}. For example:

    - -
        ...
    -    // Construct the LicenseChecker with a Policy.
    -    mChecker = new LicenseChecker(
    -        this, new ServerManagedPolicy(this,
    -            new AESObfuscator(SALT, getPackageName(), deviceId)),
    -        BASE64_PUBLIC_KEY  // Your public licensing key.
    -        );
    -    ...
    -
    - -

    For a complete example, see MainActivity in the LVL sample application.

    - - -

    Checking the License from an Activity

    - -

    Once you've implemented a {@code Policy} for managing access to your application, the -next step is to add a license check to your application, which initiates a query -to the licensing server if needed and manages access to the application based on -the license response. All of the work of adding the license check and handling -the response takes place in your main {@link android.app.Activity} source file. -

    - -

    To add the license check and handle the response, you must:

    - -
      -
    1. Add imports
    2. -
    3. Implement LicenseCheckerCallback as a private inner class
    4. -
    5. Create a Handler for posting from LicenseCheckerCallback to the UI thread
    6. -
    7. Instantiate LicenseChecker and LicenseCheckerCallback
    8. -
    9. Call checkAccess() to initiate the license check
    10. -
    11. Embed your public key for licensing
    12. -
    13. Call your LicenseChecker's onDestroy() method to close IPC connections.
    14. -
    - -

    The sections below describe these tasks.

    - -

    Overview of license check and response

    - - - -

    In most cases, you should add the license check to your application's main -{@link android.app.Activity}, in the {@link android.app.Activity#onCreate onCreate()} method. This -ensures that when the user launches your application directly, the license check -will be invoked immediately. In some cases, you can add license checks in other -locations as well. For example, if your application includes multiple Activity -components that other applications can start by {@link android.content.Intent}, -you could add license checks in those Activities.

    - -

    A license check consists of two main actions:

    - -
      -
    • A call to a method to initiate the license check — in the LVL, this is -a call to the checkAccess() method of a {@code LicenseChecker} object that -you construct.
    • -
    • A callback that returns the result of the license check. In the LVL, this is -a LicenseCheckerCallback interface that you implement. The -interface declares two methods, allow() and -dontAllow(), which are invoked by the library based on to the -result of the license check. You implement these two methods with whatever logic -you need, to allow or disallow the user access to your application. Note that -these methods do not determine whether to allow access — that -determination is the responsibility of your {@code Policy} implementation. Rather, these -methods simply provide the application behaviors for how to allow and -disallow access (and handle application errors). -

      The allow() and dontAllow() methods do provide a "reason" -for their response, which can be one of the {@code Policy} values, {@code LICENSED}, -{@code NOT_LICENSED}, or {@code RETRY}. In particular, you should handle the case in which -the method receives the {@code RETRY} response for {@code dontAllow()} and provide the user with an -"Retry" button, which might have happened because the service was unavailable during the -request.

    • -
    - -
    - - -
    Figure 6. Overview of a -typical license check interaction.
    -
    - -

    The diagram above illustrates how a typical license check takes place:

    - -
      -
    1. Code in the application's main Activity instantiates {@code LicenseCheckerCallback} -and {@code LicenseChecker} objects. When constructing {@code LicenseChecker}, the code passes in -{@link android.content.Context}, a {@code Policy} implementation to use, and the -publisher account's public key for licensing as parameters.
    2. -
    3. The code then calls the checkAccess() method on the -{@code LicenseChecker} object. The method implementation calls the {@code Policy} to determine -whether there is a valid license response cached locally, in -{@link android.content.SharedPreferences}. -
        -
      • If so, the checkAccess() implementation calls - allow().
      • -
      • Otherwise, the {@code LicenseChecker} initiates a license check request that is sent - to the licensing server.
      • -
      - -

      Note: The licensing server always returns -LICENSED when you perform a license check of a draft application.

      -
    4. -
    5. When a response is received, {@code LicenseChecker} creates a LicenseValidator that -verifies the signed license data and extracts the fields of the response, then -passes them to your {@code Policy} for further evaluation. -
        -
      • If the license is valid, the {@code Policy} caches the response in -{@link android.content.SharedPreferences} and notifies the validator, which then calls the -allow() method on the {@code LicenseCheckerCallback} object.
      • -
      • If the license not valid, the {@code Policy} notifies the validator, which calls -the dontAllow() method on {@code LicenseCheckerCallback}.
      • -
      -
    6. -
    7. In case of a recoverable local or server error, such as when the network is -not available to send the request, {@code LicenseChecker} passes a {@code RETRY} response to -your {@code Policy} object's processServerResponse() method. -

      Also, both the {@code allow()} and {@code dontAllow()} callback methods receive a -reason argument. The {@code allow()} method's reason is usually {@code -Policy.LICENSED} or {@code Policy.RETRY} and the {@code dontAllow()} reason is usually {@code -Policy.NOT_LICENSED} or {@code Policy.RETRY}. These response values are useful so you can show -an appropriate response for the user, such as by providing a "Retry" button when {@code -dontAllow()} responds with {@code Policy.RETRY}, which might have been because the service was -unavailable.

    8. -
    9. In case of a application error, such as when the application attempts to -check the license of an invalid package name, {@code LicenseChecker} passes an error -response to the LicenseCheckerCallback's applicationError() -method.
    10. -
    - -

    Note that, in addition to initiating the license check and handling the -result, which are described in the sections below, your application also needs -to provide a Policy implementation and, if the {@code Policy} -stores response data (such as ServerManagedPolicy), an Obfuscator implementation.

    - - -

    Add imports

    - -

    First, open the class file of the application's main Activity and import -{@code LicenseChecker} and {@code LicenseCheckerCallback} from the LVL package.

    - -
        import com.android.vending.licensing.LicenseChecker;
    -    import com.android.vending.licensing.LicenseCheckerCallback;
    - -

    If you are using the default {@code Policy} implementation provided with the LVL, -ServerManagedPolicy, import it also, together with the AESObfuscator. If you are -using a custom {@code Policy} or {@code Obfuscator}, import those instead.

    - -
        import com.android.vending.licensing.ServerManagedPolicy;
    -    import com.android.vending.licensing.AESObfuscator;
    - -

    Implement LicenseCheckerCallback as a private inner class

    - -

    {@code LicenseCheckerCallback} is an interface provided by the LVL for handling -result of a license check. To support licensing using the LVL, you must -implement {@code LicenseCheckerCallback} and -its methods to allow or disallow access to the application.

    - -

    The result of a license check is always a call to one of the -{@code LicenseCheckerCallback} methods, made based on the validation of the response -payload, the server response code itself, and any additional processing provided -by your {@code Policy}. Your application can implement the methods in any way needed. In -general, it's best to keep the methods simple, limiting them to managing UI -state and application access. If you want to add further processing of license -responses, such as by contacting a backend server or applying custom constraints, -you should consider incorporating that code into your {@code Policy}, rather than -putting it in the {@code LicenseCheckerCallback} methods.

    - -

    In most cases, you should declare your implementation of -{@code LicenseCheckerCallback} as a private class inside your application's main -Activity class.

    - -

    Implement the allow() and dontAllow() methods as -needed. To start with, you can use simple result-handling behaviors in the -methods, such as displaying the license result in a dialog. This helps you get -your application running sooner and can assist with debugging. Later, after you -have determined the exact behaviors you want, you can add more complex handling. -

    - -

    Some suggestions for handling unlicensed responses in -dontAllow() include:

    - -
      -
    • Display a "Try again" dialog to the user, including a button to initiate a -new license check if the reason supplied is {@code Policy.RETRY}.
    • -
    • Display a "Purchase this application" dialog, including a button that -deep-links the user to the application's details page on Google Play, from which the -use can purchase the application. For more information on how to set up such -links, see Linking to your apps -on Google Play.
    • -
    • Display a Toast notification that indicates that the features of the -application are limited because it is not licensed.
    • -
    - -

    The example below shows how the LVL sample application implements -{@code LicenseCheckerCallback}, with methods that display the license check result in a -dialog.

    - -
    -private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
    -    public void allow(int reason) {
    -        if (isFinishing()) {
    -            // Don't update UI if Activity is finishing.
    -            return;
    -        }
    -        // Should allow user access.
    -        displayResult(getString(R.string.allow));
    -    }
    -
    -    public void dontAllow(int reason) {
    -        if (isFinishing()) {
    -            // Don't update UI if Activity is finishing.
    -            return;
    -        }
    -        displayResult(getString(R.string.dont_allow));
    -        
    -        if (reason == Policy.RETRY) {
    -            // If the reason received from the policy is RETRY, it was probably
    -            // due to a loss of connection with the service, so we should give the
    -            // user a chance to retry. So show a dialog to retry.
    -            showDialog(DIALOG_RETRY);
    -        } else {
    -            // Otherwise, the user is not licensed to use this app.
    -            // Your response should always inform the user that the application
    -            // is not licensed, but your behavior at that point can vary. You might
    -            // provide the user a limited access version of your app or you can
    -            // take them to Google Play to purchase the app.
    -            showDialog(DIALOG_GOTOMARKET);
    -        }
    -    }
    -}
    -
    - -

    Additionally, you should implement the applicationError() -method, which the LVL calls to let your application handle errors that are not -retryable. For a list of such errors, see Server -Response Codes in the Licensing Reference. You can implement -the method in any way needed. In most cases, the -method should log the error code and call dontAllow().

    - -

    Create a Handler for posting from LicenseCheckerCallback -to the UI thread

    - -

    During a license check, the LVL passes the request to the Google Play -application, which handles communication with the licensing server. The LVL -passes the request over asynchronous IPC (using {@link android.os.Binder}) so -the actual processing and network communication do not take place on a thread -managed by your application. Similarly, when the Google Play application -receives the result, it invokes a callback method over IPC, which in turn -executes in an IPC thread pool in your application's process.

    - -

    The {@code LicenseChecker} class manages your application's IPC communication with -the Google Play application, including the call that sends the request and -the callback that receives the response. {@code LicenseChecker} also tracks open license -requests and manages their timeouts.

    - -

    So that it can handle timeouts properly and also process incoming responses -without affecting your application's UI thread, {@code LicenseChecker} spawns a -background thread at instantiation. In the thread it does all processing of -license check results, whether the result is a response received from the server -or a timeout error. At the conclusion of processing, the LVL calls your -{@code LicenseCheckerCallback} methods from the background thread.

    - -

    To your application, this means that:

    - -
      -
    1. Your {@code LicenseCheckerCallback} methods will be invoked, in many cases, from a -background thread.
    2. -
    3. Those methods won't be able to update state or invoke any processing in the -UI thread, unless you create a Handler in the UI thread and have your callback -methods post to the Handler.
    4. -
    - -

    If you want your {@code LicenseCheckerCallback} methods to update the UI thread, -instantiate a {@link android.os.Handler} in the main Activity's -{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, -as shown below. In this example, the LVL sample application's -{@code LicenseCheckerCallback} methods (see above) call displayResult() to -update the UI thread through the Handler's -{@link android.os.Handler#post(java.lang.Runnable) post()} method.

    - -
    private Handler mHandler;
    -
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        ...
    -        mHandler = new Handler();
    -    }
    -
    - -

    Then, in your {@code LicenseCheckerCallback} methods, you can use Handler methods to -post Runnable or Message objects to the Handler. Here's how the sample -application included in the LVL posts a Runnable to a Handler in the UI thread -to display the license status.

    - -
        private void displayResult(final String result) {
    -        mHandler.post(new Runnable() {
    -            public void run() {
    -                mStatusText.setText(result);
    -                setProgressBarIndeterminateVisibility(false);
    -                mCheckLicenseButton.setEnabled(true);
    -            }
    -        });
    -    }
    -
    - -

    Instantiate LicenseChecker and LicenseCheckerCallback

    - -

    In the main Activity's -{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, -create private instances of LicenseCheckerCallback and {@code LicenseChecker}. You must -instantiate {@code LicenseCheckerCallback} first, because you need to pass a reference -to that instance when you call the constructor for {@code LicenseChecker}.

    - -

    When you instantiate {@code LicenseChecker}, you need to pass in these parameters:

    - -
      -
    • The application {@link android.content.Context}
    • -
    • A reference to the {@code Policy} implementation to use for the license check. In -most cases, you would use the default {@code Policy} implementation provided by the LVL, -ServerManagedPolicy.
    • -
    • The String variable holding your publisher account's public key for -licensing.
    • -
    - -

    If you are using ServerManagedPolicy, you won't need to access the class -directly, so you can instantiate it in the {@code LicenseChecker} constructor, -as shown in the example below. Note that you need to pass a reference to a new -Obfuscator instance when you construct ServerManagedPolicy.

    - -

    The example below shows the instantiation of {@code LicenseChecker} and -{@code LicenseCheckerCallback} from the onCreate() method of an Activity -class.

    - -
    public class MainActivity extends Activity {
    -    ...
    -    private LicenseCheckerCallback mLicenseCheckerCallback;
    -    private LicenseChecker mChecker;
    -
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        ...
    -        // Construct the LicenseCheckerCallback. The library calls this when done.
    -        mLicenseCheckerCallback = new MyLicenseCheckerCallback();
    -
    -        // Construct the LicenseChecker with a Policy.
    -        mChecker = new LicenseChecker(
    -            this, new ServerManagedPolicy(this,
    -                new AESObfuscator(SALT, getPackageName(), deviceId)),
    -            BASE64_PUBLIC_KEY  // Your public licensing key.
    -            );
    -        ...
    -    }
    -}
    -
    - - -

    Note that {@code LicenseChecker} calls the {@code LicenseCheckerCallback} methods from the UI -thread only if there is valid license response cached locally. If the -license check is sent to the server, the callbacks always originate from the -background thread, even for network errors.

    - - -

    Call checkAccess() to initiate the license check

    - -

    In your main Activity, add a call to the checkAccess() method of the -{@code LicenseChecker} instance. In the call, pass a reference to your -{@code LicenseCheckerCallback} instance as a parameter. If you need to handle any -special UI effects or state management before the call, you might find it useful -to call checkAccess() from a wrapper method. For example, the LVL -sample application calls checkAccess() from a -doCheck() wrapper method:

    - -
        @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        ...
    -        // Call a wrapper method that initiates the license check
    -        doCheck();
    -        ...
    -    }
    -    ...
    -    private void doCheck() {
    -        mCheckLicenseButton.setEnabled(false);
    -        setProgressBarIndeterminateVisibility(true);
    -        mStatusText.setText(R.string.checking_license);
    -        mChecker.checkAccess(mLicenseCheckerCallback);
    -    }
    -
    - - -

    Embed your public key for licensing

    - -

    For each publisher account, the Google Play service automatically -generates a 2048-bit RSA public/private key pair that is used exclusively for -licensing. The key pair is uniquely associated with the publisher account and is -shared across all applications that are published through the account. Although -associated with a publisher account, the key pair is not the same as -the key that you use to sign your applications (or derived from it).

    - -

    The Google Play publisher site exposes the public key for licensing to any -developer signed in to the publisher account, but it keeps the private key -hidden from all users in a secure location. When an application requests a -license check for an application published in your account, the licensing server -signs the license response using the private key of your account's key pair. -When the LVL receives the response, it uses the public key provided by the -application to verify the signature of the license response.

    - -

    To add licensing to an application, you must obtain your publisher account's -public key for licensing and copy it into your application. Here's how to find -your account's public key for licensing:

    - -
      -
    1. Go to the Google Play publisher site and sign in. -Make sure that you sign in to the account from which the application you are -licensing is published (or will be published).
    2. -
    3. In the account home page, locate the "Edit profile" link and click it.
    4. -
    5. In the Edit Profile page, locate the "Licensing" pane, shown below. Your -public key for licensing is given in the "Public key" text box.
    6. -
    - -

    To add the public key to your application, simply copy/paste the key string -from the text box into your application as the value of the String variable -BASE64_PUBLIC_KEY. When you are copying, make sure that you have -selected the entire key string, without omitting any characters.

    - -

    Here's an example from the LVL sample application:

    - -
        public class MainActivity extends Activity {
    -        private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
    -    ...
    -    }
    -
    - -

    Call your LicenseChecker's onDestroy() method -to close IPC connections

    - -

    Finally, to let the LVL clean up before your application -{@link android.content.Context} changes, add a call to the {@code LicenseChecker}'s -onDestroy() method from your Activity's -{@link android.app.Activity#onDestroy()} implementation. The call causes the -{@code LicenseChecker} to properly close any open IPC connection to the Google Play -application's ILicensingService and removes any local references to the service -and handler.

    - -

    Failing to call the {@code LicenseChecker}'s onDestroy() method -can lead to problems over the lifecycle of your application. For example, if the -user changes screen orientation while a license check is active, the application -{@link android.content.Context} is destroyed. If your application does not -properly close the {@code LicenseChecker}'s IPC connection, your application will crash -when the response is received. Similarly, if the user exits your application -while a license check is in progress, your application will crash when the -response is received, unless it has properly called the -{@code LicenseChecker}'s onDestroy() method to disconnect from the service. -

    - -

    Here's an example from the sample application included in the LVL, where -mChecker is the {@code LicenseChecker} instance:

    - -
        @Override
    -    protected void onDestroy() {
    -        super.onDestroy();
    -        mChecker.onDestroy();
    -        ...
    -    }
    -
    - -

    If you are extending or modifying {@code LicenseChecker}, you might also need to call -the {@code LicenseChecker}'s finishCheck() method, to clean up any open IPC -connections.

    - -

    Implementing a DeviceLimiter

    - -

    In some cases, you might want your {@code Policy} to limit the number of actual -devices that are permitted to use a single license. This would prevent a user -from moving a licensed application onto a number of devices and using the -application on those devices under the same account ID. It would also prevent a -user from "sharing" the application by providing the account information -associated with the license to other individuals, who could then sign in to that -account on their devices and access the license to the application.

    - -

    The LVL supports per-device licensing by providing a -DeviceLimiter interface, which declares a single method, -allowDeviceAccess(). When a LicenseValidator is handling a response -from the licensing server, it calls allowDeviceAccess(), passing a -user ID string extracted from the response.

    - -

    If you do not want to support device limitation, no work is -required — the {@code LicenseChecker} class automatically uses a default -implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter -is a "no-op" class whose allowDeviceAccess() method simply returns -a LICENSED response for all users and devices.

    - -
    -

    Caution: Per-device licensing is not recommended for -most applications because:

    -
      -
    • It requires that you provide a backend server to manage a users and devices -mapping, and
    • -
    • It could inadvertently result in a user being denied access to an -application that they have legitimately purchased on another device.
    • -
    -
    - - - - - - - - - - - -

    Obfuscating Your Code

    - -

    To ensure the security of your application, particularly for a paid -application that uses licensing and/or custom constraints and protections, it's -very important to obfuscate your application code. Properly obfuscating your -code makes it more difficult for a malicious user to decompile the application's -bytecode, modify it — such as by removing the license check — -and then recompile it.

    - -

    Several obfuscator programs are available for Android applications, including -ProGuard, which also offers -code-optimization features. The use of ProGuard or a similar program to obfuscate -your code is strongly recommended for all applications that use Google -Play Licensing.

    - -

    Publishing a Licensed Application

    - -

    When you are finished testing your license implementation, you are ready to -publish the application on Google Play. Follow the normal steps to prepare, sign, and then publish the application. -

    - -

    Removing Copy Protection

    - -

    After uploading your licensed application, remember to remove copy protection -from the application, if it is currently used. To check and remove copy -protection, sign in to the publisher site and go the application's upload -details page. In the Publishing options section, make sure that the Copy -Protection radio button selection is "Off".

    - - -

    Where to Get Support

    - -

    If you have questions or encounter problems while implementing or deploying -publishing in your applications, please use the support resources listed in the -table below. By directing your queries to the correct forum, you can get the -support you need more quickly.

    - -

    Table 2. Developer support resources -for Google Play Licensing Service.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Support TypeResourceRange of Topics
    Development and testing issuesGoogle Groups: android-developers -LVL download and integration, library projects, {@code Policy} -questions, user experience ideas, handling of responses, {@code Obfuscator}, IPC, test -environment setup
    Stack Overflow: http://stackoverflow.com/questions/tagged/android
    Accounts, publishing, and deployment issuesGoogle Play -Help ForumPublisher accounts, licensing key pair, test accounts, server -responses, test responses, application deployment and results
    Market -Licensing Support FAQ
    LVL issue trackerMarketlicensing -project issue trackerBug and issue reports related specifically to the LVL source code classes -and interface implementations
    - -

    For general information about how to post to the groups listed above, see Developer Forums document -in the Resources tab.

    - - diff --git a/docs/html/guide/market/licensing/index.jd b/docs/html/guide/market/licensing/index.jd deleted file mode 100644 index 1f15303e4e8e..000000000000 --- a/docs/html/guide/market/licensing/index.jd +++ /dev/null @@ -1,61 +0,0 @@ -page.title=Application Licensing -@jd:body - - -

    Google Play offers a licensing service that lets you enforce licensing policies for -applications that you publish on Google Play. With Google Play Licensing, your application can -query Google Play at run time to obtain the licensing status for the current user, then allow or -disallow further use as appropriate.

    - -

    Using the service, you can apply a flexible licensing policy on an application-by-application -basis—each application can enforce licensing in the way most appropriate for it. If necessary, -an application can apply custom constraints based on the licensing status obtained from Google Play. -For example, an application can check the licensing status and then apply custom constraints -that allow the user to run it unlicensed for a specific validity period. An application can also -restrict use of the application to a specific device, in addition to any other constraints.

    - -

    The licensing service is a secure means of controlling access to your applications. When an -application checks the licensing status, the Google Play server signs the licensing status -response using a key pair that is uniquely associated with the publisher account. Your application -stores the public key in its compiled .apk file and uses it to verify the licensing -status response.

    - -

    Any application that you publish through Google Play can use the Google Play Licensing -service. No special account or registration is needed. Additionally, because the service uses no -dedicated framework APIs, you can add licensing to any application that uses a minimum API level of -3 or higher.

    - -

    Note: The Google Play Licensing service is primarily intended -for paid applications that wish to verify that the current user did in fact pay for the application -on Google Play. However, any application (including free apps) may use the licensing service -to initiate the download of an APK expansion file. In which case, the request that your application -sends to the licensing service is not to check whether the user paid for the app, but to request the -URL of the expansion files. For information about downloading expansion files for your application, -read the guide to APK Expansion Files.

    - - -

    To learn more about Google Play's application licensing service and start integrating it into -your applications, read the following documents:

    - -
    -
    Licensing -Overview
    -
    Describes how the service works and what a typical licensing implementation looks -like.
    -
    Setting Up for -Licensing
    -
    Explains how to set up your Google Play account, development environment, and -testing environment in order to add licensing to your app.
    -
    Adding -Licensing to Your App
    -
    Provides a step-by-step guide to add licensing verification to your application.
    -
    Licensing -Reference
    -
    Provides detailed information about the licensing library's classes and the service response -codes.
    -
    - - - - - diff --git a/docs/html/guide/market/licensing/licensing-reference.jd b/docs/html/guide/market/licensing/licensing-reference.jd deleted file mode 100644 index 0a7e03331b8e..000000000000 --- a/docs/html/guide/market/licensing/licensing-reference.jd +++ /dev/null @@ -1,439 +0,0 @@ -page.title=Licensing Reference -parent.title=Application Licensing -parent.link=index.html -@jd:body - - - - - - -

    LVL Classes and Interfaces

    - -

    Table 1 lists all of the source files in the License Verification -Library (LVL) available through the Android SDK. All of the files are part of -the com.android.vending.licensing package.

    - -

    Table 1. Summary of LVL library -classes and interfaces.

    - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CategoryNameDescription
    License check and resultLicenseCheckerClass that you instantiate (or subclass) to initiate a license check.
    LicenseCheckerCallbackInterface that you implement to handle result of the license check.
    PolicyPolicyInterface that you implement to determine whether to allow -access to the application, based on the license response.
    ServerManagedPolicyDefault {@code Policy} implementation. Uses settings provided by the -licensing server to manage local storage of license data, license validity, -retry.
    StrictPolicyAlternative {@code Policy} implementation. Enforces licensing based on a direct -license response from the server only. No caching or request retry.
    Data obfuscation
    (optional)
    ObfuscatorInterface that you implement if you are using a {@code Policy} (such as -ServerManagedPolicy) that caches license response data in a persistent store. -Applies an obfuscation algorithm to encode and decode data being written or -read.
    AESObfuscatorDefault Obfuscator implementation that uses AES encryption/decryption -algorithm to obfuscate/unobfuscate data.
    Device limitation
    (optional)
    DeviceLimiterInterface that you implement if you want to restrict use of an -application to a specific device. Called from LicenseValidator. Implementing -DeviceLimiter is not recommended for most applications because it requires a -backend server and may cause the user to lose access to licensed applications, -unless designed with care.
    NullDeviceLimiterDefault DeviceLimiter implementation that is a no-op (allows access to all -devices).
    Library core, no integration neededResponseDataClass that holds the fields of a license response.
    LicenseValidatorClass that decrypts and verifies a response received from the licensing -server.
    ValidationExceptionClass that indicates errors that occur when validating the integrity of data -managed by an Obfuscator.
    PreferenceObfuscatorUtility class that writes/reads obfuscated data to the system's -{@link android.content.SharedPreferences} store.
    ILicensingServiceOne-way IPC interface over which a license check request is passed to the -Google Play client.
    ILicenseResultListenerOne-way IPC callback implementation over which the application receives an -asynchronous response from the licensing server.
    -
    - - -

    Server Response Codes

    - -

    Table 2 lists all of the license response codes supported by the -licensing server. In general, an application should handle all of these response -codes. By default, the LicenseValidator class in the LVL provides all of the -necessary handling of these response codes for you.

    - -

    Table 2. Summary of response codes -returned by the Google Play server in a license response.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Response CodeDescriptionSigned?ExtrasComments
    {@code LICENSED}The application is licensed to the user. The user has purchased the -application or the application only exists as a draft.YesVTGT, GRAllow access according to {@code Policy} constraints.
    {@code LICENSED_OLD_KEY}The application is licensed to the user, but there is an updated application -version available that is signed with a different key. Yes VT, GT, GR, UTOptionally allow access according to {@code Policy} constraints. -

    Can indicate that the key pair used by the installed -application version is invalid or compromised. The application can allow access -if needed or inform the user that an upgrade is available and limit further use -until upgrade.

    -
    {@code NOT_LICENSED}The application is not licensed to the user.NoDo not allow access.
    {@code ERROR_CONTACTING_SERVER}Local error — the Google Play application was not able to reach the -licensing server, possibly because of network availability problems. NoRetry the license check according to {@code Policy} retry limits.
    {@code ERROR_SERVER_FAILURE}Server error — the server could not load the publisher account's key -pair for licensing.NoRetry the license check according to {@code Policy} retry limits. -
    {@code ERROR_INVALID_PACKAGE_NAME}Local error — the application requested a license check for a package -that is not installed on the device. No Do not retry the license check. -

    Typically caused by a development error.

    -
    {@code ERROR_NON_MATCHING_UID}Local error — the application requested a license check for a package -whose UID (package, user ID pair) does not match that of the requesting -application. No Do not retry the license check. -

    Typically caused by a development error.

    -
    {@code ERROR_NOT_MARKET_MANAGED}Server error — the application (package name) was not recognized by -Google Play. NoDo not retry the license check. -

    Can indicate that the application was not published -through Google Play or that there is an development error in the licensing -implementation.

    -
    - -

    Note: As documented in -Setting Up The Testing Environment, the response code can be manually -overridden for the application developer and any registered test users via the -Google Play publisher site. -

    -Additionally, as noted above, applications that are in draft mode (in other -words, applications that have been uploaded but have never been -published) will return {@code LICENSED} for all users, even if not listed as a test -user. Since the application has never been offered for download, it is assumed -that any users running it must have obtained it from an authorized channel for -testing purposes.

    - - - - -

    Server Response Extras

    - -

    To assist your application in managing access to the application across the application refund -period and provide other information, The licensing server includes several pieces of -information in the license responses. Specifically, the service provides recommended values for the -application's license validity period, retry grace period, maximum allowable retry count, and other -settings. If your application uses APK -expansion files, the response also includes the file names, sizes, and URLs. The server appends -the settings as key-value pairs in the license response "extras" field.

    - -

    Any {@code Policy} implementation can extract the extras settings from the license -response and use them as needed. The LVL default {@code Policy} implementation, {@code -ServerManagedPolicy}, serves as a working -implementation and an illustration of how to obtain, store, and use the -settings.

    - -

    Table 3. Summary of -license-management settings supplied by the Google Play server in a license -response.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ExtraDescription
    {@code VT}License validity timestamp. Specifies the date/time at which the current -(cached) license response expires and must be rechecked on the licensing server. See the section -below about License validity period. -
    {@code GT}Grace period timestamp. Specifies the end of the period during which a -Policy may allow access to the application, even though the response status is -{@code RETRY}.

    The value is managed by the server, however a typical value would be 5 -or more days. See the section -below about Retry period and maximum retry count.

    {@code GR}Maximum retries count. Specifies how many consecutive {@code RETRY} license checks -the {@code Policy} should allow, before denying the user access to the application. -

    The value is managed by the server, however a typical value would be "10" or -higher. See the section -below about Retry period and maximum retry count.

    {@code UT}Update timestamp. Specifies the day/time when the most recent update to -this application was uploaded and published.

    The server returns this extra -only for {@code LICENSED_OLD_KEYS} responses, to allow the {@code Policy} to determine how much -time has elapsed since an update was published with new licensing keys before -denying the user access to the application.

    {@code FILE_URL1} or {@code FILE_URL2}The URL for an expansion file (1 is for the main file, 2 is the patch file). Use this to -download the file over HTTP.
    {@code FILE_NAME1} or {@code FILE_NAME2}The expansion file's name (1 is for the main file, 2 is the patch file). You must use this -name when saving the file on the device.
    {@code FILE_SIZE1} or {@code FILE_SIZE2}The size of the file in bytes (1 is for the main file, 2 is the patch file). Use this to -assist with downloading and to ensure that enough space is available on the device's shared -storage location before downloading.
    - - - -

    License validity period

    - -

    The Google Play licensing server sets a license validity period for all -downloaded applications. The period expresses the interval of time over which an -application's license status should be considered as unchanging and cacheable by -a licensing {@code Policy} in the application. The licensing server includes the -validity period in its response to all license checks, appending an -end-of-validity timestamp to the response as an extra under the key {@code VT}. A -{@code Policy} can extract the VT key value and use it to conditionally allow access to -the application without rechecking the license, until the validity period -expires.

    - -

    The license validity signals to a licensing {@code Policy} when it must recheck the -licensing status with the licensing server. It is not intended to imply -whether an application is actually licensed for use. That is, when an -application's license validity period expires, this does not mean that the -application is no longer licensed for use — rather, it indicates only that -the {@code Policy} must recheck the licensing status with the server. It follows that, -as long as the license validity period has not expired, it is acceptable for the -{@code Policy} to cache the initial license status locally and return the cached license -status instead of sending a new license check to the server.

    - -

    The licensing server manages the validity period as a means of helping the -application properly enforce licensing across the refund period offered by -Google Play for paid applications. It sets the validity period based on -whether the application was purchased and, if so, how long ago. Specifically, -the server sets a validity period as follows:

    - -
      -
    • For a paid application, the server sets the initial license validity period -so that the license response remains valid for as long as the application is -refundable. A licensing {@code Policy} in the application may cache the -result of the initial license check and does not need to recheck the license -until the validity period has expired.
    • -
    • When an application is no longer refundable, the server -sets a longer validity period — typically a number of days.
    • - - -
    • For a free application, the server sets the validity period to a very high -value (long.MAX_VALUE). This ensures that, provided the {@code Policy} has -cached the validity timestamp locally, it will not need to recheck the -license status of the application in the future.
    • -
    - -

    The {@code ServerManagedPolicy} implementation uses the extracted timestamp -(mValidityTimestamp) as a primary condition for determining whether -to recheck the license status with the server before allowing the user access to -the application.

    - - -

    Retry period and maximum retry count

    - -

    In some cases, system or network conditions can prevent an application's -license check from reaching the licensing server, or prevent the server's -response from reaching the Google Play client application. For example, the -user might launch an application when there is no cell network or data -connection available—such as when on an airplane—or when the -network connection is unstable or the cell signal is weak.

    - -

    When network problems prevent or interrupt a license check, the Google -Play client notifies the application by returning a {@code RETRY} response code to -the {@code Policy}'s processServerResponse() method. In the case of system -problems, such as when the application is unable to bind with Google Play's -{@code ILicensingService} implementation, the {@code LicenseChecker} library itself calls the -Policy processServerResonse() method with a {@code RETRY} response code. -

    - -

    In general, the {@code RETRY} response code is a signal to the application that an -error has occurred that has prevented a license check from completing. - -

    The Google Play server helps an application to manage licensing under -error conditions by setting a retry "grace period" and a recommended maximum -retries count. The server includes these values in all license check responses, -appending them as extras under the keys {@code GT} and {@code GR}.

    - -

    The application {@code Policy} can extract the {@code GT} and {@code GR} extras and use them to -conditionally allow access to the application, as follows:

    - -
      -
    • For a license check that results in a {@code RETRY} response, the {@code Policy} should -cache the {@code RETRY} response code and increment a count of {@code RETRY} responses.
    • -
    • The {@code Policy} should allow the user to access the application, provided that -either the retry grace period is still active or the maximum retries count has -not been reached.
    • -
    - -

    The {@code ServerManagedPolicy} uses the server-supplied {@code GT} and {@code GR} values as -described above. The example below shows the conditional handling of the retry -responses in the allow() method. The count of {@code RETRY} responses is -maintained in the processServerResponse() method, not shown.

    - - -
        
    -public boolean allowAccess() {
    -    long ts = System.currentTimeMillis();
    -    if (mLastResponse == LicenseResponse.LICENSED) {
    -        // Check if the LICENSED response occurred within the validity timeout.
    -        if (ts <= mValidityTimestamp) {
    -            // Cached LICENSED response is still valid.
    -            return true;
    -        }
    -    } else if (mLastResponse == LicenseResponse.RETRY &&
    -                ts < mLastResponseTime + MILLIS_PER_MINUTE) {
    -        // Only allow access if we are within the retry period or we haven't used up our
    -        // max retries.
    -        return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
    -    }
    -    return false;
    -}
    - diff --git a/docs/html/guide/market/licensing/overview.jd b/docs/html/guide/market/licensing/overview.jd deleted file mode 100644 index e7e23f877dad..000000000000 --- a/docs/html/guide/market/licensing/overview.jd +++ /dev/null @@ -1,246 +0,0 @@ -page.title=Licensing Overview -parent.title=Application Licensing -parent.link=index.html -@jd:body - - -
    -
    - -

    Quickview

    -
      -
    • Licensing allows you to verify your app was purchased from Google Play
    • -
    • Your app maintains control of how it enforces its licensing status
    • -
    • The service is free for all developers who publish on Google Play
    • -
    - -

    In this document

    -
      -
    1. License Responses are Secure
    2. -
    3. Licensing Verification Library
    4. -
    5. Requirements and Limitations
    6. -
    7. Replacement for Copy Protection
    8. -
    - -
    -
    - - -

    Google Play Licensing is a network-based service that lets an application query a trusted -Google Play licensing server to determine whether the application is licensed to the current -device user. The licensing service is based on the capability of the Google Play licensing server -to determine whether a given user is licensed to use a given application. Google Play considers a -user to be licensed if the user is a recorded purchaser of the application.

    - -

    The request starts when your application makes a request to a service hosted by -the Google Play client application. The Google Play application then sends a request to -the licensing server and receives the result. The Google Play application sends -the result to your application, which can allow or disallow further use of the -application as needed.

    - -

    Note: If a paid application has been uploaded to Google Play but -saved only as a draft application (the app is unpublished), the licensing server considers all users -to be licensed users of the application (because it's not even possible to purchase the app). -This exception is necessary in order for you to perform testing of your licensing -implementation.

    - - -
    - -

    Figure 1. Your application initiates a -license check through the License Verification Library and the Google Play -client, which handles communication with the Google Play server.

    -
    - - -

    To properly identify the user and determine the license status, the licensing server requires -information about the application and user—your application and the Google Play client work -together to assemble the information and the Google Play client passes it to the server.

    - -

    To help you add licensing to your application, the Android SDK provides a downloadable set of -library sources that you can include in your application project: the Google Market -Licensing package. The License Verification Library (LVL) is a library you can add to your -application that -handles all of the licensing-related communication with the Google Play licensing service. With -the LVL added to your application, your application can determine its licensing status for the -current user by simply calling a method and implementing a callback that receives the status -response.

    - -

    Your application does not query the licensing server -directly, but instead calls the Google Play client over remote IPC to -initiate a license request. In the license request:

    - -
      -
    • Your application provides: its package name, a nonce that is later used to -validate any response from the server, and a callback over which the -response can be returned asynchronously.
    • -
    • The Google Play client collects the necessary information about the user and the device, -such as the device's primary Google account username, IMSI, and other -information. It then sends the license check request to the server on behalf of -your application.
    • -
    • The Google Play server evaluates the request using all available information, attempting -to establish the user's identity to a sufficient level of confidence. The server -then checks the user identity against purchase records for your application and -returns a license response, which the Google Play client returns to your -application over the IPC callback.
    • -
    - -

    You can choose when, and how often, you want your application to check its -license and you have full control over how it handles the response, verifies the -signed response data, and enforces access controls.

    - -

    Notice that during a license check, your application does not manage any -network connections or use any licensing related APIs in the Android platform.

    - - - - -

    License Responses are Secure

    - -

    To ensure the integrity of each license query, the server signs the license -response data using an RSA key pair that is shared exclusively between the Google Play -server and you.

    - -

    The licensing service generates a single licensing key pair for each -publisher account and exposes the public key in your account's profile page. You must copy the -public key from the web site and embed it in your application source code. The server retains the -private key internally and uses it to sign license responses for the applications you -publish with that account.

    - -

    When your application receives a signed response, it uses the embedded public -key to verify the data. The use of public key cryptography in the licensing -service makes it possible for the application to detect responses that have been -tampered with or that are spoofed.

    - - - - -

    Licensing Verification Library

    - -

    The Android SDK provides a downloadable package called the Google Market Licensing package, -which includes the License Verification Library (LVL). The LVL greatly simplifies the process of -adding licensing to your application and helps ensure a more secure, robust implementation for your -application. The LVL provides internal classes that handle most of the standard operations of a -license query, such as contacting the Google Play client to initiate a license request and -verifying and validating the responses. It also exposes interfaces that let you easily plug in your -custom code for defining licensing policy and managing access as needed by your application. The key -LVL interfaces are:

    - -
    -
    {@code Policy}
    -
    Your implementation determines whether to allow access to the -application, based on the license response received from the server and any -other data available (such as from a backend server associated with your -application). The implementation can evaluate the various fields of the license -response and apply other constraints, if needed. The implementation also lets -you manage the handling of license checks that result in errors, such as network -errors.
    - -
    {@code LicenseCheckerCallback}
    -
    Your implementation manages access to the -application, based on the result of the {@code Policy} object's handling of the license -response. Your implementation can manage access in any way needed, including -displaying the license result in the UI or directing the user to purchase the -application (if not currently licensed).
    -
    - - -

    To help you get started with a {@code Policy}, the LVL provides two fully complete -{@code Policy} implementations that you can use without modification or adapt to your -needs:

    - -
    -
    {@code ServerManagedPolicy}
    -
    A flexible {@code Policy} -that uses settings provided by the licensing server to manage response caching -and access to the application while the device is offline (such as when the -user is on an airplane). For most applications, the use of -{@code ServerManagedPolicy} is highly recommended.
    - -
    {@code StrictPolicy}
    -
    A restrictive {@code Policy} that -does not cache any response data and allows the application access only -when the server returns a licensed response.
    -
    - -

    The LVL is available as a downloadable package of the Android SDK. The -package includes both the LVL itself and an example application that shows how -the library should be integrated with your application and how your application -should manage response data, UI interaction, and error conditions.

    - -

    The LVL sources are provided as an Android library project, which -means that you can maintain a single set of library sources and share them -across multiple applications. A full test environment is also available through -the SDK, so you can develop and test the licensing implementation in your -applications before publishing them, even if you don't have access to a -physical device.

    - - - - -

    Requirements and Limitations

    - -

    Google Play Licensing is designed to let you apply license controls to -applications that you publish through Google Play. The service is not -designed to let you control access to applications that are not published -through Google Play or that are run on devices that do not offer the Google -Play client.

    - -

    Here are some points to keep in mind as you implement licensing in your -application:

    - -
      -
    • An application can use the service only if the Google Play client is -installed on its host device and the device is running Android 1.5 (API level 3) -or higher.
    • -
    • To complete a license check, the licensing server must be accessible over -the network. You can implement license caching behaviors to manage access to your application when -there is no network connectivity.
    • -
    • The security of your application's licensing controls ultimately relies on -the design of your implementation itself. The service provides the building -blocks that let you securely check licensing, but the actual enforcement and -handling of the license are factors are up to you. By following the best -practices in the following documents, you can help ensure that your implementation will be -secure.
    • -
    • Adding licensing to an application does not affect the way the application -functions when run on a device that does not offer Google Play.
    • -
    • You can implement licensing controls for a free app, but only if you're using the service to -provide APK expansion files.
    • -
    - - - -

    Replacement for Copy Protection

    - -

    Google Play Licensing is a flexible, secure mechanism for controlling -access to your applications. It effectively replaces the Copy Protection -mechanism offered on Google Play and gives you wider distribution -potential for your applications.

    - -
      -
    • A limitation of the legacy Copy Protection mechanism on Google Play is -that applications using it can be installed only on compatible devices that -provide a secure internal storage environment. For example, a copy-protected -application cannot be downloaded from Google Play to a device that provides root -access, and the application cannot be installed to a device's SD card.
    • -
    • With Google Play licensing, you can move to a license-based model in -which access is not bound to the characteristics of the host device, but to your -publisher account on Google Play and the licensing policy that you define. -Your application can be installed and controlled on any compatible device on -any storage, including SD card.
    • -
    - -

    Although no license mechanism can completely prevent all unauthorized use, -the licensing service lets you control access for most types of normal usage, -across all compatible devices, locked or unlocked, that run Android 1.5 or -higher version of the platform.

    - -

    To begin adding application licensing to your application, continue to Setting Up for Licensing.

    - - - - - - diff --git a/docs/html/guide/market/licensing/setting-up.jd b/docs/html/guide/market/licensing/setting-up.jd deleted file mode 100644 index 0de7819b0108..000000000000 --- a/docs/html/guide/market/licensing/setting-up.jd +++ /dev/null @@ -1,701 +0,0 @@ -page.title=Setting Up for Licensing -parent.title=Application Licensing -parent.link=index.html -@jd:body - - - - -

    Before you start adding license verification to your application, you need to set up your Google -Play publishing account, your development environment, and test accounts required to verify -your implementation.

    - - -

    Setting Up a Publisher Account

    - -

    If you don't already have a publisher account for Google Play, you need to register for one -using your Google account and agree to the terms of service on the Google Play publisher site:

    - -

    http://play.google.com/apps/publish -

    - -

    For more information, see Publishing on Google Play.

    - -

    If you already have a publisher account on Google Play, use your existing -account to set up licensing.

    - -

    Using your publisher account on Google Play, you can:

    - -
      -
    • Obtain a public key for licensing
    • -
    • Debug and test an application's licensing implementation, prior to -publishing the application
    • -
    • Publish the applications to which you have added licensing support
    • -
    - -

    Administrative settings for licensing

    - -

    You can manage several -administrative controls for Google Play licensing on the publisher site. The controls are available -in the Edit Profile page, in the "Licensing" panel, shown in figure 1. The controls -let you:

    - -
      -
    • Set up multiple "test accounts," identified by email address. The licensing -server allows users signed in to test accounts on a device or emulator to send -license checks and receive static test responses.
    • -
    • Obtain the account's public key for licensing. When you are implementing -licensing in an application, you must copy the public key string into the -application.
    • -
    • Configure static test responses that the server sends, when it receives a -license check for an application uploaded to the publisher account, from a user -signed in to the publisher account or a test account.
    • -
    - - - -

    Figure 1. The Licensing -panel of your account's Edit Profile page lets you manage administrative -settings for licensing.

    - -

    For more information about how to work with test accounts and static test -responses, see Setting Up a Testing Environment, below. - - - -

    Setting Up the Development Environment

    - -

    Setting up your environment for licensing involves these tasks:

    - -
      -
    1. Setting up the runtime environment for development
    2. -
    3. Downloading the LVL into your SDK
    4. -
    5. Setting up the Licensing Verification Library
    6. -
    7. Including the LVL library project in your application
    8. -
    - -

    The sections below describe these tasks. When you are done with setup, -you can begin Adding -Licensing to Your App.

    - -

    To get started, you need to set up a proper runtime environment on which -you can run, debug, and test your application's implementation of license -checking and enforcement.

    - - -

    Setting up the runtime environment

    - -

    As described earlier, applications check licensing status not by contacting -the licensing server directly, but by binding to a service provided by the -Google Play application and initiating a license check request. The Google -Play service then handles the direct communication with the licensing server -and finally routes the response back to your application. To debug and test -licensing in your application, you need to set up a runtime environment that -includes the necessary Google Play service, so that your application is able -to send license check requests to the licensing server.

    - -

    There are two types of runtime environment that you can use:

    - -
      -
    • An Android-powered device that includes the Google Play application, or
    • -
    • An Android emulator running the Google APIs Add-on, API level 8 (release 2) -or higher
    • -
    - -

    Running on a device

    - -

    To use an Android-powered device for -debugging and testing licensing, the device must:

    - -
      -
    • Run a compatible version of Android 1.5 or later (API level -3 or higher) platform, and
    • -
    • Run a system image on which the Google Play client application -is preinstalled.
    • -
    - -

    If Google Play is not preinstalled in the system image, your application won't -be able to communicate with the Google Play licensing server.

    - -

    For general information about how to set up a device for use in developing -Android applications, see Using Hardware Devices.

    - -

    Running on an Android emulator

    - -

    If you don't have a device available, you can use an Android emulator for debugging and testing -licensing.

    - -

    Because the Android platforms provided in the Android SDK do -not include Google Play, you need to download the Google APIs Add-On -platform, API level 8 (or higher), from the SDK repository. After downloading -the add-on, you need to create an AVD configuration that uses that system image. -

    - -

    The Google APIs Add-On does not include the full Google Play client. -However, it does provide:

    - -
      -
    • An Google Play background service that implements the -ILicensingService remote interface, so that your application can -send license checks over the network to the licensing server.
    • -
    • A set of underlying account services that let you add an a Google account on -the AVD and sign in using your publisher account or test account credentials. -

      Signing in using your publisher or test account enables you to debug and test -your application without having publish it. For more information see Signing in to an authorized account, below.

    • -
    - -

    Several versions of the Google APIs add-on are available through the SDK Manager, but only -the version for Android 2.2 and higher includes the necessary Google -Play services.

    - -

    To set up an emulator for adding licensing to an application, follow -these steps:

    - -
      -
    1. Launch the Android SDK Manager (available under the Eclipse Window -menu or by executing {@code <sdk>/tools/android sdk}).
    2. -
    3. Select and download Google APIs for the Android version you'd like to target -(must be Android 2.2 or higher).
    4. -
    5. When the download is complete, open the AVD Manager (available under the Eclipse -Window -menu or by executing {@code <sdk>/tools/android avd}).
    6. -
    7. Click -New and set the configuration details for the new AVD.
    8. -
    9. In the dialog that appears, assign a descriptive name to the AVD and then -use the Target menu to choose the Google APIs as -the system image to run on the new AVD. Set the other configuration details as -needed and then click Create AVD to finish. The SDK tools -create the new AVD configuration, which then appears in the list of available -Android Virtual Devices.
    10. -
    - -

    If you are not familiar with AVDs or how to use them, see Managing Virtual Devices.

    - -

    Updating your project configuration

    - -

    After you set up a runtime environment that meets the requirements described -above — either on an actual device or on an emulator — make sure to -update your application project or build scripts as needed, so that your compiled -.apk files that use licensing are deployed into that environment. -In particular, if you are developing in Eclipse, make sure that you set up a -Run/Debug Configuration that targets the appropriate device or AVD.

    - -

    You do not need to make any changes to your application's -build configuration, provided that the project is already configured to compile -against a standard Android 1.5 (API level 3) or higher library. For example: - -

      -
    • If you have an existing application that is compiled against -the Android 1.5 library, you do not need to make any changes to your -build configuration to support licensing. The build target meets the minimum -requirements for licensing, so you would continue building -against the same version of the Android platform.
    • - -
    • Similarly, if you are building against Android 1.5 (API level 3) but -are using an emulator running the Google APIs Add-On API 8 as the application's -runtime environment, there is no need to change your application's build -configuration.
    • -
    - -

    In general, adding licensing to an application should have no impact -whatsoever on the application's build configuration.

    - - -

    Downloading the LVL

    - -

    The License Verification Library (LVL) is a collection of helper classes that -greatly simplify the work that you need to do to add licensing to your -application. In all cases, we recommend that you download the LVL and use it as -the basis for the licensing implementation in your application.

    - -

    The LVL is available as a downloadable package of the Android SDK. The -package includes:

    - -
      -
    • The LVL sources, stored inside an Android library project.
    • -
    • An example application called "sample" that depends on the LVL library -project. The example illustrates how an application uses the library helper -classes to check and enforce licensing.
    • -
    - -

    To download the LVL package into your development environment, use the -Android SDK Manager. Launch the Android SDK Manager and then -select the Google Market Licensing package, as shown in figure 2. -Accept the terms and click Install Selected to begin the download.

    - - -

    Figure 2. The Licensing package contains the LVL and -the LVL sample application.

    - -

    When the download is complete, the Android SDK Manager installs both -the LVL library project and the example application into these directories:

    - -

    <sdk>/extras/google/market_licensing/library/ -  (the LVL library project)
    -<sdk>/extras/google/market_licensing/sample/  (the example -application)

    - -

    If you aren't familiar with how to download packess into your SDK, see the -Adding SDK Packages -document.

    - - -

    Setting Up the Licensing Verification Library

    - -

    After downloading the LVL to your computer, you need to set it up in your -development environment, either as an Android library project or by -copying (or importing) the library sources directly into your existing -application package. In general, using the LVL as a library project is recommended, -since it lets you reuse your licensing code across multiple applications and -maintain it more easily over time. Note that the LVL is not designed to be -compiled separately and added to an application as a static .jar file.

    - -

    Moving the library sources to a new location

    - -

    Because you will be customizing the LVL sources to some extent, you should -make sure to move or copy the library sources (the entire -directory at <sdk>/market_licensing/library/) -to a working directory outside of the SDK. You should then use the relocated -sources as your working set. If you are using a source-code management -system, add and track the sources that are in the working location rather -than those in default location in the SDK.

    - -

    Moving the library sources is important is because, when you later update the -Licensing package, the SDK installs the new files to the same location as -the older files. Moving your working library files to a safe location ensures -that your work won't be inadvertently overwritten should you download a new -version of the LVL.

    - -

    Creating the LVL as a library project

    - - - -

    The recommended way of using the LVL is setting it up as a new Android -library project. A library project is a type of development project -that holds shared Android source code and resources. Other Android application -projects can reference the library project and, at build time, include its -compiled sources in their .apk files. In the context of licensing, -this means that you can do most of your licensing development once, in a library -project, then include the library sources in your various application projects. -In this way, you can easily maintain a uniform implementation of licensing -across all of your projects and maintain it centrally.

    - -

    The LVL is provided as a configured library project — once you have -downloaded it, you can start using it right away.

    - -

    If you are working in Eclipse with ADT, you need to add the LVL to your -workspace as a new development project, in the same way as you would a new -application project.

    - -
      -
    1. Use the New Project Wizard to create a new -project from existing sources. Select the LVL's library directory -(the directory containing the library's AndroidManifest.xml file) as the project -root.
    2. -
    3. When you are creating the library project, you can select any application -name, package, and set other fields as needed.
    4. -
    5. For the library's build target, select Android 1.5 (API level 3) or higher.
    6. -
    - -

    When created, the project is -predefined as a library project in its project.properties file, so -no further configuration is needed.

    - -

    For more information about how to create an application project or work with -library projects in Eclipse, see Managing Projects from -Eclipse with ADT.

    - - -

    Copying the LVL sources to your application

    - -

    As an alternative to adding the LVL as a library project, you can copy the -library sources directly into your application. To do so, copy (or import) the -LVL's library/src/com directory into your application's -src/ directory.

    - -

    If you add the LVL sources directly to your application, you can skip the -next section and start working with the library, as described in Adding -Licensing to Your App.

    - - -

    Including the LVL library project sources in your -application

    - -

    If you want to use the LVL sources as a library project, you need to add a -reference to the LVL library project in your application project properties. This tells -build tools to include the LVL library project sources in your application at -compile time. The process for adding a reference to a library project depends -on your development environment, as described below.

    - -

    If you are developing in Eclipse with ADT, you should already have added the -library project to your workspace, as described in the previous section. If you -haven't done that already, do it now before continuing.

    - -

    Next, open the application's project properties window, as shown below. -Select the "Android" properties group and click Add, then -choose the LVL library project (com_android_vending_licensing) and click -OK. For more information, see - -Managing Projects from Eclipse with ADT

    . - - - -

    Figure 3. If you are -working in Eclipse with ADT, you can add the LVL library project to your -application from the application's project properties.

    - - -

    If you are developing using the SDK command-line tools, navigate to the -directory containing your application project and open the -project.properties file. Add a line to the file that specifies the -android.library.reference.<n> key and the path to the -library. For example:

    - -
    android.library.reference.1=path/to/library_project
    - -

    Alternatively, you can use this command to update the project -properties, including the reference to the library project:

    - -
    android update lib-project
    ---target <target_ID> \
    ---path path/to/my/app_project \
    ---library path/to/my/library_project
    -
    - -

    For more information about working with library projects, -see -Setting up a Library Project.

    - - - - - - - - - - - - - - - - - - - - - -

    Setting Up the Testing Environment

    - -

    The Google Play publisher site provides configuration tools that let you -and others test licensing on your application before it is published. As you are -implementing licensing, you can make use of the publisher site tools to test -your application's Policy and handling of different licensing responses and -error conditions.

    - -

    The main components of the test environment for licensing include:

    - -
      -
    • A "Test response" configuration in your publisher account that lets you -set the static licensing response returned, when the server processes a -license check for an application uploaded to the publisher account, from a user -signed in to the publisher account or a test account.
    • -
    • An optional set of test accounts that will receive the static test -response when they check the license of an application that you have uploaded -(regardless whether the application is published or not).
    • -
    • A runtime environment for the application that includes the Google Play -application or Google APIs Add-On, on which the user is signed in to the -publisher account or one of the test accounts.
    • -
    - -

    Setting up the test environment properly involves:

    - -
      -
    1. Setting static test responses that are returned by the licensing server.
    2. -
    3. Setting up test accounts as needed.
    4. -
    5. Signing in properly to an emulator or device, before initiating a license check test.
    6. -
    - -

    The sections below provide more information.

    - - -

    Setting test responses for license checks

    - -

    Google Play provides a configuration setting in your publisher account -that lets you override the normal processing of a license check and return a -specified static response code. The setting is for testing only and applies -only to license checks for applications that you have uploaded, made by -any user signed in to an emulator or device using the credentials of the -publisher account or a registered test account. For other users, the server -always processes license checks according to normal rules.

    - -

    To set a test response for your account, sign in to your publisher account -and click "Edit Profile". In the Edit Profile page, locate the Test Response -menu in the Licensing panel, shown below. You can select from the full set of -valid server response codes to control the response or condition you want to -test in your application.

    - -

    In general, you should make sure to test your application's licensing -implementation with every response code available in the Test Response menu. -For a description of the codes, see Server -Response Codes in the Licensing Reference.

    - - -

    Figure 4. The Licensing -panel of your account's Edit Profile page, showing the Test Accounts field and the -Test Response menu.

    - -

    Note that the test response that you configure applies account-wide — -that is, it applies not to a single application, but to all -applications associated with the publisher account. If you are testing multiple -applications at once, changing the test response will affect all of those -applications on their next license check (if the user is signed in to -the emulator or device using the publisher account or a test account).

    - -

    Before you can successfully receive a test response for a license check, -you must sign in to the device or emulator on which the application -is installed, and from which it is querying the server. Specifically, you must -sign using either your publisher account or one of the test accounts that you -have set up. For more information about test accounts, see the next section.

    - -

    See Server -Response Codes for a list of -test responses available and their meanings.

    - - -

    Setting up test accounts

    - -

    In some cases, you might want to let multiple teams of developers test -licensing on applications that will ultimately be published through your -publisher account, but without giving them access to your publisher account's -sign-in credentials. To meet that need, the Google Play publisher site lets -you set up one or more optional test accounts — accounts that are -authorized to query the licensing server and receive static test responses from -your publisher account.

    - -

    Test accounts are standard Google accounts that you register on your -publisher account, such that they will receive the test response for -applications that you have uploaded. Developers can then sign in to their -devices or emulators using the test account credentials and initiate license -checks from installed applications. When the licensing server receives a license -check from a user of a test account, it returns the static test response -configured for the publisher account.

    - -

    Necessarily, there are limitations on the access and permissions given to -users signed in through test accounts, including:

    - -
      -
    • Test account users can query the licensing server only for applications that -are already uploaded to the publisher account.
    • -
    • Test account users do not have permission to upload applications to your -publisher account.
    • -
    • Test account users do not have permission to set the publisher account's -static test response.
    • -
    - -

    The table below summarizes the differences in capabilities, between the -publisher account, a test account, and any other account.

    - -

    Table 1. -Differences in account types for testing licensing.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Account TypeCan check license before upload?Can receive test response?Can set test response?
    Publisher accountYesYesYes
    Test accountNoYesNo
    OtherNoNoNo
    - -

    Registering test accounts on the publisher account

    - -

    To get started, you need to register each test account in your publisher -account. As shown in Figure 4, you -register test accounts in the Licensing panel of your publisher account's Edit -Profile page. Simply enter the accounts as a comma-delimited list and click -Save to save your profile changes.

    - -

    You can use any Google account as a test account. If you want to own and -control the test accounts, you can create the accounts yourself and distribute -the credentials to your developers or testers.

    - -

    Handling application upload and distribution for test -account users

    - -

    As mentioned above, users of test accounts can only receive static test -responses for applications that are uploaded to the publisher account. Since -those users do not have permission to upload applications, as the publisher you -will need to work with those users to collect apps for upload and distribute -uploaded apps for testing. You can handle collection and distribution in any way -that is convenient.

    - -

    Once an application is uploaded and becomes known to the licensing server, -developers and testers can continue modify the application in their local -development environment, without having to upload new versions. You only need to -upload a new version if the local application increments the -versionCode attribute in the manifest file.

    - -

    Distributing your public key to test account users

    - -

    The licensing server handles static test responses in the normal way, -including signing the license response data, adding extras parameters, and so -on. To support developers who are implementing licensing using test accounts, -rather than the publisher account, you will need to distribute -your public key to them. Developers without access to the publisher site do not -have access to your public key, and without the key they won't be able to -verify license responses.

    - -

    Note that if you decide to generate a new licensing key pair for your account -for some reason, you need to notify all users of test accounts. For -testers, you can embed the new key in the application package and distribute it -to users. For developers, you will need to distribute the new key to them -directly.

    - - -

    Signing in to an authorized account in the runtime -environment

    - -

    The licensing service is designed to determine whether a given user is -licensed to use a given application — during a license check, the Google -Play application gathers the user ID from the primary account on the system -and sends it to the server, together with the package name of the application -and other information. However, if there is no user information available, the -license check cannot succeed, so the Google Play application terminates the -request and returns an error to the application.

    - -

    During testing, to ensure that your application can successfully query the -licensing server, you must make sure that you sign in to an account on the -device or emulator using:

    - -
      -
    • The credentials of a publisher account, or
    • -
    • The credentials of a test account that is registered with a publisher -account
    • -
    - - - - -

    Signing in using a publisher account offers the advantage of letting your -applications receive static test responses even before the applications are -uploaded to the publisher site.

    - -

    If you are part of a larger organization or are working with external groups -on applications that will be published through your site, you will more likely -want to distribute test accounts instead, then use those to sign in during -testing.

    - -

    To sign in on a device or emulator, follow the steps below. The preferred -approach is to sign in as the primary account — however, if there are -other accounts already in use on the device or emulator, you can create an -additional account and sign in to it using the publisher or test account -credentials.

    - -
      -
    1. Open Settings > Accounts & sync
    2. -
    3. Select Add Account and choose to add a Google account. -
    4. -
    5. Select Next and then Sign in.
    6. -
    7. Enter the username and password of either the publisher account or a test -account that is registered in the publisher account.
    8. -
    9. Select Sign in. The system signs you in to the new -account.
    10. -
    - -

    Once you are signed in, you can begin testing licensing in your application -(if you have completed the LVL integration steps above). When your application -initiates a license check, it will receive a response containing the static test -response configured on the publisher account.

    - -

    Note that, if you are using an emulator, you will need to sign in to the -publisher account or test account each time you wipe data when restarting the -emulator.

    - -

    Once you've completed the setup procedures, continue to Adding Licensing to Your App.

    - - - diff --git a/docs/html/guide/market/publishing/multiple-apks.jd b/docs/html/guide/market/publishing/multiple-apks.jd deleted file mode 100644 index e7cfa33dac95..000000000000 --- a/docs/html/guide/market/publishing/multiple-apks.jd +++ /dev/null @@ -1,643 +0,0 @@ -page.title=Multiple APK Support - -@jd:body - -
    -
    - -

    Quickview

    -
      -
    • Simultaneously publish different APKs for different -device configurations
    • -
    • Different APKs are distributed to different devices based on filters declared in the -manifest file
    • -
    • You should publish multiple APKs only when it's not possible or reasonable to -support all desired devices with a single APK
    • -
    - -

    In this document

    -
      -
    1. Publishing Concepts -
        -
      1. Active APKs
      2. -
      3. Simple mode and advanced mode
      4. -
      -
    2. -
    3. How Multiple APKs Work -
        -
      1. Supported filters
      2. -
      3. Rules for multiple APKs
      4. -
      -
    4. -
    5. Creating Multiple APKs -
        -
      1. Assigning version codes
      2. -
      -
    6. -
    7. Using a Single APK Instead -
        -
      1. Supporting multiple GL textures
      2. -
      3. Supporting multiple screens
      4. -
      5. Supporting multiple API levels
      6. -
      -
    8. -
    - -

    See also

    -
      -
    1. Filters on Google Play
    2. -
    3. Supporting Multiple Screens
    4. -
    5. Compatibility -Package
    6. -
    7. Android API Levels
    8. -
    - -
    -
    - -

    Multiple APK support is a feature on Google Play that allows you to publish different APKs -for your application that are each targeted to different device configurations. Each APK is a -complete and independent version of your application, but they share the same application listing on -Google Play and must share the same package name and be signed with the same release key. This -feature is useful for cases in which your application cannot reach all desired devices with a single -APK.

    - -

    Android-powered devices may differ in several ways and it's important -to the success of your application that you make it available to as many devices as possible. -Android applications usually run on most compatible devices with a single APK, by supplying -alternative resources for different configurations (for example, different layouts for different -screen sizes) and the Android system selects the appropriate resources for the device at runtime. In -a few cases, however, a single APK is unable to support all device configurations, because -alternative resources make the APK file too big (greater than 50MB) or other technical challenges -prevent a single APK from working on all devices.

    - -

    Although we encourage you to develop and publish a single APK that supports as -many device configurations as possible, doing so is sometimes not possible. To help -you publish your application for as many devices as possible, Google Play allows you to -publish multiple APKs under the same application listing. Google Play then supplies each APK to -the appropriate devices based on configuration support you've declared in the manifest file of each -APK.

    - -

    By publishing your application with multiple APKs, you can:

    - -
      -
    • Support different OpenGL texture compression formats with each APK.
    • -
    • Support different screen configurations with each APK.
    • -
    • Support different platform versions with each APK.
    • -
    - -

    Currently, these are the only device characteristics that Google Play supports for publishing -multiple APKs as the same application.

    - -

    Note: You should generally use multiple APKs to support -different device configurations only when your APK is too large (greater than -50MB). Using a single APK to support different configurations is always the best practice, -because it makes the path for application updates simple and clear for users (and also makes -your life simpler by avoiding development and publishing complexity). Read the section below about -Using a Single APK Instead to -consider your options before publishing multiple APKs.

    - - -

    Publishing Concepts

    - -

    Before you start publishing multiple APKs on Google Play, you must understand a few -concepts regarding how the Google Play publisher site works.

    - -

    Active APKs

    - - - - -

    Before you can publish your application (whether publishing one or multiple APKs), you -must "activate" your APK(s) from the APK files tab. When you activate an APK, it -moves into the list of Active APKs. This list allows you to preview which APK(s) -you're about to publish.

    - -

    If there are no errors, any "active" APK will be published to -Google Play when you click the Publish button (if the application is -unpublished) or when you click the Save button (if the application is -already published).

    - - -

    Simple mode and advanced mode

    - -

    The Google Play publisher site provides two modes for managing the APKs associated with -your application: simple mode and advanced mode. You can switch between these by -clicking the -link at the top-right corner of the APK files tab.

    - -

    Simple mode is the traditional way to publish an application, using one APK at a time. In -simple mode, only one APK can be activated at a time. If you upload a new APK to update -the application, clicking "Activate" on the new APK deactivates the currently -active APK (you must then click Save to publish the new APK).

    - -

    Advanced mode allows you to activate and publish multiple APKs that are each designed for a -specific set of device configurations. However, there are several rules based on the manifest -declarations in each APK that determine whether you're allowed to activate each APK along with -others. When you activate an APK and it violates one of the rules, you will receive an error or -warning message. If it's an error, you cannot publish until you resolve the problem; if it's a -warning, you can publish the activated APKs, but there might be unintended consequences as to -whether your application is available for different devices. These rules are discussed more -below.

    - - -

    How Multiple APKs Work

    - -

    The concept for using multiple APKs on Google Play is that you have just one entry in -Google Play for your application, but different devices might download a different APK. This -means that:

    - -
      -
    • You maintain only one set of product details (app description, icons, screenshots, etc.). -This also means you cannot charge a different price for different APKs.
    • -
    • All users see only one version of your application on Google Play, so they are not -confused by different versions you may have published that are "for tablets" or -"for phones."
    • -
    • All user reviews are applied to the same application listing, even though users on different -devices may have different APKs.
    • -
    • If you publish different APKs for different versions of Android (for different API levels), -then when a user's device receives a system update that qualifies them for a different APK you've -published, Google Play updates the user's application to the APK designed for the higher version -of Android. Any system data associated with the application is retained (the same as with normal -application updates when using a single APK).
    • -
    - -

    To publish multiple APKs for the same application, you must enable Advanced mode -in your application's APK files tab (as discussed in the previous section). Once -in advanced mode, you can upload, activate, then publish multiple APKs for the same application. The -following sections describe more about how it works.

    - - -

    Supported filters

    - -

    Which devices receive each APK is determined by Google Play filters that are specified by -elements in the manifest file of each APK. However, Google Play allows you to publish multiple -APKs only when each APK uses filters to support a variation of the following -device characteristics:

    - -
      -
    • OpenGL texture compression formats -

      This is based on your manifest file's {@code -<supports-gl-texture>} element(s).

      -

      For example, when developing a game that uses OpenGL ES, you can provide one APK for -devices that support ATI texture compression and a separate APK for devices -that support PowerVR compression (among many others).

      -
      -
    • - -
    • Screen size (and, optionally, screen density) -

      This is based on your manifest file's {@code -<supports-screens>} or {@code -<compatible-screens>} element. You should never use both elements and you should use only -{@code -<supports-screens>} when possible.

      -

      For example, you can provide one APK that supports small and normal size screens and another -APK that supports large and xlarge screens.

      - -

      Note: The Android system provides strong support for -applications to support all screen configurations with a single APK. You should avoid creating -multiple APKs to support different screens unless absolutely necessary and instead follow the guide -to Supporting Multiple -Screens so that your application is flexible and can adapt to all screen configurations -with a single APK.

      -

      Caution: By default, all screen size attributes in the {@code -<supports-screens>} element are "true" if you do not declare them otherwise. However, -because the {@code android:xlargeScreens} attribute was added in Android 2.3 (API level -9), Google Play will assume that it is "false" if your application does not set either {@code -android:minSdkVersion} or {@code -android:targetSdkVersion} to "9" or higher.

      -

      Caution: You should not combine both {@code -<supports-screens>} and {@code -<compatible-screens>} elements in your manifest file. Using both increases the chances -that you'll introduce an error due to conflicts between them. For help deciding which to use, read -Distributing to Specific Screens. -If you can't avoid using both, be aware that for any conflicts in agreement between a given size, -"false" will win.

      -
      -
    • - -
    • API level -

      This is based on your manifest file's {@code <uses-sdk>} element. -You -can use both the {@code -android:minSdkVersion} and {@code android:maxSdkVersion} -attributes to specify support for different API levels.

      -

      For example, you can publish your application with one APK that supports API levels 4 - 7 -(Android 1.6 - 2.1)—using only APIs available since API level 4 or lower—and another -APK that supports API levels 8 and above (Android 2.2+)—using APIs available since API level 8 -or lower.

      -
      -

      Note:

      -
        -
      • If you use this characteristic as the factor to distinguish multiple APKs, then the APK -with a higher {@code -android:minSdkVersion} value must have a higher {@code android:versionCode} -value. This is also true if two APKs overlap their device support based on a different supported -filter. This ensures that when a device receives a system update, Google Play can offer the user -an update for your application (because updates are based on an increase in the app version code). -This requirement is described further in the section below about Rules for -multiple APKs.
      • -
      • You should avoid using {@code -android:maxSdkVersion} in general, because as long as you've properly developed your -application with public APIs, it is always compatible with future versions of Android. If you want -to publish a different APK for higher API levels, you still do not need to specify the -maximum version, because if the {@code -android:minSdkVersion} is {@code "4"} in one APK and {@code "8"} in another, devices that -support API level 8 or higher will always receive the second APK (because it's version code is -higher, as per the previous note).
      • -
      -
      -
    • -
    - -

    Other manifest elements that enable Google Play filters—but are not -listed above—are still applied for each APK as usual. However, Google Play does not allow -you to publish multiple APKs based on variations of them. Thus, you cannot publish -multiple APKs if the above listed filters are the same for each APK (but the APKs differ based on -other characteristics in the manifest file). For -example, you cannot provide different APKs that differ purely on the {@code -<uses-configuration>} characteristics.

    - - - -

    Rules for multiple APKs

    - -

    Before you enable advanced mode to publish multiple APKs for your application, you need to -understand the following rules that define how publishing multiple APKs works:

    - -
      -
    • All APKs you publish for the same application must have the same package -name and be signed with the same certificate key.
    • - -
    • Each APK must have a different version code, specified by the -{@code -android:versionCode} attribute.
    • - -
    • Each APK must not exactly match the configuration support of another APK. -

      That is, each APK must declare slightly different support for at least one of -the supported Google Play filters (listed above).

      -

      Usually, you will differentiate your APKs based on a specific characteristic (such as the -supported texture compression formats), and thus, each APK will declare support for different -devices. However, it's OK to publish multiple APKs that overlap their support slightly. When two -APKs do overlap (they support some of the same device configurations), a device that falls within -that overlap range will receive the APK with a higher version code (defined by {@code -android:versionCode}).

    • - -
    • You cannot activate a new APK that has a version code lower than that of the APK it's -replacing. For example, say you have an active APK for screen sizes small - normal with version code -0400, then try to replace it with an APK for the same screen sizes with version code 0300. This -raises an error, because it means users of the previous APK will not be able to update the -application.
    • - -
    • An APK that requires a higher API level must have a higher -version code. -

      This is true only when either: the APKs differ based only on the -supported API levels (no other supported filters -distinguish the APKs from each other) or when the APKs do use another supported filter, but -there is an overlap between the APKs within that filter.

      -

      This is important because a user's device receives an application update from -Google Play only if the version code for the APK on Google Play is higher than the version -code of the APK currently on the device. This ensures that if a device receives a system update that -then qualifies it to install the APK for higher API levels, the device receives an application -update because the version code increases.

      -

      Note: The size of the version code increase is irrelevant; it -simply needs to be larger in the version that supports higher API levels.

      -

      Here are some examples:

      -
        -
      • If an APK you've uploaded for API levels 4 and above (Android 1.6+) has a version code of -{@code 0400}, then an APK for API levels 8 and above (Android 2.2+) must be {@code 0401} or -greater. In this case, the API level is the only supported filter used, so the version codes -must increase in correlation with the API level support for each APK, so that users -get an update when they receive a system update.
      • -
      • If you have one APK that's for API level 4 (and above) and small - -large screens, and another APK for API level 8 (and above) and large - xlarge screens, then -the version codes must increase. In this case, the API level filter is used to -distinguish each APK, but so is the screen size. Because the screen sizes overlap (both APKs -support large screens), the version codes must still be in order. This ensures that a large screen -device that receives a system update to API level 8 will receive an update for the second -APK.
      • -
      • If you have one APK that's for API level 4 (and above) and small - -normal screens, and another APK for API level 8 (and above) and large - xlarge -screens, then the version codes do not need to increase in correlation with the API -levels. Because there is no overlap within the screen size filter, there are no devices that -could potentially move between these two APKs, so there's no need for the version codes to -increase from the lower API level to the higher API level.
      • -
      -
    • - -
    - -

    Failure to abide by the above rules results in an error on the Google Play publisher site -when you activate your APKs—you will be unable to publish your application until you -resolve the error.

    - -

    There are other conflicts that might occur when you activate your APKs, but which will result -in warnings rather than errors. Warnings can be caused by the following:

    - -
      -
    • When you modify an APK to "shrink" the support for a device's characteristics and no other -APKs support the devices that then fall outside the supported range. For example, if an APK -currently supports small and normal size screens and you change it to support only small screens, -then you have shrunk the pool of supported devices and some devices will no longer see your -application on Google Play. You can resolve this by adding another APK that supports normal size -screens so that all previously-supported devices are still supported.
    • - -
    • When there are "overlaps" between two or more APKs. For example, if an APK supports screen -sizes small, normal, and large, while another APK supports sizes large and xlarge, there is an -overlap, because both APKs support large screens. If you do not resolve this, then devices that -qualify for both APKs (large screen devices in the example) will receive whichever APK has the -highest version code.
    • -
    - -

    When such conflicts occur, you will see a warning message, but you can still publish your -application.

    - - - -

    Creating Multiple APKs

    - -

    Once you decide to publish multiple APKs, you probably need to create separate -Android projects for each APK you intend to publish so that you can appropriately develop them -separately. You can do this by simply duplicating your existing project and give it a new name. -(Alternatively, you might use a build system that can output different resources—such -as textures—based on the build configuration.)

    - -

    Tip: One way to avoid duplicating large portions of your -application code is to use a library project. A library -project holds shared code and resources, which you can include in your actual application -projects.

    - -

    When creating multiple projects for the same application, it's a good practice to identify each -one with a name that indicates the device restrictions to be placed on the APK, so you can -easily identify them. For example, "HelloWorld_8" might be a good name for an -application designed for API level 8 and above.

    - -

    Note: All APKs you publish for the same application -must have the same package name and be signed with the same certificate key. Be -sure you also understand each of the Rules for multiple APKs.

    - - -

    Assigning version codes

    - -

    Each APK for the same application must have a unique version code, specified by -the {@code -android:versionCode} attribute. You must be careful about assigning version codes when -publishing multiple APKs, because they must each be different, but in some -cases, must or should be defined in a specific order, based on the configurations that each APK -supports.

    - -

    Ordering version codes

    - -

    An APK that requires a higher API level must usually have a higher version code. For example, if -you create two APKs to support different API levels, the APK for the higher API levels must have the -higher version code. This ensures that if a device receives a system update that then qualifies it -to install the APK for higher API levels, the user receives a notification to update the app. For -more information about how this requirement applies, see the section above about Rules for multiple APKs.

    - -

    You should also consider how the order of version codes might affect which APK your users -receive either due to overlap between coverage of different APKs or future changes you might make to -your APKs.

    - -

    For example, if you have different APKs based on screen size, such as one for small - normal and -one for large - xlarge, but foresee a time when you will change the APKs to be one for small and one -for normal - xlarge, then you should make the version code for the large - xlarge APK be higher. -That way, a normal size device will receive the appropriate update when you make the change, because -the version code increases from the existing APK to the new APK that now supports the device.

    - -

    Also, when creating multiple APKs that differ based on support for different OpenGL texture -compression formats, be aware that many devices support multiple formats. Because a device -receives the APK with the highest version code when there is an overlap in coverage between two -APKs, you should order the version codes among your APKs so that the APK with the -preferred compression format has the highest version code. For example, you might want to perform -separate builds for your app using PVRTC, ATITC, and ETC1 compression formats. If you prefer these -formats in this exact order, then the APK that uses PVRTC should have the highest version code, the -APK that uses ATITC has a lower version code, and the version with ETC1 has the lowest. Thus, if a -device supports both PVRTC and ETC1, it receives the APK with PVRTC, because it has the highest -version code.

    - - -

    Using a version code scheme

    - -

    In order to allow different APKs to update their version codes independent of others (for -example, when you fix a bug in only one APK, so don't need to update all APKs), you should use a -scheme for your version codes that -provides sufficient room between each APK so that you can increase the code in one without requiring -an increase in others. You should also include your actual version name in the code (that is, the -user visible version assigned to {@code android:versionName}), -so that it's easy for you to associate the version code and version name.

    - -

    Note: When you increase the version code for an APK, Google -Play will prompt users of the previous version to update the application. Thus, to avoid -unnecessary updates, you should not increase the version code for APKs that do not actually -include changes.

    - -

    We suggest using a version code with at least 7 digits: integers that represent -the supported configurations are in the higher order bits, and the version name (from {@code -android:versionName}) is in the lower order bits. For example, when the application version -name is 3.1.0, version codes for an API level 4 -APK and an API level 11 APK would be something like 0400310 and 1100310, respectively. The first -two digits are reserved for the API Level (4 and 11, respectively), the middle two digits are for -either screen sizes or GL texture formats (not used in these examples), and the last three digits -are for the application's version name (3.1.0). Figure 1 shows two examples that split based on both -the platform version (API Level) and screen size.

    - - -

    Figure 1. A suggested scheme for your version codes, -using the first two digits for the API Level, the second and third digits for the minimum and -maximum screen size (1 - 4 indicating each of the four sizes) or to denote the texture formats -and the last three digits for the app version.

    - -

    This scheme for version codes is just a suggestion for how you should establish a -pattern that is scalable as your application evolves. In particular, this scheme doesn't -demonstrate a solution for identifying different texture compression formats. One option might be -to define your own table that specifies a different integer to each of the different -compression formats your application supports (for example, 1 might correspond to ETC1 and 2 is -ATITC, and so on).

    - -

    You can use any scheme you want, but you should carefully consider how future versions of your -application will need to increase their version codes and how devices can receive updates when -either the device configuration changes (for example, due to a system update) or when you modify the -configuration support for one or several of the APKs.

    - - - - -

    Using a Single APK Instead

    - -

    Creating multiple APKs for your application is not the normal procedure for -publishing an application on Google Play. In most cases, you should be able to publish your -application to most users with a single APK and we encourage that you do so. When you encounter -a situation in which using a single APK becomes difficult, you should carefully consider all your -options before deciding to publish multiple APKs.

    - -

    First of all, there are a few key benefits to developing a single APK that supports all -devices:

    - -
      -
    • Publishing and managing your application is easier. -

      With only one APK to worry about at any given time, you're less likely to become confused by -which APK is what. You also don't have to keep track of multiple version codes for each -APK—by using only one APK, you can simply increase the version code with each release and -be done.

    • -
    • You need to manage only a single code base. -

      Although you can use a library project -to share code between multiple Android projects, it's still likely that you'll reproduce some code -across each project and this could become difficult to manage, especially when resolving -bugs.

    • -
    • Your application can adapt to device configuration changes. -

      By creating a single APK that contains all the resources for each device configuration, your -application can adapt to configuration changes that occur at runtime. For example, if the user docks -or otherwise connects a handset device to a larger screen, there's a chance that this will invoke a -system configuration change to support the larger screen. If you include all resources for different -screen configurations in the same APK, then your application will load alternative resources and -optimize the user experience for the new interface.

      -
    • -
    • App restore across devices just works. -

      If a user has enabled data backup on his or her current device and then buys a new device -that has a different configuration, then when the user's apps are automatically restored during -setup, the user receives your application and it runs using the resources optimized for that device. -For example, on a new tablet, the user receives your application and it runs with your -tablet-optimized resources. This restore -process does not work across different APKs, because each APK can potentially have different -permissions that the user has not agreed to, so Google Play may not restore the application at -all. (If you use multiple APKs, the user receives either the exact same APK if it's compatible or -nothing at all and must manually download your application to get the APK designed for the new -device.)

    • -
    - -

    The following sections describe some of the other options you should use to support multiple -device configurations before deciding to publish multiple APKs.

    - - - -

    Supporting multiple GL textures

    - -

    To support multiple types of GL textures with a single APK, your application should query the GL -texture formats supported on the device and then use the appropriate resources or download -them from a web server. For example, in order to keep the size of your APK small, you can query the -device's support for different GL texture formats when the application starts for the first time and -then download only the textures you need for that device.

    - -

    For maximum performance and compatibility, your application should use ETC1 textures wherever it -doesn't impact the visual quality. However, because ETC1 cannot deal with images that have drastic -chroma changes, such as line art and (most) text, and doesn't support alpha, it may not the best -format for all textures.

    - -

    With a single APK, you should try to use ETC1 textures and uncompressed textures whenever -reasonable, and consider the use of PVRTC, ATITC, or DXTC as a last resort when ETC1 does not -suffice.

    - -

    Here's an example query for supported texture compression formats from inside a -{@link android.opengl.GLSurfaceView.Renderer GLSurfaceView.Renderer}:

    - -
    -public void onSurfaceChanged(GL10 gl, int w, int h) {
    -    String extensions = gl.glGetString(GL10.GL_EXTENSIONS);
    -    Log.d("ExampleActivity", extensions);
    -}
    -
    - -

    This returns a string that lists each of the supported compression formats.

    - - - -

    Supporting multiple screens

    - -

    Unless your APK file exceeds the Google Play size limit of 50MB, supporting multiple screens -should always be done with a single APK. Since Android 1.6, the Android system manages most of the -work required for your application to run successfully on a variety of screen sizes and -densities.

    - -

    To further optimize your application for different screen sizes and densities, you should provide -alternative -resources such as bitmap drawables at different resolutions and different layout designs for -different screen sizes.

    - -

    For more information about how to support multiple screens with a single APK, read Supporting Multiple Screens.

    - -

    Additionally, you should consider using a support library from the Compatibility Package so that you can add Fragments to your activity designs -when running on larger screens such as tablets.

    - - - -

    Supporting multiple API levels

    - -

    If you want to support as many versions of the Android platform as possible, you should use -only APIs available in the lowest reasonable version. For example, your application may not require -APIs newer than Android 2.1 (API Level 7), which makes an application available to -over 95% of Android-powered devices (as indicated by the Platform Versions dashboard).

    - -

    By using a support library from the Compatibility Package, you can also use APIs -from some of the latest versions (such as Android 3.0) while -still supporting versions as low as Android 1.6. The support library includes APIs for Fragments, Loaders, and more. Using the fragment -APIs is particularly valuable so that you can optimize your user interface for large devices such as -tablets.

    - -

    Alternatively, if you want to use some APIs that are available only in newer versions of Android -(which your application can still function without), then you should consider using reflection. By -using reflection, you can check whether the current device supports certain APIs. If the APIs are -not available, your application can gracefully disable and hide the feature.

    - -

    Another way to use new APIs only when running on a version that supports them is to check the -API level of the current device. That is, you can query the value of {@link -android.os.Build.VERSION#SDK_INT} and create different code paths depending on the API level -supported by the device. For example:

    - -
    -if (android.os.Build.VERSION.SDK_INT >= 11) {
    -    // Use APIs supported by API level 11 (Android 3.0) and up
    -} else {
    -    // Do something different to support older versions
    -}
    -
    - diff --git a/docs/html/guide/practices/app-design/accessibility.html b/docs/html/guide/practices/app-design/accessibility.html new file mode 100644 index 000000000000..0fa7b3213dd9 --- /dev/null +++ b/docs/html/guide/practices/app-design/accessibility.html @@ -0,0 +1,11 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/guide/practices/app-design/index.jd b/docs/html/guide/practices/app-design/index.jd new file mode 100644 index 000000000000..a818831e43e7 --- /dev/null +++ b/docs/html/guide/practices/app-design/index.jd @@ -0,0 +1,21 @@ +page.title=Application Design Goals +@jd:body + +

    When learning how to build applications on a new platform, you first learn what APIs are available and how to use them. Later, you learn the nuances of the platform. Put another way: first you learn how you can build applications; later, you learn how you should build them, to ensure that your applications offer outstanding performance and a great user experience.

    + +

    The documents below help you learn the nuances of Android and get started building great applications more quickly, They discuss important aspects of application design that directly influence the user experience of your application, when in the hands of a mobile device user. You should read and consider these design goals as you plan your application and throughout its development, especially if you are new to developing for mobile devices.

    + +

    Successful mobile applications offer an outstanding user experience, in addition to a compelling technical feature set. The user experience is more than just its visual design or UI flow. It is also influenced by how well the application responds to the user's keypresses and other actions, how it well it interacts with other applications, and how fully and efficiently it uses device and system capabilities.

    + +

    An outstanding user experience has three key characteristics: it is +fast; it is responsive; and it is seamless. Of course +every platform since the dawn of computing has probably cited those same three +qualities at one time or another. However, each platform achieves them in +different ways; the documents below explain how you can build Android +applications that are fast, responsive, and seamless.

    + + diff --git a/docs/html/guide/practices/app-design/jni.jd b/docs/html/guide/practices/app-design/jni.jd new file mode 100644 index 000000000000..ddfa0e3991f5 --- /dev/null +++ b/docs/html/guide/practices/app-design/jni.jd @@ -0,0 +1,719 @@ +page.title=JNI Tips +@jd:body + + + +

    JNI is the Java Native Interface. It defines a way for managed code +(written in the Java programming language) to interact with native +code (written in C/C++). It's vendor-neutral, has support for loading code from +dynamic shared libraries, and while cumbersome at times is reasonably efficient.

    + +

    You really should read through the +JNI spec for J2SE 6 +to get a sense for how JNI works and what features are available. Some +aspects of the interface aren't immediately obvious on +first reading, so you may find the next few sections handy. +There's a more detailed JNI Programmer's Guide and Specification.

    + + + +

    JavaVM and JNIEnv

    + +

    JNI defines two key data structures, "JavaVM" and "JNIEnv". Both of these are essentially +pointers to pointers to function tables. (In the C++ version, they're classes with a +pointer to a function table and a member function for each JNI function that indirects through +the table.) The JavaVM provides the "invocation interface" functions, +which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, +but Android only allows one.

    + +

    The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as +the first argument.

    + +

    The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. +If a piece of code has no other way to get its JNIEnv, you should share +the JavaVM, and use GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)

    + +

    The C declarations of JNIEnv and JavaVM are different from the C++ +declarations. The "jni.h" include file provides different typedefs +depending on whether it's included into C or C++. For this reason it's a bad idea to +include JNIEnv arguments in header files included by both languages. (Put another way: if your +header file requires #ifdef __cplusplus, you may have to do some extra work if anything in +that header refers to JNIEnv.)

    + + +

    Threads

    + +

    All threads are Linux threads, scheduled by the kernel. They're usually +started from managed code (using Thread.start), +but they can also be created elsewhere and then attached to the JavaVM. For +example, a thread started with pthread_create can be attached +with the JNI AttachCurrentThread or +AttachCurrentThreadAsDaemon functions. Until a thread is +attached, it has no JNIEnv, and cannot make JNI calls.

    + +

    Attaching a natively-created thread causes a java.lang.Thread +object to be constructed and added to the "main" ThreadGroup, +making it visible to the debugger. Calling AttachCurrentThread +on an already-attached thread is a no-op.

    + +

    Android does not suspend threads executing native code. If +garbage collection is in progress, or the debugger has issued a suspend +request, Android will pause the thread the next time it makes a JNI call.

    + +

    Threads attached through JNI must call +DetachCurrentThread before they exit. +If coding this directly is awkward, in Android 2.0 (Eclair) and higher you +can use pthread_key_create to define a destructor +function that will be called before the thread exits, and +call DetachCurrentThread from there. (Use that +key with pthread_setspecific to store the JNIEnv in +thread-local-storage; that way it'll be passed into your destructor as +the argument.)

    + + + +

    jclass, jmethodID, and jfieldID

    + +

    If you want to access an object's field from native code, you would do the following:

    + +
      +
    • Get the class object reference for the class with FindClass
    • +
    • Get the field ID for the field with GetFieldID
    • +
    • Get the contents of the field with something appropriate, such as +GetIntField
    • +
    + +

    Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just +pointers to internal runtime data structures. Looking them up may require several string +comparisons, but once you have them the actual call to get the field or invoke the method +is very quick.

    + +

    If performance is important, it's useful to look the values up once and cache the results +in your native code. Because there is a limit of one JavaVM per process, it's reasonable +to store this data in a static local structure.

    + +

    The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes +are only unloaded if all classes associated with a ClassLoader can be garbage collected, +which is rare but will not be impossible in Android. Note however that +the jclass +is a class reference and must be protected with a call +to NewGlobalRef (see the next section).

    + +

    If you would like to cache the IDs when a class is loaded, and automatically re-cache them +if the class is ever unloaded and reloaded, the correct way to initialize +the IDs is to add a piece of code that looks like this to the appropriate class:

    + +
        /*
    +     * We use a class initializer to allow the native code to cache some
    +     * field offsets. This native function looks up and caches interesting
    +     * class/field/method IDs. Throws on failure.
    +     */
    +    private static native void nativeInit();
    +
    +    static {
    +        nativeInit();
    +    }
    + +

    Create a nativeClassInit method in your C/C++ code that performs the ID lookups. The code +will be executed once, when the class is initialized. If the class is ever unloaded and +then reloaded, it will be executed again.

    + + +

    Local and Global References

    + +

    Every argument passed to a native method, and almost every object returned +by a JNI function is a "local reference". This means that it's valid for the +duration of the current native method in the current thread. +Even if the object itself continues to live on after the native method +returns, the reference is not valid. +

    This applies to all sub-classes of jobject, including +jclass, jstring, and jarray. +(The runtime will warn you about most reference mis-uses when extended JNI +checks are enabled.)

    +

    The only way to get non-local references is via the functions +NewGlobalRef and NewWeakGlobalRef. + +

    If you want to hold on to a reference for a longer period, you must use +a "global" reference. The NewGlobalRef function takes the +local reference as an argument and returns a global one. +The global reference is guaranteed to be valid until you call +DeleteGlobalRef.

    + +

    This pattern is commonly used when caching a jclass returned +from FindClass, e.g.:

    +
    jclass localClass = env->FindClass("MyClass");
    +jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
    + +

    All JNI methods accept both local and global references as arguments. +It's possible for references to the same object to have different values. +For example, the return values from consecutive calls to +NewGlobalRef on the same object may be different. +To see if two references refer to the same object, +you must use the IsSameObject function. Never compare +references with == in native code.

    + +

    One consequence of this is that you +must not assume object references are constant or unique +in native code. The 32-bit value representing an object may be different +from one invocation of a method to the next, and it's possible that two +different objects could have the same 32-bit value on consecutive calls. Do +not use jobject values as keys.

    + +

    Programmers are required to "not excessively allocate" local references. In practical terms this means +that if you're creating large numbers of local references, perhaps while running through an array of +objects, you should free them manually with +DeleteLocalRef instead of letting JNI do it for you. The +implementation is only required to reserve slots for +16 local references, so if you need more than that you should either delete as you go or use +EnsureLocalCapacity/PushLocalFrame to reserve more.

    + +

    Note that jfieldIDs and jmethodIDs are opaque +types, not object references, and should not be passed to +NewGlobalRef. The raw data +pointers returned by functions like GetStringUTFChars +and GetByteArrayElements are also not objects. (They may be passed +between threads, and are valid until the matching Release call.)

    + +

    One unusual case deserves separate mention. If you attach a native +thread with AttachCurrentThread, the code you are running will +never automatically free local references until the thread detaches. Any local +references you create will have to be deleted manually. In general, any native +code that creates local references in a loop probably needs to do some manual +deletion.

    + + +

    UTF-8 and UTF-16 Strings

    + +

    The Java programming language uses UTF-16. For convenience, JNI provides methods that work with Modified UTF-8 as well. The +modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00. +The nice thing about this is that you can count on having C-style zero-terminated strings, +suitable for use with standard libc string functions. The down side is that you cannot pass +arbitrary UTF-8 data to JNI and expect it to work correctly.

    + +

    If possible, it's usually faster to operate with UTF-16 strings. Android +currently does not require a copy in GetStringChars, whereas +GetStringUTFChars requires an allocation and a conversion to +UTF-8. Note that +UTF-16 strings are not zero-terminated, and \u0000 is allowed, +so you need to hang on to the string length as well as +the jchar pointer.

    + +

    Don't forget to Release the strings you Get. The +string functions return jchar* or jbyte*, which +are C-style pointers to primitive data rather than local references. They +are guaranteed valid until Release is called, which means they are not +released when the native method returns.

    + +

    Data passed to NewStringUTF must be in Modified UTF-8 format. A +common mistake is reading character data from a file or network stream +and handing it to NewStringUTF without filtering it. +Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII +characters or convert them to proper Modified UTF-8 form. If you don't, +the UTF-16 conversion will likely not be what you expect. The extended +JNI checks will scan strings and warn you about invalid data, but they +won't catch everything.

    + + +

    Primitive Arrays

    + +

    JNI provides functions for accessing the contents of array objects. +While arrays of objects must be accessed one entry at a time, arrays of +primitives can be read and written directly as if they were declared in C.

    + +

    To make the interface as efficient as possible without constraining +the VM implementation, the Get<PrimitiveType>ArrayElements +family of calls allows the runtime to either return a pointer to the actual elements, or +allocate some memory and make a copy. Either way, the raw pointer returned +is guaranteed to be valid until the corresponding Release call +is issued (which implies that, if the data wasn't copied, the array object +will be pinned down and can't be relocated as part of compacting the heap). +You must Release every array you Get. Also, if the Get +call fails, you must ensure that your code doesn't try to Release a NULL +pointer later.

    + +

    You can determine whether or not the data was copied by passing in a +non-NULL pointer for the isCopy argument. This is rarely +useful.

    + +

    The Release call takes a mode argument that can +have one of three values. The actions performed by the runtime depend upon +whether it returned a pointer to the actual data or a copy of it:

    + +
      +
    • 0 +
        +
      • Actual: the array object is un-pinned. +
      • Copy: data is copied back. The buffer with the copy is freed. +
      +
    • JNI_COMMIT +
        +
      • Actual: does nothing. +
      • Copy: data is copied back. The buffer with the copy + is not freed. +
      +
    • JNI_ABORT +
        +
      • Actual: the array object is un-pinned. Earlier + writes are not aborted. +
      • Copy: the buffer with the copy is freed; any changes to it are lost. +
      +
    + +

    One reason for checking the isCopy flag is to know if +you need to call Release with JNI_COMMIT +after making changes to an array — if you're alternating between making +changes and executing code that uses the contents of the array, you may be +able to +skip the no-op commit. Another possible reason for checking the flag is for +efficient handling of JNI_ABORT. For example, you might want +to get an array, modify it in place, pass pieces to other functions, and +then discard the changes. If you know that JNI is making a new copy for +you, there's no need to create another "editable" copy. If JNI is passing +you the original, then you do need to make your own copy.

    + +

    It is a common mistake (repeated in example code) to assume that you can skip the Release call if +*isCopy is false. This is not the case. If no copy buffer was +allocated, then the original memory must be pinned down and can't be moved by +the garbage collector.

    + +

    Also note that the JNI_COMMIT flag does not release the array, +and you will need to call Release again with a different flag +eventually.

    + + + +

    Region Calls

    + +

    There is an alternative to calls like Get<Type>ArrayElements +and GetStringChars that may be very helpful when all you want +to do is copy data in or out. Consider the following:

    + +
        jbyte* data = env->GetByteArrayElements(array, NULL);
    +    if (data != NULL) {
    +        memcpy(buffer, data, len);
    +        env->ReleaseByteArrayElements(array, data, JNI_ABORT);
    +    }
    + +

    This grabs the array, copies the first len byte +elements out of it, and then releases the array. Depending upon the +implementation, the Get call will either pin or copy the array +contents. +The code copies the data (for perhaps a second time), then calls Release; in this case +JNI_ABORT ensures there's no chance of a third copy.

    + +

    One can accomplish the same thing more simply:

    +
        env->GetByteArrayRegion(array, 0, len, buffer);
    + +

    This has several advantages:

    +
      +
    • Requires one JNI call instead of 2, reducing overhead. +
    • Doesn't require pinning or extra data copies. +
    • Reduces the risk of programmer error — no risk of forgetting + to call Release after something fails. +
    + +

    Similarly, you can use the Set<Type>ArrayRegion call +to copy data into an array, and GetStringRegion or +GetStringUTFRegion to copy characters out of a +String. + + + +

    Exceptions

    + +

    You must not call most JNI functions while an exception is pending. +Your code is expected to notice the exception (via the function's return value, +ExceptionCheck, or ExceptionOccurred) and return, +or clear the exception and handle it.

    + +

    The only JNI functions that you are allowed to call while an exception is +pending are:

    +
      +
    • DeleteGlobalRef +
    • DeleteLocalRef +
    • DeleteWeakGlobalRef +
    • ExceptionCheck +
    • ExceptionClear +
    • ExceptionDescribe +
    • ExceptionOccurred +
    • MonitorExit +
    • PopLocalFrame +
    • PushLocalFrame +
    • Release<PrimitiveType>ArrayElements +
    • ReleasePrimitiveArrayCritical +
    • ReleaseStringChars +
    • ReleaseStringCritical +
    • ReleaseStringUTFChars +
    + +

    Many JNI calls can throw an exception, but often provide a simpler way +of checking for failure. For example, if NewString returns +a non-NULL value, you don't need to check for an exception. However, if +you call a method (using a function like CallObjectMethod), +you must always check for an exception, because the return value is not +going to be valid if an exception was thrown.

    + +

    Note that exceptions thrown by interpreted code do not unwind native stack +frames, and Android does not yet support C++ exceptions. +The JNI Throw and ThrowNew instructions just +set an exception pointer in the current thread. Upon returning to managed +from native code, the exception will be noted and handled appropriately.

    + +

    Native code can "catch" an exception by calling ExceptionCheck or +ExceptionOccurred, and clear it with +ExceptionClear. As usual, +discarding exceptions without handling them can lead to problems.

    + +

    There are no built-in functions for manipulating the Throwable object +itself, so if you want to (say) get the exception string you will need to +find the Throwable class, look up the method ID for +getMessage "()Ljava/lang/String;", invoke it, and if the result +is non-NULL use GetStringUTFChars to get something you can +hand to printf(3) or equivalent.

    + + + +

    Extended Checking

    + +

    JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.

    + +

    The additional checks include:

    + +
      +
    • Arrays: attempting to allocate a negative-sized array.
    • +
    • Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.
    • +
    • Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
    • +
    • Critical calls: making a JNI call between a “critical” get and its corresponding release.
    • +
    • Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
    • +
    • Exceptions: making a JNI call while there’s an exception pending.
    • +
    • JNIEnv*s: using a JNIEnv* from the wrong thread.
    • +
    • jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
    • +
    • jmethodIDs: using the wrong kind of jmethodID when making a Call*Method JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).
    • +
    • References: using DeleteGlobalRef/DeleteLocalRef on the wrong kind of reference.
    • +
    • Release modes: passing a bad release mode to a release call (something other than 0, JNI_ABORT, or JNI_COMMIT).
    • +
    • Type safety: returning an incompatible type from your native method (returning a StringBuilder from a method declared to return a String, say).
    • +
    • UTF-8: passing an invalid Modified UTF-8 byte sequence to a JNI call.
    • +
    + +

    (Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)

    + +

    There are several ways to enable CheckJNI.

    + +

    If you’re using the emulator, CheckJNI is on by default.

    + +

    If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:

    + +
    adb shell stop
    +adb shell setprop dalvik.vm.checkjni true
    +adb shell start
    + +

    In either of these cases, you’ll see something like this in your logcat output when the runtime starts:

    + +
    D AndroidRuntime: CheckJNI is ON
    + +

    If you have a regular device, you can use the following command:

    + +
    adb shell setprop debug.checkjni 1
    + +

    This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Change the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time an app starts:

    + +
    D Late-enabling CheckJNI
    + + + + + +

    Native Libraries

    + +

    You can load native code from shared libraries with the standard +System.loadLibrary call. The +preferred way to get at your native code is:

    + +
      +
    • Call System.loadLibrary from a static class +initializer. (See the earlier example, where one is used to call +nativeClassInit.) The argument is the "undecorated" +library name, so to load "libfubar.so" you would pass in "fubar".
    • +
    • Provide a native function: jint JNI_OnLoad(JavaVM* vm, void* reserved)
    • +
    • In JNI_OnLoad, register all of your native methods. You +should declare +the methods "static" so the names don't take up space in the symbol table +on the device.
    • +
    + +

    The JNI_OnLoad function should look something like this if +written in C++:

    +
    jint JNI_OnLoad(JavaVM* vm, void* reserved)
    +{
    +    JNIEnv* env;
    +    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
    +        return -1;
    +    }
    +
    +    // Get jclass with env->FindClass.
    +    // Register methods with env->RegisterNatives.
    +
    +    return JNI_VERSION_1_6;
    +}
    + +

    You can also call System.load with the full path name of the +shared library. For Android apps, you may find it useful to get the full +path to the application's private data storage area from the context object.

    + +

    This is the recommended approach, but not the only approach. Explicit +registration is not required, nor is it necessary that you provide a +JNI_OnLoad function. +You can instead use "discovery" of native methods that are named in a +specific way (see the JNI spec for details), though this is less desirable because if a method signature is wrong you won't know +about it until the first time the method is actually used.

    + +

    One other note about JNI_OnLoad: any FindClass +calls you make from there will happen in the context of the class loader +that was used to load the shared library. Normally FindClass +uses the loader associated with the method at the top of the interpreted +stack, or if there isn't one (because the thread was just attached) it uses +the "system" class loader. This makes +JNI_OnLoad a convenient place to look up and cache class +object references.

    + + + +

    64-bit Considerations

    + +

    Android is currently expected to run on 32-bit platforms. In theory it +could be built for a 64-bit system, but that is not a goal at this time. +For the most part this isn't something that you will need to worry about +when interacting with native code, +but it becomes significant if you plan to store pointers to native +structures in integer fields in an object. To support architectures +that use 64-bit pointers, you need to stash your native pointers in a +long field rather than an int. + + + +

    Unsupported Features/Backwards Compatibility

    + +

    All JNI 1.6 features are supported, with the following exception:

    +
      +
    • DefineClass is not implemented. Android does not use + Java bytecodes or class files, so passing in binary class data + doesn't work.
    • +
    + +

    For backward compatibility with older Android releases, you may need to +be aware of:

    +
      +
    • Dynamic lookup of native functions +

      Until Android 2.0 (Eclair), the '$' character was not properly + converted to "_00024" during searches for method names. Working + around this requires using explicit registration or moving the + native methods out of inner classes. +

    • Detaching threads +

      Until Android 2.0 (Eclair), it was not possible to use a pthread_key_create + destructor function to avoid the "thread must be detached before + exit" check. (The runtime also uses a pthread key destructor function, + so it'd be a race to see which gets called first.) +

    • Weak global references +

      Until Android 2.2 (Froyo), weak global references were not implemented. + Older versions will vigorously reject attempts to use them. You can use + the Android platform version constants to test for support. +

      Until Android 4.0 (Ice Cream Sandwich), weak global references could only + be passed to NewLocalRef, NewGlobalRef, and + DeleteWeakGlobalRef. (The spec strongly encourages + programmers to create hard references to weak globals before doing + anything with them, so this should not be at all limiting.) +

      From Android 4.0 (Ice Cream Sandwich) on, weak global references can be + used like any other JNI references.

    • +
    • Local references +

      Until Android 4.0 (Ice Cream Sandwich), local references were + actually direct pointers. Ice Cream Sandwich added the indirection + necessary to support better garbage collectors, but this means that lots + of JNI bugs are undetectable on older releases. See + JNI Local Reference Changes in ICS for more details. +

    • Determining reference type with GetObjectRefType +

      Until Android 4.0 (Ice Cream Sandwich), as a consequence of the use of + direct pointers (see above), it was impossible to implement + GetObjectRefType correctly. Instead we used a heuristic + that looked through the weak globals table, the arguments, the locals + table, and the globals table in that order. The first time it found your + direct pointer, it would report that your reference was of the type it + happened to be examining. This meant, for example, that if + you called GetObjectRefType on a global jclass that happened + to be the same as the jclass passed as an implicit argument to your static + native method, you'd get JNILocalRefType rather than + JNIGlobalRefType. +

    + + + +

    FAQ: Why do I get UnsatisfiedLinkError?

    + +

    When working on native code it's not uncommon to see a failure like this:

    +
    java.lang.UnsatisfiedLinkError: Library foo not found
    + +

    In some cases it means what it says — the library wasn't found. In +other cases the library exists but couldn't be opened by dlopen(3), and +the details of the failure can be found in the exception's detail message.

    + +

    Common reasons why you might encounter "library not found" exceptions:

    +
      +
    • The library doesn't exist or isn't accessible to the app. Use + adb shell ls -l <path> to check its presence + and permissions. +
    • The library wasn't built with the NDK. This can result in + dependencies on functions or libraries that don't exist on the device. +
    + +

    Another class of UnsatisfiedLinkError failures looks like:

    +
    java.lang.UnsatisfiedLinkError: myfunc
    +        at Foo.myfunc(Native Method)
    +        at Foo.main(Foo.java:10)
    + +

    In logcat, you'll see:

    +
    W/dalvikvm(  880): No implementation found for native LFoo;.myfunc ()V
    + +

    This means that the runtime tried to find a matching method but was +unsuccessful. Some common reasons for this are:

    +
      +
    • The library isn't getting loaded. Check the logcat output for + messages about library loading. +
    • The method isn't being found due to a name or signature mismatch. This + is commonly caused by: +
        +
      • For lazy method lookup, failing to declare C++ functions + with extern "C" and appropriate + visibility (JNIEXPORT). Note that prior to Ice Cream + Sandwich, the JNIEXPORT macro was incorrect, so using a new GCC with + an old jni.h won't work. + You can use arm-eabi-nm + to see the symbols as they appear in the library; if they look + mangled (something like _Z15Java_Foo_myfuncP7_JNIEnvP7_jclass + rather than Java_Foo_myfunc), or if the symbol type is + a lowercase 't' rather than an uppercase 'T', then you need to + adjust the declaration. +
      • For explicit registration, minor errors when entering the + method signature. Make sure that what you're passing to the + registration call matches the signature in the log file. + Remember that 'B' is byte and 'Z' is boolean. + Class name components in signatures start with 'L', end with ';', + use '/' to separate package/class names, and use '$' to separate + inner-class names (Ljava/util/Map$Entry;, say). +
      +
    + +

    Using javah to automatically generate JNI headers may help +avoid some problems. + + + +

    FAQ: Why didn't FindClass find my class?

    + +

    Make sure that the class name string has the correct format. JNI class +names start with the package name and are separated with slashes, +such as java/lang/String. If you're looking up an array class, +you need to start with the appropriate number of square brackets and +must also wrap the class with 'L' and ';', so a one-dimensional array of +String would be [Ljava/lang/String;.

    + +

    If the class name looks right, you could be running into a class loader +issue. FindClass wants to start the class search in the +class loader associated with your code. It examines the call stack, +which will look something like: +

        Foo.myfunc(Native Method)
    +    Foo.main(Foo.java:10)
    +    dalvik.system.NativeStart.main(Native Method)
    + +

    The topmost method is Foo.myfunc. FindClass +finds the ClassLoader object associated with the Foo +class and uses that.

    + +

    This usually does what you want. You can get into trouble if you +create a thread yourself (perhaps by calling pthread_create +and then attaching it with AttachCurrentThread). +Now the stack trace looks like this:

    +
        dalvik.system.NativeStart.run(Native Method)
    + +

    The topmost method is NativeStart.run, which isn't part of +your application. If you call FindClass from this thread, the +JavaVM will start in the "system" class loader instead of the one associated +with your application, so attempts to find app-specific classes will fail.

    + +

    There are a few ways to work around this:

    +
      +
    • Do your FindClass lookups once, in + JNI_OnLoad, and cache the class references for later + use. Any FindClass calls made as part of executing + JNI_OnLoad will use the class loader associated with + the function that called System.loadLibrary (this is a + special rule, provided to make library initialization more convenient). + If your app code is loading the library, FindClass + will use the correct class loader. +
    • Pass an instance of the class into the functions that need + it, by declaring your native method to take a Class argument and + then passing Foo.class in. +
    • Cache a reference to the ClassLoader object somewhere + handy, and issue loadClass calls directly. This requires + some effort. +
    + + + +

    FAQ: How do I share raw data with native code?

    + +

    You may find yourself in a situation where you need to access a large +buffer of raw data from both managed and native code. Common examples +include manipulation of bitmaps or sound samples. There are two +basic approaches.

    + +

    You can store the data in a byte[]. This allows very fast +access from managed code. On the native side, however, you're +not guaranteed to be able to access the data without having to copy it. In +some implementations, GetByteArrayElements and +GetPrimitiveArrayCritical will return actual pointers to the +raw data in the managed heap, but in others it will allocate a buffer +on the native heap and copy the data over.

    + +

    The alternative is to store the data in a direct byte buffer. These +can be created with java.nio.ByteBuffer.allocateDirect, or +the JNI NewDirectByteBuffer function. Unlike regular +byte buffers, the storage is not allocated on the managed heap, and can +always be accessed directly from native code (get the address +with GetDirectBufferAddress). Depending on how direct +byte buffer access is implemented, accessing the data from managed code +can be very slow.

    + +

    The choice of which to use depends on two factors:

    +
      +
    1. Will most of the data accesses happen from code written in Java + or in C/C++? +
    2. If the data is eventually being passed to a system API, what form + must it be in? (For example, if the data is eventually passed to a + function that takes a byte[], doing processing in a direct + ByteBuffer might be unwise.) +
    + +

    If there's no clear winner, use a direct byte buffer. Support for them +is built directly into JNI, and performance should improve in future releases.

    diff --git a/docs/html/guide/practices/app-design/performance.jd b/docs/html/guide/practices/app-design/performance.jd new file mode 100644 index 000000000000..078999becc39 --- /dev/null +++ b/docs/html/guide/practices/app-design/performance.jd @@ -0,0 +1,410 @@ +page.title=Designing for Performance +@jd:body + + + +

    An Android application will run on a mobile device with limited computing +power and storage, and constrained battery life. Because of +this, it should be efficient. Battery life is one reason you might +want to optimize your app even if it already seems to run "fast enough". +Battery life is important to users, and Android's battery usage breakdown +means users will know if your app is responsible draining their battery.

    + +

    Note that although this document primarily covers micro-optimizations, +these will almost never make or break your software. Choosing the right +algorithms and data structures should always be your priority, but is +outside the scope of this document.

    + + +

    Introduction

    + +

    There are two basic rules for writing efficient code:

    +
      +
    • Don't do work that you don't need to do.
    • +
    • Don't allocate memory if you can avoid it.
    • +
    + +

    Optimize Judiciously

    + +

    This document is about Android-specific micro-optimization, so it assumes +that you've already used profiling to work out exactly what code needs to be +optimized, and that you already have a way to measure the effect (good or bad) +of any changes you make. You only have so much engineering time to invest, so +it's important to know you're spending it wisely. + +

    (See Closing Notes for more on profiling and +writing effective benchmarks.) + +

    This document also assumes that you made the best decisions about data +structures and algorithms, and that you've also considered the future +performance consequences of your API decisions. Using the right data +structures and algorithms will make more difference than any of the advice +here, and considering the performance consequences of your API decisions will +make it easier to switch to better implementations later (this is more +important for library code than for application code). + +

    (If you need that kind of advice, see Josh Bloch's Effective Java, +item 47.)

    + +

    One of the trickiest problems you'll face when micro-optimizing an Android +app is that your app is pretty much guaranteed to be running on multiple +hardware platforms. Different versions of the VM running on different +processors running at different speeds. It's not even generally the case +that you can simply say "device X is a factor F faster/slower than device Y", +and scale your results from one device to others. In particular, measurement +on the emulator tells you very little about performance on any device. There +are also huge differences between devices with and without a JIT: the "best" +code for a device with a JIT is not always the best code for a device +without.

    + +

    If you want to know how your app performs on a given device, you need to +test on that device.

    + + +

    Avoid Creating Unnecessary Objects

    + +

    Object creation is never free. A generational GC with per-thread allocation +pools for temporary objects can make allocation cheaper, but allocating memory +is always more expensive than not allocating memory.

    + +

    If you allocate objects in a user interface loop, you will force a periodic +garbage collection, creating little "hiccups" in the user experience. The +concurrent collector introduced in Gingerbread helps, but unnecessary work +should always be avoided.

    + +

    Thus, you should avoid creating object instances you don't need to. Some +examples of things that can help:

    + +
      +
    • If you have a method returning a string, and you know that its result + will always be appended to a StringBuffer anyway, change your signature + and implementation so that the function does the append directly, + instead of creating a short-lived temporary object.
    • +
    • When extracting strings from a set of input data, try + to return a substring of the original data, instead of creating a copy. + You will create a new String object, but it will share the char[] + with the data. (The trade-off being that if you're only using a small + part of the original input, you'll be keeping it all around in memory + anyway if you go this route.)
    • +
    + +

    A somewhat more radical idea is to slice up multidimensional arrays into +parallel single one-dimension arrays:

    + +
      +
    • An array of ints is a much better than an array of Integers, + but this also generalizes to the fact that two parallel arrays of ints + are also a lot more efficient than an array of (int,int) + objects. The same goes for any combination of primitive types.
    • +
    • If you need to implement a container that stores tuples of (Foo,Bar) + objects, try to remember that two parallel Foo[] and Bar[] arrays are + generally much better than a single array of custom (Foo,Bar) objects. + (The exception to this, of course, is when you're designing an API for + other code to access; in those cases, it's usually better to trade + good API design for a small hit in speed. But in your own internal + code, you should try and be as efficient as possible.)
    • +
    + +

    Generally speaking, avoid creating short-term temporary objects if you +can. Fewer objects created mean less-frequent garbage collection, which has +a direct impact on user experience.

    + + + +

    Performance Myths

    + +

    Previous versions of this document made various misleading claims. We +address some of them here.

    + +

    On devices without a JIT, it is true that invoking methods via a +variable with an exact type rather than an interface is slightly more +efficient. (So, for example, it was cheaper to invoke methods on a +HashMap map than a Map map, even though in both +cases the map was a HashMap.) It was not the case that this +was 2x slower; the actual difference was more like 6% slower. Furthermore, +the JIT makes the two effectively indistinguishable.

    + +

    On devices without a JIT, caching field accesses is about 20% faster than +repeatedly accesssing the field. With a JIT, field access costs about the same +as local access, so this isn't a worthwhile optimization unless you feel it +makes your code easier to read. (This is true of final, static, and static +final fields too.) + + +

    Prefer Static Over Virtual

    + +

    If you don't need to access an object's fields, make your method static. +Invocations will be about 15%-20% faster. +It's also good practice, because you can tell from the method +signature that calling the method can't alter the object's state.

    + + +

    Avoid Internal Getters/Setters

    + +

    In native languages like C++ it's common practice to use getters (e.g. +i = getCount()) instead of accessing the field directly (i += mCount). This is an excellent habit for C++, because the compiler can +usually inline the access, and if you need to restrict or debug field access +you can add the code at any time.

    + +

    On Android, this is a bad idea. Virtual method calls are expensive, +much more so than instance field lookups. It's reasonable to follow +common object-oriented programming practices and have getters and setters +in the public interface, but within a class you should always access +fields directly.

    + +

    Without a JIT, direct field access is about 3x faster than invoking a +trivial getter. With the JIT (where direct field access is as cheap as +accessing a local), direct field access is about 7x faster than invoking a +trivial getter. This is true in Froyo, but will improve in the future when +the JIT inlines getter methods.

    + +

    Note that if you're using ProGuard, you can have the best +of both worlds because ProGuard can inline accessors for you.

    + + +

    Use Static Final For Constants

    + +

    Consider the following declaration at the top of a class:

    + +
    static int intVal = 42;
    +static String strVal = "Hello, world!";
    + +

    The compiler generates a class initializer method, called +<clinit>, that is executed when the class is first used. +The method stores the value 42 into intVal, and extracts a +reference from the classfile string constant table for strVal. +When these values are referenced later on, they are accessed with field +lookups.

    + +

    We can improve matters with the "final" keyword:

    + +
    static final int intVal = 42;
    +static final String strVal = "Hello, world!";
    + +

    The class no longer requires a <clinit> method, +because the constants go into static field initializers in the dex file. +Code that refers to intVal will use +the integer value 42 directly, and accesses to strVal will +use a relatively inexpensive "string constant" instruction instead of a +field lookup. (Note that this optimization only applies to primitive types and +String constants, not arbitrary reference types. Still, it's good +practice to declare constants static final whenever possible.)

    + + +

    Use Enhanced For Loop Syntax

    + +

    The enhanced for loop (also sometimes known as "for-each" loop) can be used +for collections that implement the Iterable interface and for arrays. +With collections, an iterator is allocated to make interface calls +to hasNext() and next(). With an ArrayList, a hand-written counted loop is +about 3x faster (with or without JIT), but for other collections the enhanced +for loop syntax will be exactly equivalent to explicit iterator usage.

    + +

    There are several alternatives for iterating through an array:

    + +
        static class Foo {
    +        int mSplat;
    +    }
    +    Foo[] mArray = ...
    +
    +    public void zero() {
    +        int sum = 0;
    +        for (int i = 0; i < mArray.length; ++i) {
    +            sum += mArray[i].mSplat;
    +        }
    +    }
    +
    +    public void one() {
    +        int sum = 0;
    +        Foo[] localArray = mArray;
    +        int len = localArray.length;
    +
    +        for (int i = 0; i < len; ++i) {
    +            sum += localArray[i].mSplat;
    +        }
    +    }
    +
    +    public void two() {
    +        int sum = 0;
    +        for (Foo a : mArray) {
    +            sum += a.mSplat;
    +        }
    +    }
    +
    + +

    zero() is slowest, because the JIT can't yet optimize away +the cost of getting the array length once for every iteration through the +loop.

    + +

    one() is faster. It pulls everything out into local +variables, avoiding the lookups. Only the array length offers a performance +benefit.

    + +

    two() is fastest for devices without a JIT, and +indistinguishable from one() for devices with a JIT. +It uses the enhanced for loop syntax introduced in version 1.5 of the Java +programming language.

    + +

    To summarize: use the enhanced for loop by default, but consider a +hand-written counted loop for performance-critical ArrayList iteration.

    + +

    (See also Effective Java item 46.)

    + + +

    Consider Package Instead of Private Access with Private Inner Classes

    + +

    Consider the following class definition:

    + +
    public class Foo {
    +    private class Inner {
    +        void stuff() {
    +            Foo.this.doStuff(Foo.this.mValue);
    +        }
    +    }
    +
    +    private int mValue;
    +
    +    public void run() {
    +        Inner in = new Inner();
    +        mValue = 27;
    +        in.stuff();
    +    }
    +
    +    private void doStuff(int value) {
    +        System.out.println("Value is " + value);
    +    }
    +}
    + +

    The key things to note here are that we define a private inner class +(Foo$Inner) that directly accesses a private method and a private +instance field in the outer class. This is legal, and the code prints "Value is +27" as expected.

    + +

    The problem is that the VM considers direct access to Foo's +private members from Foo$Inner to be illegal because +Foo and Foo$Inner are different classes, even though +the Java language allows an inner class to access an outer class' private +members. To bridge the gap, the compiler generates a couple of synthetic +methods:

    + +
    /*package*/ static int Foo.access$100(Foo foo) {
    +    return foo.mValue;
    +}
    +/*package*/ static void Foo.access$200(Foo foo, int value) {
    +    foo.doStuff(value);
    +}
    + +

    The inner class code calls these static methods whenever it needs to +access the mValue field or invoke the doStuff method +in the outer class. What this means is that the code above really boils down to +a case where you're accessing member fields through accessor methods. +Earlier we talked about how accessors are slower than direct field +accesses, so this is an example of a certain language idiom resulting in an +"invisible" performance hit.

    + +

    If you're using code like this in a performance hotspot, you can avoid the +overhead by declaring fields and methods accessed by inner classes to have +package access, rather than private access. Unfortunately this means the fields +can be accessed directly by other classes in the same package, so you shouldn't +use this in public API.

    + + +

    Use Floating-Point Judiciously

    + +

    As a rule of thumb, floating-point is about 2x slower than integer on +Android devices. This is true on a FPU-less, JIT-less G1 and a Nexus One with +an FPU and the JIT. (Of course, absolute speed difference between those two +devices is about 10x for arithmetic operations.)

    + +

    In speed terms, there's no difference between float and +double on the more modern hardware. Space-wise, double +is 2x larger. As with desktop machines, assuming space isn't an issue, you +should prefer double to float.

    + +

    Also, even for integers, some chips have hardware multiply but lack +hardware divide. In such cases, integer division and modulus operations are +performed in software — something to think about if you're designing a +hash table or doing lots of math.

    + + +

    Know And Use The Libraries

    + +

    In addition to all the usual reasons to prefer library code over rolling +your own, bear in mind that the system is at liberty to replace calls +to library methods with hand-coded assembler, which may be better than the +best code the JIT can produce for the equivalent Java. The typical example +here is String.indexOf and friends, which Dalvik replaces with +an inlined intrinsic. Similarly, the System.arraycopy method +is about 9x faster than a hand-coded loop on a Nexus One with the JIT.

    + +

    (See also Effective Java item 47.)

    + + +

    Use Native Methods Judiciously

    + +

    Native code isn't necessarily more efficient than Java. For one thing, +there's a cost associated with the Java-native transition, and the JIT can't +optimize across these boundaries. If you're allocating native resources (memory +on the native heap, file descriptors, or whatever), it can be significantly +more difficult to arrange timely collection of these resources. You also +need to compile your code for each architecture you wish to run on (rather +than rely on it having a JIT). You may even have to compile multiple versions +for what you consider the same architecture: native code compiled for the ARM +processor in the G1 can't take full advantage of the ARM in the Nexus One, and +code compiled for the ARM in the Nexus One won't run on the ARM in the G1.

    + +

    Native code is primarily useful when you have an existing native codebase +that you want to port to Android, not for "speeding up" parts of a Java app.

    + +

    If you do need to use native code, you should read our +JNI Tips.

    + +

    (See also Effective Java item 54.)

    + + +

    Closing Notes

    + +

    One last thing: always measure. Before you start optimizing, make sure you +have a problem. Make sure you can accurately measure your existing performance, +or you won't be able to measure the benefit of the alternatives you try.

    + +

    Every claim made in this document is backed up by a benchmark. The source +to these benchmarks can be found in the code.google.com "dalvik" project.

    + +

    The benchmarks are built with the +Caliper microbenchmarking +framework for Java. Microbenchmarks are hard to get right, so Caliper goes out +of its way to do the hard work for you, and even detect some cases where you're +not measuring what you think you're measuring (because, say, the VM has +managed to optimize all your code away). We highly recommend you use Caliper +to run your own microbenchmarks.

    + +

    You may also find +Traceview useful +for profiling, but it's important to realize that it currently disables the JIT, +which may cause it to misattribute time to code that the JIT may be able to win +back. It's especially important after making changes suggested by Traceview +data to ensure that the resulting code actually runs faster when run without +Traceview. diff --git a/docs/html/guide/practices/app-design/responsiveness.jd b/docs/html/guide/practices/app-design/responsiveness.jd new file mode 100644 index 000000000000..a00e3aa65114 --- /dev/null +++ b/docs/html/guide/practices/app-design/responsiveness.jd @@ -0,0 +1,140 @@ +page.title=Designing for Responsiveness +@jd:body + +

    + +
    + +
    +Screenshot of ANR dialog box +

    Figure 1. An ANR dialog displayed to the user.

    +
    + +

    It's possible to write code that wins every performance test in the world, +but still sends users in a fiery rage when they try to use the application. +These are the applications that aren't responsive enough — the +ones that feel sluggish, hang or freeze for significant periods, or take too +long to process input.

    + +

    In Android, the system guards against applications that are insufficiently +responsive for a period of time by displaying a dialog to the user, called the +Application Not Responding (ANR) dialog, shown at right in Figure 1. The user +can choose to let the application continue, but the user won't appreciate having +to act on this dialog every time he or she uses your application. It's critical +to design responsiveness into your application, so that the system never has +cause to display an ANR dialog to the user.

    + +

    Generally, the system displays an ANR if an application cannot respond to +user input. For example, if an application blocks on some I/O operation +(frequently a network access), then the main application thread won't be able to +process incoming user input events. After a time, the system concludes that the +application is frozen, and displays the ANR to give the user the option to kill +it.

    + +

    Similarly, if your application spends too much time building an elaborate in-memory +structure, or perhaps computing the next move in a game, the system will +conclude that your application has hung. It's always important to make +sure these computations are efficient using the techniques above, but even the +most efficient code still takes time to run.

    + +

    In both of these cases, the recommended approach is to create a child thread and do +most of your work there. This keeps the main thread (which drives the user +interface event loop) running and prevents the system from concluding that your code +has frozen. Since such threading usually is accomplished at the class +level, you can think of responsiveness as a class problem. (Compare +this with basic performance, which was described above as a method-level +concern.)

    + +

    This document describes how the Android system determines whether an +application is not responding and provides guidelines for ensuring that your +application stays responsive.

    + +

    What Triggers ANR?

    + +

    In Android, application responsiveness is monitored by the Activity Manager +and Window Manager system services. Android will display the ANR dialog +for a particular application when it detects one of the following +conditions:

    +
      +
    • No response to an input event (e.g. key press, screen touch) + within 5 seconds
    • +
    • A {@link android.content.BroadcastReceiver BroadcastReceiver} + hasn't finished executing within 10 seconds
    • +
    + +

    How to Avoid ANR

    + +

    Given the above definition for ANR, let's examine why this can occur in +Android applications and how best to structure your application to avoid ANR.

    + +

    Android applications normally run entirely on a single (i.e. main) thread. +This means that anything your application is doing in the main thread that +takes a long time to complete can trigger the ANR dialog because your +application is not giving itself a chance to handle the input event or Intent +broadcast.

    + +

    Therefore any method that runs in the main thread should do as little work +as possible. In particular, Activities should do as little as possible to set +up in key life-cycle methods such as onCreate() and +onResume(). Potentially long running operations such as network +or database operations, or computationally expensive calculations such as +resizing bitmaps should be done in a child thread (or in the case of databases +operations, via an asynchronous request). However, this does not mean that +your main thread should block while waiting for the child thread to +complete — nor should you call Thread.wait() or +Thread.sleep(). Instead of blocking while waiting for a child +thread to complete, your main thread should provide a {@link +android.os.Handler Handler} for child threads to post back to upon completion. +Designing your application in this way will allow your main thread to remain +responsive to input and thus avoid ANR dialogs caused by the 5 second input +event timeout. These same practices should be followed for any other threads +that display UI, as they are also subject to the same timeouts.

    + +

    You can use {@link android.os.StrictMode} to help find potentially +long running operations such as network or database operations that +you might accidentally be doing your main thread.

    + +

    The specific constraint on IntentReceiver execution time emphasizes what +they were meant to do: small, discrete amounts of work in the background such +as saving a setting or registering a Notification. So as with other methods +called in the main thread, applications should avoid potentially long-running +operations or calculations in BroadcastReceivers. But instead of doing intensive +tasks via child threads (as the life of a BroadcastReceiver is short), your +application should start a {@link android.app.Service Service} if a +potentially long running action needs to be taken in response to an Intent +broadcast. As a side note, you should also avoid starting an Activity from an +Intent Receiver, as it will spawn a new screen that will steal focus from +whatever application the user is currently has running. If your application +has something to show the user in response to an Intent broadcast, it should +do so using the {@link android.app.NotificationManager Notification +Manager}.

    + +

    Reinforcing Responsiveness

    + +

    Generally, 100 to 200ms is the threshold beyond which users will perceive +lag (or lack of "snappiness," if you will) in an application. As such, here +are some additional tips beyond what you should do to avoid ANR that will help +make your application seem responsive to users.

    + +
      +
    • If your application is doing work in the background in response to + user input, show that progress is being made ({@link + android.widget.ProgressBar ProgressBar} and {@link + android.app.ProgressDialog ProgressDialog} are useful for this).
    • +
    • For games specifically, do calculations for moves in a child + thread.
    • +
    • If your application has a time-consuming initial setup phase, consider + showing a splash screen or rendering the main view as quickly as possible + and filling in the information asynchronously. In either case, you should + indicate somehow that progress is being made, lest the user perceive that + the application is frozen.
    • +
    diff --git a/docs/html/guide/practices/app-design/seamlessness.jd b/docs/html/guide/practices/app-design/seamlessness.jd new file mode 100644 index 000000000000..ec6b7fdff73c --- /dev/null +++ b/docs/html/guide/practices/app-design/seamlessness.jd @@ -0,0 +1,249 @@ +page.title=Designing for Seamlessness +@jd:body + + + +

    Even if your application is fast and responsive, certain design decisions can +still cause problems for users — because of unplanned interactions with +other applications or dialogs, inadvertent loss of data, unintended blocking, +and so on. To avoid these problems, it helps to understand the context in which +your applications run and the system interactions that can affect your +application. In short, you should strive to develop an application that +interacts seamlessly with the system and with other applications.

    + +

    A common seamlessness problem is when an application's background process +— for example, a service or broadcast receiver — pops up a dialog in +response to some event. This may seem like harmless behavior, especially when +you are building and testing your application in isolation, on the emulator. +However, when your application is run on an actual device, your application may +not have user focus at the time your background process displays the dialog. So +it could end up that your application would display it's dialog behind the +active application, or it could take focus from the current application and +display the dialog in front of whatever the user was doing (such as dialing a +phone call, for example). That behavior would not work for your application or +for the user.

    + +

    To avoid these problems, your application should use the proper system +facility for notifying the user — the +{@link android.app.Notification Notification} classes. Using +notifications, your application can signal the user that an event has +taken place, by displaying an icon in the status bar rather than taking +focus and interrupting the user.

    + +

    Another example of a seamlessness problem is when an activity inadvertently +loses state or user data because it doesn't correctly implement the onPause() +and other lifecycle methods. Or, if your application exposes data intended to be +used by other applications, you should expose it via a ContentProvider, rather +than (for example) doing so through a world-readable raw file or database.

    + +

    What those examples have in common is that they involve cooperating nicely +with the system and other applications. The Android system is designed to treat +applications as a sort of federation of loosely-coupled components, rather than +chunks of black-box code. This allows you as the developer to view the entire +system as just an even-larger federation of these components. This benefits you +by allowing you to integrate cleanly and seamlessly with other applications, and +so you should design your own code to return the favor.

    + +

    This document discusses common seamlessness problems and how to avoid them.

    + +

    Don't Drop Data

    + +

    Always keep in mind that Android is a mobile platform. It may seem obvious to +say it, but it's important to remember that another Activity (such as the +"Incoming Phone Call" app) can pop up over your own Activity at any moment. +This will fire the onSaveInstanceState() and onPause() methods, and will likely result in +your application being killed.

    + +

    If the user was editing data in your application when the other Activity +appeared, your application will likely lose that data when your application is +killed. Unless, of course, you save the work in progress first. The "Android +Way" is to do just that: Android applications that accept or edit input should +override the onSaveInstanceState() method and save their state in some appropriate +fashion. When the user revisits the application, she should be able to +retrieve her data.

    + +

    A classic example of a good use of this behavior is a mail application. If the +user was composing an email when another Activity started up, the application +should save the in-process email as a draft.

    + +

    Don't Expose Raw Data

    + +

    If you wouldn't walk down the street in your underwear, neither should your +data. While it's possible to expose certain kinds of application to the world +to read, this is usually not the best idea. Exposing raw data requires other +applications to understand your data format; if you change that format, you'll +break any other applications that aren't similarly updated.

    + +

    The "Android Way" is to create a ContentProvider to expose your data to other +applications via a clean, well-thought-out, and maintainable API. Using a +ContentProvider is much like inserting a Java language interface to split up and +componentize two tightly-coupled pieces of code. This means you'll be able to +modify the internal format of your data without changing the interface exposed +by the ContentProvider, and this without affecting other applications.

    + +

    Don't Interrupt the User

    + +

    If the user is running an application (such as the Phone application during a +call) it's a pretty safe bet he did it on purpose. That's why you should avoid +spawning activities except in direct response to user input from the current +Activity.

    + +

    That is, don't call startActivity() from BroadcastReceivers or Services running in +the background. Doing so will interrupt whatever application is currently +running, and result in an annoyed user. Perhaps even worse, your Activity may +become a "keystroke bandit" and receive some of the input the user was in the +middle of providing to the previous Activity. Depending on what your +application does, this could be bad news.

    + +

    Instead of spawning Activity UIs directly from the background, you should +instead use the NotificationManager to set Notifications. These will appear in +the status bar, and the user can then click on them at his leisure, to see +what your application has to show him.

    + +

    (Note that all this doesn't apply to cases where your own Activity is already +in the foreground: in that case, the user expects to see your next Activity in +response to input.)

    + +

    Got a Lot to Do? Do it in a Thread

    + +

    If your application needs to perform some expensive or long-running +computation, you should probably move it to a thread. This will prevent the +dreaded "Application Not Responding" dialog from being displayed to the user, +with the ultimate result being the fiery demise of your application.

    + +

    By default, all code in an Activity as well as all its Views run in the same +thread. This is the same thread that also handles UI events. For example, when +the user presses a key, a key-down event is added to the Activity's main +thread's queue. The event handler system needs to dequeue and handle that +event quickly; if it doesn't, the system concludes after a few seconds that +the application is hung and offers to kill it for the user.

    + +

    If you have long-running code, running it inline in your Activity will run it +on the event handler thread, effectively blocking the event handler. This will +delay input processing, and result in the ANR dialogs. To avoid this, move +your computations to a thread. This Design for Responsiveness document +discusses how to do that..

    + +

    Don't Overload a Single Activity Screen

    + +

    Any application worth using will probably have several different screens. +When designing the screens of your UI, be sure to make use of multiple Activity +object instances.

    + +

    Depending on your development background, you may interpret an Activity as +similar to something like a Java Applet, in that it is the entry point for +your application. However, that's not quite accurate: where an Applet subclass +is the single entry point for a Java Applet, an Activity should be thought of +as one of potentially several entry points to your application. The only +difference between your "main" Activity and any others you might have is that +the "main" one just happens to be the only one that expressed an interest in +the "android.intent.action.MAIN" action in your AndroidManifest..xml file.

    + +

    So, when designing your application, think of your application as a federation +of Activity objects. This will make your code a lot more maintainable in the long +run, and as a nice side effect also plays nicely with Android's application +history and "backstack" model.

    + +

    Extend System Themes

    + +

    When it comes to the look-and-feel of the user interface, it's important to +blend in nicely. Users are jarred by applications which contrast with the user +interface they've come to expect. When designing your UIs, you should try and +avoid rolling your own as much as possible. Instead, use a Theme. You +can override or extend those parts of the theme that you need to, but at least +you're starting from the same UI base as all the other applications. For all +the details, read Styles and Themes.

    + +

    Design Your UI to Work with Multiple Screen Resolutions

    + +

    Different Android-powered devices will support different screen resolutions. +Some will even be able to change resolutions on the fly, such as by switching +to landscape mode. It's important to make sure your layouts and drawables +are flexible enough to display properly on a variety of device screens.

    + +

    Fortunately, this is very easy to do. In brief, what you must do is +provide different versions of your artwork (if you use any) for the key +resolutions, and then design your layout to accommodate various dimensions. +(For example, avoid using hard-coded positions and instead use relative +layouts.) If you do that much, the system handles the rest, and your +application looks great on any device.

    + +

    Assume the Network is Slow

    + +

    Android devices will come with a variety of network-connectivity options. All +will have some data-access provision, though some will be faster than others. +The lowest common denominator, however, is GPRS, the non-3G data service for +GSM networks. Even 3G-capable devices will spend lots of time on non-3G +networks, so slow networks will remain a reality for quite a long time to +come.

    + +

    That's why you should always code your applications to minimize network +accesses and bandwidth. You can't assume the network is fast, so you should +always plan for it to be slow. If your users happen to be on faster networks, +then that's great — their experience will only improve. You want to avoid the +inverse case though: applications that are usable some of the time, but +frustratingly slow the rest based on where the user is at any given moment are +likely to be unpopular.

    + +

    One potential gotcha here is that it's very easy to fall into this trap if +you're using the emulator, since the emulator uses your desktop computer's +network connection. That's almost guaranteed to be much faster than a cell +network, so you'll want to change the settings on the emulator that simulate +slower network speeds. You can do this in Eclipse, in the "Emulator Settings" +tab of your launch configuration or via a command-line +option when starting the emulator.

    + +

    Don't Assume Touchscreen or Keyboard

    + +

    +Android will support a variety of handset form-factors. That's a fancy way of +saying that some Android devices will have full "QWERTY" keyboards, while +others will have 40-key, 12-key, or even other key configurations. Similarly, +some devices will have touch-screens, but many won't. +

    +When building your applications, keep that in mind. Don't make assumptions +about specific keyboard layouts -- unless, of course, you're really interested +in restricting your application so that it can only be used on those devices. +

    + +

    Do Conserve the Device Battery

    +

    +A mobile device isn't very mobile if it's constantly plugged into the +wall. Mobile devices are battery-powered, and the longer we can make that +battery last on a charge, the happier everyone is — especially the user. +Two of the biggest consumers of battery power are the processor, and the +radio; that's why it's important to write your applications to do as little +work as possible, and use the network as infrequently as possible. +

    +Minimizing the amount of processor time your application uses really comes +down to writing efficient +code. To minimize the power drain from using the radio, be sure to handle +error conditions gracefully, and only fetch what you need. For example, don't +constantly retry a network operation if one failed. If it failed once, it's +likely because the user has no reception, so it's probably going to fail again +if you try right away; all you'll do is waste battery power. +

    +Users are pretty smart: if your program is power-hungry, you can count on +them noticing. The only thing you can be sure of at that point is that your +program won't stay installed very long. +

    diff --git a/docs/html/guide/practices/compatibility.jd b/docs/html/guide/practices/compatibility.jd index 5e514c4444c1..a2284bd03133 100644 --- a/docs/html/guide/practices/compatibility.jd +++ b/docs/html/guide/practices/compatibility.jd @@ -7,7 +7,7 @@ page.title=Android Compatibility

    See also

    1. Filtering on Google Play
    2. +href="{@docRoot}guide/google/play/filters.html">Filtering on Google Play
    3. Providing Alternative Resources
    4. .apk file.

      There is exactly one Android API for each API level, and it’s the same +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level, and it’s the same API no matter what kind of device it’s installed on. No parts of the API are optional, and you never have to worry about parts of the API missing on some devices. Every compatible Android device your app will land on will include @@ -119,7 +119,7 @@ device.

      For information about other filters that you can use to control the availability of your apps, see the -Filters on Google Play +Filters on Google Play document.

    diff --git a/docs/html/guide/practices/design/accessibility.html b/docs/html/guide/practices/design/accessibility.html deleted file mode 100644 index 0fa7b3213dd9..000000000000 --- a/docs/html/guide/practices/design/accessibility.html +++ /dev/null @@ -1,11 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/practices/design/index.jd b/docs/html/guide/practices/design/index.jd deleted file mode 100644 index a818831e43e7..000000000000 --- a/docs/html/guide/practices/design/index.jd +++ /dev/null @@ -1,21 +0,0 @@ -page.title=Application Design Goals -@jd:body - -

    When learning how to build applications on a new platform, you first learn what APIs are available and how to use them. Later, you learn the nuances of the platform. Put another way: first you learn how you can build applications; later, you learn how you should build them, to ensure that your applications offer outstanding performance and a great user experience.

    - -

    The documents below help you learn the nuances of Android and get started building great applications more quickly, They discuss important aspects of application design that directly influence the user experience of your application, when in the hands of a mobile device user. You should read and consider these design goals as you plan your application and throughout its development, especially if you are new to developing for mobile devices.

    - -

    Successful mobile applications offer an outstanding user experience, in addition to a compelling technical feature set. The user experience is more than just its visual design or UI flow. It is also influenced by how well the application responds to the user's keypresses and other actions, how it well it interacts with other applications, and how fully and efficiently it uses device and system capabilities.

    - -

    An outstanding user experience has three key characteristics: it is -fast; it is responsive; and it is seamless. Of course -every platform since the dawn of computing has probably cited those same three -qualities at one time or another. However, each platform achieves them in -different ways; the documents below explain how you can build Android -applications that are fast, responsive, and seamless.

    - - diff --git a/docs/html/guide/practices/design/jni.jd b/docs/html/guide/practices/design/jni.jd deleted file mode 100644 index ddfa0e3991f5..000000000000 --- a/docs/html/guide/practices/design/jni.jd +++ /dev/null @@ -1,719 +0,0 @@ -page.title=JNI Tips -@jd:body - - - -

    JNI is the Java Native Interface. It defines a way for managed code -(written in the Java programming language) to interact with native -code (written in C/C++). It's vendor-neutral, has support for loading code from -dynamic shared libraries, and while cumbersome at times is reasonably efficient.

    - -

    You really should read through the -JNI spec for J2SE 6 -to get a sense for how JNI works and what features are available. Some -aspects of the interface aren't immediately obvious on -first reading, so you may find the next few sections handy. -There's a more detailed JNI Programmer's Guide and Specification.

    - - - -

    JavaVM and JNIEnv

    - -

    JNI defines two key data structures, "JavaVM" and "JNIEnv". Both of these are essentially -pointers to pointers to function tables. (In the C++ version, they're classes with a -pointer to a function table and a member function for each JNI function that indirects through -the table.) The JavaVM provides the "invocation interface" functions, -which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, -but Android only allows one.

    - -

    The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as -the first argument.

    - -

    The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. -If a piece of code has no other way to get its JNIEnv, you should share -the JavaVM, and use GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)

    - -

    The C declarations of JNIEnv and JavaVM are different from the C++ -declarations. The "jni.h" include file provides different typedefs -depending on whether it's included into C or C++. For this reason it's a bad idea to -include JNIEnv arguments in header files included by both languages. (Put another way: if your -header file requires #ifdef __cplusplus, you may have to do some extra work if anything in -that header refers to JNIEnv.)

    - - -

    Threads

    - -

    All threads are Linux threads, scheduled by the kernel. They're usually -started from managed code (using Thread.start), -but they can also be created elsewhere and then attached to the JavaVM. For -example, a thread started with pthread_create can be attached -with the JNI AttachCurrentThread or -AttachCurrentThreadAsDaemon functions. Until a thread is -attached, it has no JNIEnv, and cannot make JNI calls.

    - -

    Attaching a natively-created thread causes a java.lang.Thread -object to be constructed and added to the "main" ThreadGroup, -making it visible to the debugger. Calling AttachCurrentThread -on an already-attached thread is a no-op.

    - -

    Android does not suspend threads executing native code. If -garbage collection is in progress, or the debugger has issued a suspend -request, Android will pause the thread the next time it makes a JNI call.

    - -

    Threads attached through JNI must call -DetachCurrentThread before they exit. -If coding this directly is awkward, in Android 2.0 (Eclair) and higher you -can use pthread_key_create to define a destructor -function that will be called before the thread exits, and -call DetachCurrentThread from there. (Use that -key with pthread_setspecific to store the JNIEnv in -thread-local-storage; that way it'll be passed into your destructor as -the argument.)

    - - - -

    jclass, jmethodID, and jfieldID

    - -

    If you want to access an object's field from native code, you would do the following:

    - -
      -
    • Get the class object reference for the class with FindClass
    • -
    • Get the field ID for the field with GetFieldID
    • -
    • Get the contents of the field with something appropriate, such as -GetIntField
    • -
    - -

    Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just -pointers to internal runtime data structures. Looking them up may require several string -comparisons, but once you have them the actual call to get the field or invoke the method -is very quick.

    - -

    If performance is important, it's useful to look the values up once and cache the results -in your native code. Because there is a limit of one JavaVM per process, it's reasonable -to store this data in a static local structure.

    - -

    The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes -are only unloaded if all classes associated with a ClassLoader can be garbage collected, -which is rare but will not be impossible in Android. Note however that -the jclass -is a class reference and must be protected with a call -to NewGlobalRef (see the next section).

    - -

    If you would like to cache the IDs when a class is loaded, and automatically re-cache them -if the class is ever unloaded and reloaded, the correct way to initialize -the IDs is to add a piece of code that looks like this to the appropriate class:

    - -
        /*
    -     * We use a class initializer to allow the native code to cache some
    -     * field offsets. This native function looks up and caches interesting
    -     * class/field/method IDs. Throws on failure.
    -     */
    -    private static native void nativeInit();
    -
    -    static {
    -        nativeInit();
    -    }
    - -

    Create a nativeClassInit method in your C/C++ code that performs the ID lookups. The code -will be executed once, when the class is initialized. If the class is ever unloaded and -then reloaded, it will be executed again.

    - - -

    Local and Global References

    - -

    Every argument passed to a native method, and almost every object returned -by a JNI function is a "local reference". This means that it's valid for the -duration of the current native method in the current thread. -Even if the object itself continues to live on after the native method -returns, the reference is not valid. -

    This applies to all sub-classes of jobject, including -jclass, jstring, and jarray. -(The runtime will warn you about most reference mis-uses when extended JNI -checks are enabled.)

    -

    The only way to get non-local references is via the functions -NewGlobalRef and NewWeakGlobalRef. - -

    If you want to hold on to a reference for a longer period, you must use -a "global" reference. The NewGlobalRef function takes the -local reference as an argument and returns a global one. -The global reference is guaranteed to be valid until you call -DeleteGlobalRef.

    - -

    This pattern is commonly used when caching a jclass returned -from FindClass, e.g.:

    -
    jclass localClass = env->FindClass("MyClass");
    -jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
    - -

    All JNI methods accept both local and global references as arguments. -It's possible for references to the same object to have different values. -For example, the return values from consecutive calls to -NewGlobalRef on the same object may be different. -To see if two references refer to the same object, -you must use the IsSameObject function. Never compare -references with == in native code.

    - -

    One consequence of this is that you -must not assume object references are constant or unique -in native code. The 32-bit value representing an object may be different -from one invocation of a method to the next, and it's possible that two -different objects could have the same 32-bit value on consecutive calls. Do -not use jobject values as keys.

    - -

    Programmers are required to "not excessively allocate" local references. In practical terms this means -that if you're creating large numbers of local references, perhaps while running through an array of -objects, you should free them manually with -DeleteLocalRef instead of letting JNI do it for you. The -implementation is only required to reserve slots for -16 local references, so if you need more than that you should either delete as you go or use -EnsureLocalCapacity/PushLocalFrame to reserve more.

    - -

    Note that jfieldIDs and jmethodIDs are opaque -types, not object references, and should not be passed to -NewGlobalRef. The raw data -pointers returned by functions like GetStringUTFChars -and GetByteArrayElements are also not objects. (They may be passed -between threads, and are valid until the matching Release call.)

    - -

    One unusual case deserves separate mention. If you attach a native -thread with AttachCurrentThread, the code you are running will -never automatically free local references until the thread detaches. Any local -references you create will have to be deleted manually. In general, any native -code that creates local references in a loop probably needs to do some manual -deletion.

    - - -

    UTF-8 and UTF-16 Strings

    - -

    The Java programming language uses UTF-16. For convenience, JNI provides methods that work with Modified UTF-8 as well. The -modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00. -The nice thing about this is that you can count on having C-style zero-terminated strings, -suitable for use with standard libc string functions. The down side is that you cannot pass -arbitrary UTF-8 data to JNI and expect it to work correctly.

    - -

    If possible, it's usually faster to operate with UTF-16 strings. Android -currently does not require a copy in GetStringChars, whereas -GetStringUTFChars requires an allocation and a conversion to -UTF-8. Note that -UTF-16 strings are not zero-terminated, and \u0000 is allowed, -so you need to hang on to the string length as well as -the jchar pointer.

    - -

    Don't forget to Release the strings you Get. The -string functions return jchar* or jbyte*, which -are C-style pointers to primitive data rather than local references. They -are guaranteed valid until Release is called, which means they are not -released when the native method returns.

    - -

    Data passed to NewStringUTF must be in Modified UTF-8 format. A -common mistake is reading character data from a file or network stream -and handing it to NewStringUTF without filtering it. -Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII -characters or convert them to proper Modified UTF-8 form. If you don't, -the UTF-16 conversion will likely not be what you expect. The extended -JNI checks will scan strings and warn you about invalid data, but they -won't catch everything.

    - - -

    Primitive Arrays

    - -

    JNI provides functions for accessing the contents of array objects. -While arrays of objects must be accessed one entry at a time, arrays of -primitives can be read and written directly as if they were declared in C.

    - -

    To make the interface as efficient as possible without constraining -the VM implementation, the Get<PrimitiveType>ArrayElements -family of calls allows the runtime to either return a pointer to the actual elements, or -allocate some memory and make a copy. Either way, the raw pointer returned -is guaranteed to be valid until the corresponding Release call -is issued (which implies that, if the data wasn't copied, the array object -will be pinned down and can't be relocated as part of compacting the heap). -You must Release every array you Get. Also, if the Get -call fails, you must ensure that your code doesn't try to Release a NULL -pointer later.

    - -

    You can determine whether or not the data was copied by passing in a -non-NULL pointer for the isCopy argument. This is rarely -useful.

    - -

    The Release call takes a mode argument that can -have one of three values. The actions performed by the runtime depend upon -whether it returned a pointer to the actual data or a copy of it:

    - -
      -
    • 0 -
        -
      • Actual: the array object is un-pinned. -
      • Copy: data is copied back. The buffer with the copy is freed. -
      -
    • JNI_COMMIT -
        -
      • Actual: does nothing. -
      • Copy: data is copied back. The buffer with the copy - is not freed. -
      -
    • JNI_ABORT -
        -
      • Actual: the array object is un-pinned. Earlier - writes are not aborted. -
      • Copy: the buffer with the copy is freed; any changes to it are lost. -
      -
    - -

    One reason for checking the isCopy flag is to know if -you need to call Release with JNI_COMMIT -after making changes to an array — if you're alternating between making -changes and executing code that uses the contents of the array, you may be -able to -skip the no-op commit. Another possible reason for checking the flag is for -efficient handling of JNI_ABORT. For example, you might want -to get an array, modify it in place, pass pieces to other functions, and -then discard the changes. If you know that JNI is making a new copy for -you, there's no need to create another "editable" copy. If JNI is passing -you the original, then you do need to make your own copy.

    - -

    It is a common mistake (repeated in example code) to assume that you can skip the Release call if -*isCopy is false. This is not the case. If no copy buffer was -allocated, then the original memory must be pinned down and can't be moved by -the garbage collector.

    - -

    Also note that the JNI_COMMIT flag does not release the array, -and you will need to call Release again with a different flag -eventually.

    - - - -

    Region Calls

    - -

    There is an alternative to calls like Get<Type>ArrayElements -and GetStringChars that may be very helpful when all you want -to do is copy data in or out. Consider the following:

    - -
        jbyte* data = env->GetByteArrayElements(array, NULL);
    -    if (data != NULL) {
    -        memcpy(buffer, data, len);
    -        env->ReleaseByteArrayElements(array, data, JNI_ABORT);
    -    }
    - -

    This grabs the array, copies the first len byte -elements out of it, and then releases the array. Depending upon the -implementation, the Get call will either pin or copy the array -contents. -The code copies the data (for perhaps a second time), then calls Release; in this case -JNI_ABORT ensures there's no chance of a third copy.

    - -

    One can accomplish the same thing more simply:

    -
        env->GetByteArrayRegion(array, 0, len, buffer);
    - -

    This has several advantages:

    -
      -
    • Requires one JNI call instead of 2, reducing overhead. -
    • Doesn't require pinning or extra data copies. -
    • Reduces the risk of programmer error — no risk of forgetting - to call Release after something fails. -
    - -

    Similarly, you can use the Set<Type>ArrayRegion call -to copy data into an array, and GetStringRegion or -GetStringUTFRegion to copy characters out of a -String. - - - -

    Exceptions

    - -

    You must not call most JNI functions while an exception is pending. -Your code is expected to notice the exception (via the function's return value, -ExceptionCheck, or ExceptionOccurred) and return, -or clear the exception and handle it.

    - -

    The only JNI functions that you are allowed to call while an exception is -pending are:

    -
      -
    • DeleteGlobalRef -
    • DeleteLocalRef -
    • DeleteWeakGlobalRef -
    • ExceptionCheck -
    • ExceptionClear -
    • ExceptionDescribe -
    • ExceptionOccurred -
    • MonitorExit -
    • PopLocalFrame -
    • PushLocalFrame -
    • Release<PrimitiveType>ArrayElements -
    • ReleasePrimitiveArrayCritical -
    • ReleaseStringChars -
    • ReleaseStringCritical -
    • ReleaseStringUTFChars -
    - -

    Many JNI calls can throw an exception, but often provide a simpler way -of checking for failure. For example, if NewString returns -a non-NULL value, you don't need to check for an exception. However, if -you call a method (using a function like CallObjectMethod), -you must always check for an exception, because the return value is not -going to be valid if an exception was thrown.

    - -

    Note that exceptions thrown by interpreted code do not unwind native stack -frames, and Android does not yet support C++ exceptions. -The JNI Throw and ThrowNew instructions just -set an exception pointer in the current thread. Upon returning to managed -from native code, the exception will be noted and handled appropriately.

    - -

    Native code can "catch" an exception by calling ExceptionCheck or -ExceptionOccurred, and clear it with -ExceptionClear. As usual, -discarding exceptions without handling them can lead to problems.

    - -

    There are no built-in functions for manipulating the Throwable object -itself, so if you want to (say) get the exception string you will need to -find the Throwable class, look up the method ID for -getMessage "()Ljava/lang/String;", invoke it, and if the result -is non-NULL use GetStringUTFChars to get something you can -hand to printf(3) or equivalent.

    - - - -

    Extended Checking

    - -

    JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.

    - -

    The additional checks include:

    - -
      -
    • Arrays: attempting to allocate a negative-sized array.
    • -
    • Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.
    • -
    • Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
    • -
    • Critical calls: making a JNI call between a “critical” get and its corresponding release.
    • -
    • Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
    • -
    • Exceptions: making a JNI call while there’s an exception pending.
    • -
    • JNIEnv*s: using a JNIEnv* from the wrong thread.
    • -
    • jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
    • -
    • jmethodIDs: using the wrong kind of jmethodID when making a Call*Method JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).
    • -
    • References: using DeleteGlobalRef/DeleteLocalRef on the wrong kind of reference.
    • -
    • Release modes: passing a bad release mode to a release call (something other than 0, JNI_ABORT, or JNI_COMMIT).
    • -
    • Type safety: returning an incompatible type from your native method (returning a StringBuilder from a method declared to return a String, say).
    • -
    • UTF-8: passing an invalid Modified UTF-8 byte sequence to a JNI call.
    • -
    - -

    (Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)

    - -

    There are several ways to enable CheckJNI.

    - -

    If you’re using the emulator, CheckJNI is on by default.

    - -

    If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:

    - -
    adb shell stop
    -adb shell setprop dalvik.vm.checkjni true
    -adb shell start
    - -

    In either of these cases, you’ll see something like this in your logcat output when the runtime starts:

    - -
    D AndroidRuntime: CheckJNI is ON
    - -

    If you have a regular device, you can use the following command:

    - -
    adb shell setprop debug.checkjni 1
    - -

    This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Change the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time an app starts:

    - -
    D Late-enabling CheckJNI
    - - - - - -

    Native Libraries

    - -

    You can load native code from shared libraries with the standard -System.loadLibrary call. The -preferred way to get at your native code is:

    - -
      -
    • Call System.loadLibrary from a static class -initializer. (See the earlier example, where one is used to call -nativeClassInit.) The argument is the "undecorated" -library name, so to load "libfubar.so" you would pass in "fubar".
    • -
    • Provide a native function: jint JNI_OnLoad(JavaVM* vm, void* reserved)
    • -
    • In JNI_OnLoad, register all of your native methods. You -should declare -the methods "static" so the names don't take up space in the symbol table -on the device.
    • -
    - -

    The JNI_OnLoad function should look something like this if -written in C++:

    -
    jint JNI_OnLoad(JavaVM* vm, void* reserved)
    -{
    -    JNIEnv* env;
    -    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
    -        return -1;
    -    }
    -
    -    // Get jclass with env->FindClass.
    -    // Register methods with env->RegisterNatives.
    -
    -    return JNI_VERSION_1_6;
    -}
    - -

    You can also call System.load with the full path name of the -shared library. For Android apps, you may find it useful to get the full -path to the application's private data storage area from the context object.

    - -

    This is the recommended approach, but not the only approach. Explicit -registration is not required, nor is it necessary that you provide a -JNI_OnLoad function. -You can instead use "discovery" of native methods that are named in a -specific way (see the JNI spec for details), though this is less desirable because if a method signature is wrong you won't know -about it until the first time the method is actually used.

    - -

    One other note about JNI_OnLoad: any FindClass -calls you make from there will happen in the context of the class loader -that was used to load the shared library. Normally FindClass -uses the loader associated with the method at the top of the interpreted -stack, or if there isn't one (because the thread was just attached) it uses -the "system" class loader. This makes -JNI_OnLoad a convenient place to look up and cache class -object references.

    - - - -

    64-bit Considerations

    - -

    Android is currently expected to run on 32-bit platforms. In theory it -could be built for a 64-bit system, but that is not a goal at this time. -For the most part this isn't something that you will need to worry about -when interacting with native code, -but it becomes significant if you plan to store pointers to native -structures in integer fields in an object. To support architectures -that use 64-bit pointers, you need to stash your native pointers in a -long field rather than an int. - - - -

    Unsupported Features/Backwards Compatibility

    - -

    All JNI 1.6 features are supported, with the following exception:

    -
      -
    • DefineClass is not implemented. Android does not use - Java bytecodes or class files, so passing in binary class data - doesn't work.
    • -
    - -

    For backward compatibility with older Android releases, you may need to -be aware of:

    -
      -
    • Dynamic lookup of native functions -

      Until Android 2.0 (Eclair), the '$' character was not properly - converted to "_00024" during searches for method names. Working - around this requires using explicit registration or moving the - native methods out of inner classes. -

    • Detaching threads -

      Until Android 2.0 (Eclair), it was not possible to use a pthread_key_create - destructor function to avoid the "thread must be detached before - exit" check. (The runtime also uses a pthread key destructor function, - so it'd be a race to see which gets called first.) -

    • Weak global references -

      Until Android 2.2 (Froyo), weak global references were not implemented. - Older versions will vigorously reject attempts to use them. You can use - the Android platform version constants to test for support. -

      Until Android 4.0 (Ice Cream Sandwich), weak global references could only - be passed to NewLocalRef, NewGlobalRef, and - DeleteWeakGlobalRef. (The spec strongly encourages - programmers to create hard references to weak globals before doing - anything with them, so this should not be at all limiting.) -

      From Android 4.0 (Ice Cream Sandwich) on, weak global references can be - used like any other JNI references.

    • -
    • Local references -

      Until Android 4.0 (Ice Cream Sandwich), local references were - actually direct pointers. Ice Cream Sandwich added the indirection - necessary to support better garbage collectors, but this means that lots - of JNI bugs are undetectable on older releases. See - JNI Local Reference Changes in ICS for more details. -

    • Determining reference type with GetObjectRefType -

      Until Android 4.0 (Ice Cream Sandwich), as a consequence of the use of - direct pointers (see above), it was impossible to implement - GetObjectRefType correctly. Instead we used a heuristic - that looked through the weak globals table, the arguments, the locals - table, and the globals table in that order. The first time it found your - direct pointer, it would report that your reference was of the type it - happened to be examining. This meant, for example, that if - you called GetObjectRefType on a global jclass that happened - to be the same as the jclass passed as an implicit argument to your static - native method, you'd get JNILocalRefType rather than - JNIGlobalRefType. -

    - - - -

    FAQ: Why do I get UnsatisfiedLinkError?

    - -

    When working on native code it's not uncommon to see a failure like this:

    -
    java.lang.UnsatisfiedLinkError: Library foo not found
    - -

    In some cases it means what it says — the library wasn't found. In -other cases the library exists but couldn't be opened by dlopen(3), and -the details of the failure can be found in the exception's detail message.

    - -

    Common reasons why you might encounter "library not found" exceptions:

    -
      -
    • The library doesn't exist or isn't accessible to the app. Use - adb shell ls -l <path> to check its presence - and permissions. -
    • The library wasn't built with the NDK. This can result in - dependencies on functions or libraries that don't exist on the device. -
    - -

    Another class of UnsatisfiedLinkError failures looks like:

    -
    java.lang.UnsatisfiedLinkError: myfunc
    -        at Foo.myfunc(Native Method)
    -        at Foo.main(Foo.java:10)
    - -

    In logcat, you'll see:

    -
    W/dalvikvm(  880): No implementation found for native LFoo;.myfunc ()V
    - -

    This means that the runtime tried to find a matching method but was -unsuccessful. Some common reasons for this are:

    -
      -
    • The library isn't getting loaded. Check the logcat output for - messages about library loading. -
    • The method isn't being found due to a name or signature mismatch. This - is commonly caused by: -
        -
      • For lazy method lookup, failing to declare C++ functions - with extern "C" and appropriate - visibility (JNIEXPORT). Note that prior to Ice Cream - Sandwich, the JNIEXPORT macro was incorrect, so using a new GCC with - an old jni.h won't work. - You can use arm-eabi-nm - to see the symbols as they appear in the library; if they look - mangled (something like _Z15Java_Foo_myfuncP7_JNIEnvP7_jclass - rather than Java_Foo_myfunc), or if the symbol type is - a lowercase 't' rather than an uppercase 'T', then you need to - adjust the declaration. -
      • For explicit registration, minor errors when entering the - method signature. Make sure that what you're passing to the - registration call matches the signature in the log file. - Remember that 'B' is byte and 'Z' is boolean. - Class name components in signatures start with 'L', end with ';', - use '/' to separate package/class names, and use '$' to separate - inner-class names (Ljava/util/Map$Entry;, say). -
      -
    - -

    Using javah to automatically generate JNI headers may help -avoid some problems. - - - -

    FAQ: Why didn't FindClass find my class?

    - -

    Make sure that the class name string has the correct format. JNI class -names start with the package name and are separated with slashes, -such as java/lang/String. If you're looking up an array class, -you need to start with the appropriate number of square brackets and -must also wrap the class with 'L' and ';', so a one-dimensional array of -String would be [Ljava/lang/String;.

    - -

    If the class name looks right, you could be running into a class loader -issue. FindClass wants to start the class search in the -class loader associated with your code. It examines the call stack, -which will look something like: -

        Foo.myfunc(Native Method)
    -    Foo.main(Foo.java:10)
    -    dalvik.system.NativeStart.main(Native Method)
    - -

    The topmost method is Foo.myfunc. FindClass -finds the ClassLoader object associated with the Foo -class and uses that.

    - -

    This usually does what you want. You can get into trouble if you -create a thread yourself (perhaps by calling pthread_create -and then attaching it with AttachCurrentThread). -Now the stack trace looks like this:

    -
        dalvik.system.NativeStart.run(Native Method)
    - -

    The topmost method is NativeStart.run, which isn't part of -your application. If you call FindClass from this thread, the -JavaVM will start in the "system" class loader instead of the one associated -with your application, so attempts to find app-specific classes will fail.

    - -

    There are a few ways to work around this:

    -
      -
    • Do your FindClass lookups once, in - JNI_OnLoad, and cache the class references for later - use. Any FindClass calls made as part of executing - JNI_OnLoad will use the class loader associated with - the function that called System.loadLibrary (this is a - special rule, provided to make library initialization more convenient). - If your app code is loading the library, FindClass - will use the correct class loader. -
    • Pass an instance of the class into the functions that need - it, by declaring your native method to take a Class argument and - then passing Foo.class in. -
    • Cache a reference to the ClassLoader object somewhere - handy, and issue loadClass calls directly. This requires - some effort. -
    - - - -

    FAQ: How do I share raw data with native code?

    - -

    You may find yourself in a situation where you need to access a large -buffer of raw data from both managed and native code. Common examples -include manipulation of bitmaps or sound samples. There are two -basic approaches.

    - -

    You can store the data in a byte[]. This allows very fast -access from managed code. On the native side, however, you're -not guaranteed to be able to access the data without having to copy it. In -some implementations, GetByteArrayElements and -GetPrimitiveArrayCritical will return actual pointers to the -raw data in the managed heap, but in others it will allocate a buffer -on the native heap and copy the data over.

    - -

    The alternative is to store the data in a direct byte buffer. These -can be created with java.nio.ByteBuffer.allocateDirect, or -the JNI NewDirectByteBuffer function. Unlike regular -byte buffers, the storage is not allocated on the managed heap, and can -always be accessed directly from native code (get the address -with GetDirectBufferAddress). Depending on how direct -byte buffer access is implemented, accessing the data from managed code -can be very slow.

    - -

    The choice of which to use depends on two factors:

    -
      -
    1. Will most of the data accesses happen from code written in Java - or in C/C++? -
    2. If the data is eventually being passed to a system API, what form - must it be in? (For example, if the data is eventually passed to a - function that takes a byte[], doing processing in a direct - ByteBuffer might be unwise.) -
    - -

    If there's no clear winner, use a direct byte buffer. Support for them -is built directly into JNI, and performance should improve in future releases.

    diff --git a/docs/html/guide/practices/design/performance.jd b/docs/html/guide/practices/design/performance.jd deleted file mode 100644 index dd9b55407edd..000000000000 --- a/docs/html/guide/practices/design/performance.jd +++ /dev/null @@ -1,410 +0,0 @@ -page.title=Designing for Performance -@jd:body - - - -

    An Android application will run on a mobile device with limited computing -power and storage, and constrained battery life. Because of -this, it should be efficient. Battery life is one reason you might -want to optimize your app even if it already seems to run "fast enough". -Battery life is important to users, and Android's battery usage breakdown -means users will know if your app is responsible draining their battery.

    - -

    Note that although this document primarily covers micro-optimizations, -these will almost never make or break your software. Choosing the right -algorithms and data structures should always be your priority, but is -outside the scope of this document.

    - - -

    Introduction

    - -

    There are two basic rules for writing efficient code:

    -
      -
    • Don't do work that you don't need to do.
    • -
    • Don't allocate memory if you can avoid it.
    • -
    - -

    Optimize Judiciously

    - -

    This document is about Android-specific micro-optimization, so it assumes -that you've already used profiling to work out exactly what code needs to be -optimized, and that you already have a way to measure the effect (good or bad) -of any changes you make. You only have so much engineering time to invest, so -it's important to know you're spending it wisely. - -

    (See Closing Notes for more on profiling and -writing effective benchmarks.) - -

    This document also assumes that you made the best decisions about data -structures and algorithms, and that you've also considered the future -performance consequences of your API decisions. Using the right data -structures and algorithms will make more difference than any of the advice -here, and considering the performance consequences of your API decisions will -make it easier to switch to better implementations later (this is more -important for library code than for application code). - -

    (If you need that kind of advice, see Josh Bloch's Effective Java, -item 47.)

    - -

    One of the trickiest problems you'll face when micro-optimizing an Android -app is that your app is pretty much guaranteed to be running on multiple -hardware platforms. Different versions of the VM running on different -processors running at different speeds. It's not even generally the case -that you can simply say "device X is a factor F faster/slower than device Y", -and scale your results from one device to others. In particular, measurement -on the emulator tells you very little about performance on any device. There -are also huge differences between devices with and without a JIT: the "best" -code for a device with a JIT is not always the best code for a device -without.

    - -

    If you want to know how your app performs on a given device, you need to -test on that device.

    - - -

    Avoid Creating Unnecessary Objects

    - -

    Object creation is never free. A generational GC with per-thread allocation -pools for temporary objects can make allocation cheaper, but allocating memory -is always more expensive than not allocating memory.

    - -

    If you allocate objects in a user interface loop, you will force a periodic -garbage collection, creating little "hiccups" in the user experience. The -concurrent collector introduced in Gingerbread helps, but unnecessary work -should always be avoided.

    - -

    Thus, you should avoid creating object instances you don't need to. Some -examples of things that can help:

    - -
      -
    • If you have a method returning a string, and you know that its result - will always be appended to a StringBuffer anyway, change your signature - and implementation so that the function does the append directly, - instead of creating a short-lived temporary object.
    • -
    • When extracting strings from a set of input data, try - to return a substring of the original data, instead of creating a copy. - You will create a new String object, but it will share the char[] - with the data. (The trade-off being that if you're only using a small - part of the original input, you'll be keeping it all around in memory - anyway if you go this route.)
    • -
    - -

    A somewhat more radical idea is to slice up multidimensional arrays into -parallel single one-dimension arrays:

    - -
      -
    • An array of ints is a much better than an array of Integers, - but this also generalizes to the fact that two parallel arrays of ints - are also a lot more efficient than an array of (int,int) - objects. The same goes for any combination of primitive types.
    • -
    • If you need to implement a container that stores tuples of (Foo,Bar) - objects, try to remember that two parallel Foo[] and Bar[] arrays are - generally much better than a single array of custom (Foo,Bar) objects. - (The exception to this, of course, is when you're designing an API for - other code to access; in those cases, it's usually better to trade - good API design for a small hit in speed. But in your own internal - code, you should try and be as efficient as possible.)
    • -
    - -

    Generally speaking, avoid creating short-term temporary objects if you -can. Fewer objects created mean less-frequent garbage collection, which has -a direct impact on user experience.

    - - - -

    Performance Myths

    - -

    Previous versions of this document made various misleading claims. We -address some of them here.

    - -

    On devices without a JIT, it is true that invoking methods via a -variable with an exact type rather than an interface is slightly more -efficient. (So, for example, it was cheaper to invoke methods on a -HashMap map than a Map map, even though in both -cases the map was a HashMap.) It was not the case that this -was 2x slower; the actual difference was more like 6% slower. Furthermore, -the JIT makes the two effectively indistinguishable.

    - -

    On devices without a JIT, caching field accesses is about 20% faster than -repeatedly accesssing the field. With a JIT, field access costs about the same -as local access, so this isn't a worthwhile optimization unless you feel it -makes your code easier to read. (This is true of final, static, and static -final fields too.) - - -

    Prefer Static Over Virtual

    - -

    If you don't need to access an object's fields, make your method static. -Invocations will be about 15%-20% faster. -It's also good practice, because you can tell from the method -signature that calling the method can't alter the object's state.

    - - -

    Avoid Internal Getters/Setters

    - -

    In native languages like C++ it's common practice to use getters (e.g. -i = getCount()) instead of accessing the field directly (i -= mCount). This is an excellent habit for C++, because the compiler can -usually inline the access, and if you need to restrict or debug field access -you can add the code at any time.

    - -

    On Android, this is a bad idea. Virtual method calls are expensive, -much more so than instance field lookups. It's reasonable to follow -common object-oriented programming practices and have getters and setters -in the public interface, but within a class you should always access -fields directly.

    - -

    Without a JIT, direct field access is about 3x faster than invoking a -trivial getter. With the JIT (where direct field access is as cheap as -accessing a local), direct field access is about 7x faster than invoking a -trivial getter. This is true in Froyo, but will improve in the future when -the JIT inlines getter methods.

    - -

    Note that if you're using ProGuard, you can have the best -of both worlds because ProGuard can inline accessors for you.

    - - -

    Use Static Final For Constants

    - -

    Consider the following declaration at the top of a class:

    - -
    static int intVal = 42;
    -static String strVal = "Hello, world!";
    - -

    The compiler generates a class initializer method, called -<clinit>, that is executed when the class is first used. -The method stores the value 42 into intVal, and extracts a -reference from the classfile string constant table for strVal. -When these values are referenced later on, they are accessed with field -lookups.

    - -

    We can improve matters with the "final" keyword:

    - -
    static final int intVal = 42;
    -static final String strVal = "Hello, world!";
    - -

    The class no longer requires a <clinit> method, -because the constants go into static field initializers in the dex file. -Code that refers to intVal will use -the integer value 42 directly, and accesses to strVal will -use a relatively inexpensive "string constant" instruction instead of a -field lookup. (Note that this optimization only applies to primitive types and -String constants, not arbitrary reference types. Still, it's good -practice to declare constants static final whenever possible.)

    - - -

    Use Enhanced For Loop Syntax

    - -

    The enhanced for loop (also sometimes known as "for-each" loop) can be used -for collections that implement the Iterable interface and for arrays. -With collections, an iterator is allocated to make interface calls -to hasNext() and next(). With an ArrayList, a hand-written counted loop is -about 3x faster (with or without JIT), but for other collections the enhanced -for loop syntax will be exactly equivalent to explicit iterator usage.

    - -

    There are several alternatives for iterating through an array:

    - -
        static class Foo {
    -        int mSplat;
    -    }
    -    Foo[] mArray = ...
    -
    -    public void zero() {
    -        int sum = 0;
    -        for (int i = 0; i < mArray.length; ++i) {
    -            sum += mArray[i].mSplat;
    -        }
    -    }
    -
    -    public void one() {
    -        int sum = 0;
    -        Foo[] localArray = mArray;
    -        int len = localArray.length;
    -
    -        for (int i = 0; i < len; ++i) {
    -            sum += localArray[i].mSplat;
    -        }
    -    }
    -
    -    public void two() {
    -        int sum = 0;
    -        for (Foo a : mArray) {
    -            sum += a.mSplat;
    -        }
    -    }
    -
    - -

    zero() is slowest, because the JIT can't yet optimize away -the cost of getting the array length once for every iteration through the -loop.

    - -

    one() is faster. It pulls everything out into local -variables, avoiding the lookups. Only the array length offers a performance -benefit.

    - -

    two() is fastest for devices without a JIT, and -indistinguishable from one() for devices with a JIT. -It uses the enhanced for loop syntax introduced in version 1.5 of the Java -programming language.

    - -

    To summarize: use the enhanced for loop by default, but consider a -hand-written counted loop for performance-critical ArrayList iteration.

    - -

    (See also Effective Java item 46.)

    - - -

    Consider Package Instead of Private Access with Private Inner Classes

    - -

    Consider the following class definition:

    - -
    public class Foo {
    -    private class Inner {
    -        void stuff() {
    -            Foo.this.doStuff(Foo.this.mValue);
    -        }
    -    }
    -
    -    private int mValue;
    -
    -    public void run() {
    -        Inner in = new Inner();
    -        mValue = 27;
    -        in.stuff();
    -    }
    -
    -    private void doStuff(int value) {
    -        System.out.println("Value is " + value);
    -    }
    -}
    - -

    The key things to note here are that we define a private inner class -(Foo$Inner) that directly accesses a private method and a private -instance field in the outer class. This is legal, and the code prints "Value is -27" as expected.

    - -

    The problem is that the VM considers direct access to Foo's -private members from Foo$Inner to be illegal because -Foo and Foo$Inner are different classes, even though -the Java language allows an inner class to access an outer class' private -members. To bridge the gap, the compiler generates a couple of synthetic -methods:

    - -
    /*package*/ static int Foo.access$100(Foo foo) {
    -    return foo.mValue;
    -}
    -/*package*/ static void Foo.access$200(Foo foo, int value) {
    -    foo.doStuff(value);
    -}
    - -

    The inner class code calls these static methods whenever it needs to -access the mValue field or invoke the doStuff method -in the outer class. What this means is that the code above really boils down to -a case where you're accessing member fields through accessor methods. -Earlier we talked about how accessors are slower than direct field -accesses, so this is an example of a certain language idiom resulting in an -"invisible" performance hit.

    - -

    If you're using code like this in a performance hotspot, you can avoid the -overhead by declaring fields and methods accessed by inner classes to have -package access, rather than private access. Unfortunately this means the fields -can be accessed directly by other classes in the same package, so you shouldn't -use this in public API.

    - - -

    Use Floating-Point Judiciously

    - -

    As a rule of thumb, floating-point is about 2x slower than integer on -Android devices. This is true on a FPU-less, JIT-less G1 and a Nexus One with -an FPU and the JIT. (Of course, absolute speed difference between those two -devices is about 10x for arithmetic operations.)

    - -

    In speed terms, there's no difference between float and -double on the more modern hardware. Space-wise, double -is 2x larger. As with desktop machines, assuming space isn't an issue, you -should prefer double to float.

    - -

    Also, even for integers, some chips have hardware multiply but lack -hardware divide. In such cases, integer division and modulus operations are -performed in software — something to think about if you're designing a -hash table or doing lots of math.

    - - -

    Know And Use The Libraries

    - -

    In addition to all the usual reasons to prefer library code over rolling -your own, bear in mind that the system is at liberty to replace calls -to library methods with hand-coded assembler, which may be better than the -best code the JIT can produce for the equivalent Java. The typical example -here is String.indexOf and friends, which Dalvik replaces with -an inlined intrinsic. Similarly, the System.arraycopy method -is about 9x faster than a hand-coded loop on a Nexus One with the JIT.

    - -

    (See also Effective Java item 47.)

    - - -

    Use Native Methods Judiciously

    - -

    Native code isn't necessarily more efficient than Java. For one thing, -there's a cost associated with the Java-native transition, and the JIT can't -optimize across these boundaries. If you're allocating native resources (memory -on the native heap, file descriptors, or whatever), it can be significantly -more difficult to arrange timely collection of these resources. You also -need to compile your code for each architecture you wish to run on (rather -than rely on it having a JIT). You may even have to compile multiple versions -for what you consider the same architecture: native code compiled for the ARM -processor in the G1 can't take full advantage of the ARM in the Nexus One, and -code compiled for the ARM in the Nexus One won't run on the ARM in the G1.

    - -

    Native code is primarily useful when you have an existing native codebase -that you want to port to Android, not for "speeding up" parts of a Java app.

    - -

    If you do need to use native code, you should read our -JNI Tips.

    - -

    (See also Effective Java item 54.)

    - - -

    Closing Notes

    - -

    One last thing: always measure. Before you start optimizing, make sure you -have a problem. Make sure you can accurately measure your existing performance, -or you won't be able to measure the benefit of the alternatives you try.

    - -

    Every claim made in this document is backed up by a benchmark. The source -to these benchmarks can be found in the code.google.com "dalvik" project.

    - -

    The benchmarks are built with the -Caliper microbenchmarking -framework for Java. Microbenchmarks are hard to get right, so Caliper goes out -of its way to do the hard work for you, and even detect some cases where you're -not measuring what you think you're measuring (because, say, the VM has -managed to optimize all your code away). We highly recommend you use Caliper -to run your own microbenchmarks.

    - -

    You may also find -Traceview useful -for profiling, but it's important to realize that it currently disables the JIT, -which may cause it to misattribute time to code that the JIT may be able to win -back. It's especially important after making changes suggested by Traceview -data to ensure that the resulting code actually runs faster when run without -Traceview. diff --git a/docs/html/guide/practices/design/responsiveness.jd b/docs/html/guide/practices/design/responsiveness.jd deleted file mode 100644 index a00e3aa65114..000000000000 --- a/docs/html/guide/practices/design/responsiveness.jd +++ /dev/null @@ -1,140 +0,0 @@ -page.title=Designing for Responsiveness -@jd:body - -

    - -
    - -
    -Screenshot of ANR dialog box -

    Figure 1. An ANR dialog displayed to the user.

    -
    - -

    It's possible to write code that wins every performance test in the world, -but still sends users in a fiery rage when they try to use the application. -These are the applications that aren't responsive enough — the -ones that feel sluggish, hang or freeze for significant periods, or take too -long to process input.

    - -

    In Android, the system guards against applications that are insufficiently -responsive for a period of time by displaying a dialog to the user, called the -Application Not Responding (ANR) dialog, shown at right in Figure 1. The user -can choose to let the application continue, but the user won't appreciate having -to act on this dialog every time he or she uses your application. It's critical -to design responsiveness into your application, so that the system never has -cause to display an ANR dialog to the user.

    - -

    Generally, the system displays an ANR if an application cannot respond to -user input. For example, if an application blocks on some I/O operation -(frequently a network access), then the main application thread won't be able to -process incoming user input events. After a time, the system concludes that the -application is frozen, and displays the ANR to give the user the option to kill -it.

    - -

    Similarly, if your application spends too much time building an elaborate in-memory -structure, or perhaps computing the next move in a game, the system will -conclude that your application has hung. It's always important to make -sure these computations are efficient using the techniques above, but even the -most efficient code still takes time to run.

    - -

    In both of these cases, the recommended approach is to create a child thread and do -most of your work there. This keeps the main thread (which drives the user -interface event loop) running and prevents the system from concluding that your code -has frozen. Since such threading usually is accomplished at the class -level, you can think of responsiveness as a class problem. (Compare -this with basic performance, which was described above as a method-level -concern.)

    - -

    This document describes how the Android system determines whether an -application is not responding and provides guidelines for ensuring that your -application stays responsive.

    - -

    What Triggers ANR?

    - -

    In Android, application responsiveness is monitored by the Activity Manager -and Window Manager system services. Android will display the ANR dialog -for a particular application when it detects one of the following -conditions:

    -
      -
    • No response to an input event (e.g. key press, screen touch) - within 5 seconds
    • -
    • A {@link android.content.BroadcastReceiver BroadcastReceiver} - hasn't finished executing within 10 seconds
    • -
    - -

    How to Avoid ANR

    - -

    Given the above definition for ANR, let's examine why this can occur in -Android applications and how best to structure your application to avoid ANR.

    - -

    Android applications normally run entirely on a single (i.e. main) thread. -This means that anything your application is doing in the main thread that -takes a long time to complete can trigger the ANR dialog because your -application is not giving itself a chance to handle the input event or Intent -broadcast.

    - -

    Therefore any method that runs in the main thread should do as little work -as possible. In particular, Activities should do as little as possible to set -up in key life-cycle methods such as onCreate() and -onResume(). Potentially long running operations such as network -or database operations, or computationally expensive calculations such as -resizing bitmaps should be done in a child thread (or in the case of databases -operations, via an asynchronous request). However, this does not mean that -your main thread should block while waiting for the child thread to -complete — nor should you call Thread.wait() or -Thread.sleep(). Instead of blocking while waiting for a child -thread to complete, your main thread should provide a {@link -android.os.Handler Handler} for child threads to post back to upon completion. -Designing your application in this way will allow your main thread to remain -responsive to input and thus avoid ANR dialogs caused by the 5 second input -event timeout. These same practices should be followed for any other threads -that display UI, as they are also subject to the same timeouts.

    - -

    You can use {@link android.os.StrictMode} to help find potentially -long running operations such as network or database operations that -you might accidentally be doing your main thread.

    - -

    The specific constraint on IntentReceiver execution time emphasizes what -they were meant to do: small, discrete amounts of work in the background such -as saving a setting or registering a Notification. So as with other methods -called in the main thread, applications should avoid potentially long-running -operations or calculations in BroadcastReceivers. But instead of doing intensive -tasks via child threads (as the life of a BroadcastReceiver is short), your -application should start a {@link android.app.Service Service} if a -potentially long running action needs to be taken in response to an Intent -broadcast. As a side note, you should also avoid starting an Activity from an -Intent Receiver, as it will spawn a new screen that will steal focus from -whatever application the user is currently has running. If your application -has something to show the user in response to an Intent broadcast, it should -do so using the {@link android.app.NotificationManager Notification -Manager}.

    - -

    Reinforcing Responsiveness

    - -

    Generally, 100 to 200ms is the threshold beyond which users will perceive -lag (or lack of "snappiness," if you will) in an application. As such, here -are some additional tips beyond what you should do to avoid ANR that will help -make your application seem responsive to users.

    - -
      -
    • If your application is doing work in the background in response to - user input, show that progress is being made ({@link - android.widget.ProgressBar ProgressBar} and {@link - android.app.ProgressDialog ProgressDialog} are useful for this).
    • -
    • For games specifically, do calculations for moves in a child - thread.
    • -
    • If your application has a time-consuming initial setup phase, consider - showing a splash screen or rendering the main view as quickly as possible - and filling in the information asynchronously. In either case, you should - indicate somehow that progress is being made, lest the user perceive that - the application is frozen.
    • -
    diff --git a/docs/html/guide/practices/design/seamlessness.jd b/docs/html/guide/practices/design/seamlessness.jd deleted file mode 100644 index 6c734264c1a9..000000000000 --- a/docs/html/guide/practices/design/seamlessness.jd +++ /dev/null @@ -1,249 +0,0 @@ -page.title=Designing for Seamlessness -@jd:body - - - -

    Even if your application is fast and responsive, certain design decisions can -still cause problems for users — because of unplanned interactions with -other applications or dialogs, inadvertent loss of data, unintended blocking, -and so on. To avoid these problems, it helps to understand the context in which -your applications run and the system interactions that can affect your -application. In short, you should strive to develop an application that -interacts seamlessly with the system and with other applications.

    - -

    A common seamlessness problem is when an application's background process -— for example, a service or broadcast receiver — pops up a dialog in -response to some event. This may seem like harmless behavior, especially when -you are building and testing your application in isolation, on the emulator. -However, when your application is run on an actual device, your application may -not have user focus at the time your background process displays the dialog. So -it could end up that your application would display it's dialog behind the -active application, or it could take focus from the current application and -display the dialog in front of whatever the user was doing (such as dialing a -phone call, for example). That behavior would not work for your application or -for the user.

    - -

    To avoid these problems, your application should use the proper system -facility for notifying the user — the -{@link android.app.Notification Notification} classes. Using -notifications, your application can signal the user that an event has -taken place, by displaying an icon in the status bar rather than taking -focus and interrupting the user.

    - -

    Another example of a seamlessness problem is when an activity inadvertently -loses state or user data because it doesn't correctly implement the onPause() -and other lifecycle methods. Or, if your application exposes data intended to be -used by other applications, you should expose it via a ContentProvider, rather -than (for example) doing so through a world-readable raw file or database.

    - -

    What those examples have in common is that they involve cooperating nicely -with the system and other applications. The Android system is designed to treat -applications as a sort of federation of loosely-coupled components, rather than -chunks of black-box code. This allows you as the developer to view the entire -system as just an even-larger federation of these components. This benefits you -by allowing you to integrate cleanly and seamlessly with other applications, and -so you should design your own code to return the favor.

    - -

    This document discusses common seamlessness problems and how to avoid them.

    - -

    Don't Drop Data

    - -

    Always keep in mind that Android is a mobile platform. It may seem obvious to -say it, but it's important to remember that another Activity (such as the -"Incoming Phone Call" app) can pop up over your own Activity at any moment. -This will fire the onSaveInstanceState() and onPause() methods, and will likely result in -your application being killed.

    - -

    If the user was editing data in your application when the other Activity -appeared, your application will likely lose that data when your application is -killed. Unless, of course, you save the work in progress first. The "Android -Way" is to do just that: Android applications that accept or edit input should -override the onSaveInstanceState() method and save their state in some appropriate -fashion. When the user revisits the application, she should be able to -retrieve her data.

    - -

    A classic example of a good use of this behavior is a mail application. If the -user was composing an email when another Activity started up, the application -should save the in-process email as a draft.

    - -

    Don't Expose Raw Data

    - -

    If you wouldn't walk down the street in your underwear, neither should your -data. While it's possible to expose certain kinds of application to the world -to read, this is usually not the best idea. Exposing raw data requires other -applications to understand your data format; if you change that format, you'll -break any other applications that aren't similarly updated.

    - -

    The "Android Way" is to create a ContentProvider to expose your data to other -applications via a clean, well-thought-out, and maintainable API. Using a -ContentProvider is much like inserting a Java language interface to split up and -componentize two tightly-coupled pieces of code. This means you'll be able to -modify the internal format of your data without changing the interface exposed -by the ContentProvider, and this without affecting other applications.

    - -

    Don't Interrupt the User

    - -

    If the user is running an application (such as the Phone application during a -call) it's a pretty safe bet he did it on purpose. That's why you should avoid -spawning activities except in direct response to user input from the current -Activity.

    - -

    That is, don't call startActivity() from BroadcastReceivers or Services running in -the background. Doing so will interrupt whatever application is currently -running, and result in an annoyed user. Perhaps even worse, your Activity may -become a "keystroke bandit" and receive some of the input the user was in the -middle of providing to the previous Activity. Depending on what your -application does, this could be bad news.

    - -

    Instead of spawning Activity UIs directly from the background, you should -instead use the NotificationManager to set Notifications. These will appear in -the status bar, and the user can then click on them at his leisure, to see -what your application has to show him.

    - -

    (Note that all this doesn't apply to cases where your own Activity is already -in the foreground: in that case, the user expects to see your next Activity in -response to input.)

    - -

    Got a Lot to Do? Do it in a Thread

    - -

    If your application needs to perform some expensive or long-running -computation, you should probably move it to a thread. This will prevent the -dreaded "Application Not Responding" dialog from being displayed to the user, -with the ultimate result being the fiery demise of your application.

    - -

    By default, all code in an Activity as well as all its Views run in the same -thread. This is the same thread that also handles UI events. For example, when -the user presses a key, a key-down event is added to the Activity's main -thread's queue. The event handler system needs to dequeue and handle that -event quickly; if it doesn't, the system concludes after a few seconds that -the application is hung and offers to kill it for the user.

    - -

    If you have long-running code, running it inline in your Activity will run it -on the event handler thread, effectively blocking the event handler. This will -delay input processing, and result in the ANR dialogs. To avoid this, move -your computations to a thread. This Design for Responsiveness document -discusses how to do that..

    - -

    Don't Overload a Single Activity Screen

    - -

    Any application worth using will probably have several different screens. -When designing the screens of your UI, be sure to make use of multiple Activity -object instances.

    - -

    Depending on your development background, you may interpret an Activity as -similar to something like a Java Applet, in that it is the entry point for -your application. However, that's not quite accurate: where an Applet subclass -is the single entry point for a Java Applet, an Activity should be thought of -as one of potentially several entry points to your application. The only -difference between your "main" Activity and any others you might have is that -the "main" one just happens to be the only one that expressed an interest in -the "android.intent.action.MAIN" action in your AndroidManifest..xml file.

    - -

    So, when designing your application, think of your application as a federation -of Activity objects. This will make your code a lot more maintainable in the long -run, and as a nice side effect also plays nicely with Android's application -history and "backstack" model.

    - -

    Extend System Themes

    - -

    When it comes to the look-and-feel of the user interface, it's important to -blend in nicely. Users are jarred by applications which contrast with the user -interface they've come to expect. When designing your UIs, you should try and -avoid rolling your own as much as possible. Instead, use a Theme. You -can override or extend those parts of the theme that you need to, but at least -you're starting from the same UI base as all the other applications. For all -the details, read Styles and Themes.

    - -

    Design Your UI to Work with Multiple Screen Resolutions

    - -

    Different Android-powered devices will support different screen resolutions. -Some will even be able to change resolutions on the fly, such as by switching -to landscape mode. It's important to make sure your layouts and drawables -are flexible enough to display properly on a variety of device screens.

    - -

    Fortunately, this is very easy to do. In brief, what you must do is -provide different versions of your artwork (if you use any) for the key -resolutions, and then design your layout to accommodate various dimensions. -(For example, avoid using hard-coded positions and instead use relative -layouts.) If you do that much, the system handles the rest, and your -application looks great on any device.

    - -

    Assume the Network is Slow

    - -

    Android devices will come with a variety of network-connectivity options. All -will have some data-access provision, though some will be faster than others. -The lowest common denominator, however, is GPRS, the non-3G data service for -GSM networks. Even 3G-capable devices will spend lots of time on non-3G -networks, so slow networks will remain a reality for quite a long time to -come.

    - -

    That's why you should always code your applications to minimize network -accesses and bandwidth. You can't assume the network is fast, so you should -always plan for it to be slow. If your users happen to be on faster networks, -then that's great — their experience will only improve. You want to avoid the -inverse case though: applications that are usable some of the time, but -frustratingly slow the rest based on where the user is at any given moment are -likely to be unpopular.

    - -

    One potential gotcha here is that it's very easy to fall into this trap if -you're using the emulator, since the emulator uses your desktop computer's -network connection. That's almost guaranteed to be much faster than a cell -network, so you'll want to change the settings on the emulator that simulate -slower network speeds. You can do this in Eclipse, in the "Emulator Settings" -tab of your launch configuration or via a command-line -option when starting the emulator.

    - -

    Don't Assume Touchscreen or Keyboard

    - -

    -Android will support a variety of handset form-factors. That's a fancy way of -saying that some Android devices will have full "QWERTY" keyboards, while -others will have 40-key, 12-key, or even other key configurations. Similarly, -some devices will have touch-screens, but many won't. -

    -When building your applications, keep that in mind. Don't make assumptions -about specific keyboard layouts -- unless, of course, you're really interested -in restricting your application so that it can only be used on those devices. -

    - -

    Do Conserve the Device Battery

    -

    -A mobile device isn't very mobile if it's constantly plugged into the -wall. Mobile devices are battery-powered, and the longer we can make that -battery last on a charge, the happier everyone is — especially the user. -Two of the biggest consumers of battery power are the processor, and the -radio; that's why it's important to write your applications to do as little -work as possible, and use the network as infrequently as possible. -

    -Minimizing the amount of processor time your application uses really comes -down to writing efficient -code. To minimize the power drain from using the radio, be sure to handle -error conditions gracefully, and only fetch what you need. For example, don't -constantly retry a network operation if one failed. If it failed once, it's -likely because the user has no reception, so it's probably going to fail again -if you try right away; all you'll do is waste battery power. -

    -Users are pretty smart: if your program is power-hungry, you can count on -them noticing. The only thing you can be sure of at that point is that your -program won't stay installed very long. -

    diff --git a/docs/html/guide/practices/index.html b/docs/html/guide/practices/index.html deleted file mode 100644 index 4881acf44581..000000000000 --- a/docs/html/guide/practices/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/practices/index.jd b/docs/html/guide/practices/index.jd new file mode 100644 index 000000000000..e218b505159a --- /dev/null +++ b/docs/html/guide/practices/index.jd @@ -0,0 +1,52 @@ +page.title=Best Practices +page.landing=true +page.landing.intro=Design and build apps the right way. Learn how to create apps that look great and perform well on as many devices as possible, from phones to tablets and more. +page.landing.image= + +@jd:body + +
    + +
    +

    Blog Articles

    + + +

    Improving App Quality

    +

    One way of improving your app’s visibility in the ecosystem is by deploying well-targeted +mobile advertising campaigns and cross-app promotions. However, there’s another time-tested method +of fueling the impression-install-ranking cycle: improve the product!

    +
    + + +

    Say Goodbye to the Menu Button

    +

    As Ice Cream Sandwich rolls out to more devices, it?s important that you begin to migrate +your designs to the action bar in order to promote a consistent Android user experience.

    +
    + + +

    New Tools For Managing Screen Sizes

    +

    Android 3.2 includes new tools for supporting devices with a wide range of screen sizes. +One important result is better support for a new size of screen; what is typically called a “7-inch” +tablet. This release also offers several new APIs to simplify developers’ work in adjusting to +different screen sizes.

    +
    + + +

    Identifying App Installations

    +

    It is very common, and perfectly reasonable, for a developer to want to track individual +installations of their apps. It sounds plausible just to call TelephonyManager.getDeviceId() and use +that value to identify the installation. There are problems with this

    +
    + + +

    Making Android Games that Play Nice

    +

    Making a game on Android is easy. Making a great game for a mobile, multitasking, +often multi-core, multi-purpose system like Android is trickier. Even the best developers frequently +make mistakes in the way they interact with the Android system and with other applications

    +
    + +
    + + +
    \ No newline at end of file diff --git a/docs/html/guide/practices/jni.jd b/docs/html/guide/practices/jni.jd new file mode 100644 index 000000000000..ddfa0e3991f5 --- /dev/null +++ b/docs/html/guide/practices/jni.jd @@ -0,0 +1,719 @@ +page.title=JNI Tips +@jd:body + + + +

    JNI is the Java Native Interface. It defines a way for managed code +(written in the Java programming language) to interact with native +code (written in C/C++). It's vendor-neutral, has support for loading code from +dynamic shared libraries, and while cumbersome at times is reasonably efficient.

    + +

    You really should read through the +JNI spec for J2SE 6 +to get a sense for how JNI works and what features are available. Some +aspects of the interface aren't immediately obvious on +first reading, so you may find the next few sections handy. +There's a more detailed JNI Programmer's Guide and Specification.

    + + + +

    JavaVM and JNIEnv

    + +

    JNI defines two key data structures, "JavaVM" and "JNIEnv". Both of these are essentially +pointers to pointers to function tables. (In the C++ version, they're classes with a +pointer to a function table and a member function for each JNI function that indirects through +the table.) The JavaVM provides the "invocation interface" functions, +which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, +but Android only allows one.

    + +

    The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as +the first argument.

    + +

    The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. +If a piece of code has no other way to get its JNIEnv, you should share +the JavaVM, and use GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)

    + +

    The C declarations of JNIEnv and JavaVM are different from the C++ +declarations. The "jni.h" include file provides different typedefs +depending on whether it's included into C or C++. For this reason it's a bad idea to +include JNIEnv arguments in header files included by both languages. (Put another way: if your +header file requires #ifdef __cplusplus, you may have to do some extra work if anything in +that header refers to JNIEnv.)

    + + +

    Threads

    + +

    All threads are Linux threads, scheduled by the kernel. They're usually +started from managed code (using Thread.start), +but they can also be created elsewhere and then attached to the JavaVM. For +example, a thread started with pthread_create can be attached +with the JNI AttachCurrentThread or +AttachCurrentThreadAsDaemon functions. Until a thread is +attached, it has no JNIEnv, and cannot make JNI calls.

    + +

    Attaching a natively-created thread causes a java.lang.Thread +object to be constructed and added to the "main" ThreadGroup, +making it visible to the debugger. Calling AttachCurrentThread +on an already-attached thread is a no-op.

    + +

    Android does not suspend threads executing native code. If +garbage collection is in progress, or the debugger has issued a suspend +request, Android will pause the thread the next time it makes a JNI call.

    + +

    Threads attached through JNI must call +DetachCurrentThread before they exit. +If coding this directly is awkward, in Android 2.0 (Eclair) and higher you +can use pthread_key_create to define a destructor +function that will be called before the thread exits, and +call DetachCurrentThread from there. (Use that +key with pthread_setspecific to store the JNIEnv in +thread-local-storage; that way it'll be passed into your destructor as +the argument.)

    + + + +

    jclass, jmethodID, and jfieldID

    + +

    If you want to access an object's field from native code, you would do the following:

    + +
      +
    • Get the class object reference for the class with FindClass
    • +
    • Get the field ID for the field with GetFieldID
    • +
    • Get the contents of the field with something appropriate, such as +GetIntField
    • +
    + +

    Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just +pointers to internal runtime data structures. Looking them up may require several string +comparisons, but once you have them the actual call to get the field or invoke the method +is very quick.

    + +

    If performance is important, it's useful to look the values up once and cache the results +in your native code. Because there is a limit of one JavaVM per process, it's reasonable +to store this data in a static local structure.

    + +

    The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes +are only unloaded if all classes associated with a ClassLoader can be garbage collected, +which is rare but will not be impossible in Android. Note however that +the jclass +is a class reference and must be protected with a call +to NewGlobalRef (see the next section).

    + +

    If you would like to cache the IDs when a class is loaded, and automatically re-cache them +if the class is ever unloaded and reloaded, the correct way to initialize +the IDs is to add a piece of code that looks like this to the appropriate class:

    + +
        /*
    +     * We use a class initializer to allow the native code to cache some
    +     * field offsets. This native function looks up and caches interesting
    +     * class/field/method IDs. Throws on failure.
    +     */
    +    private static native void nativeInit();
    +
    +    static {
    +        nativeInit();
    +    }
    + +

    Create a nativeClassInit method in your C/C++ code that performs the ID lookups. The code +will be executed once, when the class is initialized. If the class is ever unloaded and +then reloaded, it will be executed again.

    + + +

    Local and Global References

    + +

    Every argument passed to a native method, and almost every object returned +by a JNI function is a "local reference". This means that it's valid for the +duration of the current native method in the current thread. +Even if the object itself continues to live on after the native method +returns, the reference is not valid. +

    This applies to all sub-classes of jobject, including +jclass, jstring, and jarray. +(The runtime will warn you about most reference mis-uses when extended JNI +checks are enabled.)

    +

    The only way to get non-local references is via the functions +NewGlobalRef and NewWeakGlobalRef. + +

    If you want to hold on to a reference for a longer period, you must use +a "global" reference. The NewGlobalRef function takes the +local reference as an argument and returns a global one. +The global reference is guaranteed to be valid until you call +DeleteGlobalRef.

    + +

    This pattern is commonly used when caching a jclass returned +from FindClass, e.g.:

    +
    jclass localClass = env->FindClass("MyClass");
    +jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
    + +

    All JNI methods accept both local and global references as arguments. +It's possible for references to the same object to have different values. +For example, the return values from consecutive calls to +NewGlobalRef on the same object may be different. +To see if two references refer to the same object, +you must use the IsSameObject function. Never compare +references with == in native code.

    + +

    One consequence of this is that you +must not assume object references are constant or unique +in native code. The 32-bit value representing an object may be different +from one invocation of a method to the next, and it's possible that two +different objects could have the same 32-bit value on consecutive calls. Do +not use jobject values as keys.

    + +

    Programmers are required to "not excessively allocate" local references. In practical terms this means +that if you're creating large numbers of local references, perhaps while running through an array of +objects, you should free them manually with +DeleteLocalRef instead of letting JNI do it for you. The +implementation is only required to reserve slots for +16 local references, so if you need more than that you should either delete as you go or use +EnsureLocalCapacity/PushLocalFrame to reserve more.

    + +

    Note that jfieldIDs and jmethodIDs are opaque +types, not object references, and should not be passed to +NewGlobalRef. The raw data +pointers returned by functions like GetStringUTFChars +and GetByteArrayElements are also not objects. (They may be passed +between threads, and are valid until the matching Release call.)

    + +

    One unusual case deserves separate mention. If you attach a native +thread with AttachCurrentThread, the code you are running will +never automatically free local references until the thread detaches. Any local +references you create will have to be deleted manually. In general, any native +code that creates local references in a loop probably needs to do some manual +deletion.

    + + +

    UTF-8 and UTF-16 Strings

    + +

    The Java programming language uses UTF-16. For convenience, JNI provides methods that work with Modified UTF-8 as well. The +modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00. +The nice thing about this is that you can count on having C-style zero-terminated strings, +suitable for use with standard libc string functions. The down side is that you cannot pass +arbitrary UTF-8 data to JNI and expect it to work correctly.

    + +

    If possible, it's usually faster to operate with UTF-16 strings. Android +currently does not require a copy in GetStringChars, whereas +GetStringUTFChars requires an allocation and a conversion to +UTF-8. Note that +UTF-16 strings are not zero-terminated, and \u0000 is allowed, +so you need to hang on to the string length as well as +the jchar pointer.

    + +

    Don't forget to Release the strings you Get. The +string functions return jchar* or jbyte*, which +are C-style pointers to primitive data rather than local references. They +are guaranteed valid until Release is called, which means they are not +released when the native method returns.

    + +

    Data passed to NewStringUTF must be in Modified UTF-8 format. A +common mistake is reading character data from a file or network stream +and handing it to NewStringUTF without filtering it. +Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII +characters or convert them to proper Modified UTF-8 form. If you don't, +the UTF-16 conversion will likely not be what you expect. The extended +JNI checks will scan strings and warn you about invalid data, but they +won't catch everything.

    + + +

    Primitive Arrays

    + +

    JNI provides functions for accessing the contents of array objects. +While arrays of objects must be accessed one entry at a time, arrays of +primitives can be read and written directly as if they were declared in C.

    + +

    To make the interface as efficient as possible without constraining +the VM implementation, the Get<PrimitiveType>ArrayElements +family of calls allows the runtime to either return a pointer to the actual elements, or +allocate some memory and make a copy. Either way, the raw pointer returned +is guaranteed to be valid until the corresponding Release call +is issued (which implies that, if the data wasn't copied, the array object +will be pinned down and can't be relocated as part of compacting the heap). +You must Release every array you Get. Also, if the Get +call fails, you must ensure that your code doesn't try to Release a NULL +pointer later.

    + +

    You can determine whether or not the data was copied by passing in a +non-NULL pointer for the isCopy argument. This is rarely +useful.

    + +

    The Release call takes a mode argument that can +have one of three values. The actions performed by the runtime depend upon +whether it returned a pointer to the actual data or a copy of it:

    + +
      +
    • 0 +
        +
      • Actual: the array object is un-pinned. +
      • Copy: data is copied back. The buffer with the copy is freed. +
      +
    • JNI_COMMIT +
        +
      • Actual: does nothing. +
      • Copy: data is copied back. The buffer with the copy + is not freed. +
      +
    • JNI_ABORT +
        +
      • Actual: the array object is un-pinned. Earlier + writes are not aborted. +
      • Copy: the buffer with the copy is freed; any changes to it are lost. +
      +
    + +

    One reason for checking the isCopy flag is to know if +you need to call Release with JNI_COMMIT +after making changes to an array — if you're alternating between making +changes and executing code that uses the contents of the array, you may be +able to +skip the no-op commit. Another possible reason for checking the flag is for +efficient handling of JNI_ABORT. For example, you might want +to get an array, modify it in place, pass pieces to other functions, and +then discard the changes. If you know that JNI is making a new copy for +you, there's no need to create another "editable" copy. If JNI is passing +you the original, then you do need to make your own copy.

    + +

    It is a common mistake (repeated in example code) to assume that you can skip the Release call if +*isCopy is false. This is not the case. If no copy buffer was +allocated, then the original memory must be pinned down and can't be moved by +the garbage collector.

    + +

    Also note that the JNI_COMMIT flag does not release the array, +and you will need to call Release again with a different flag +eventually.

    + + + +

    Region Calls

    + +

    There is an alternative to calls like Get<Type>ArrayElements +and GetStringChars that may be very helpful when all you want +to do is copy data in or out. Consider the following:

    + +
        jbyte* data = env->GetByteArrayElements(array, NULL);
    +    if (data != NULL) {
    +        memcpy(buffer, data, len);
    +        env->ReleaseByteArrayElements(array, data, JNI_ABORT);
    +    }
    + +

    This grabs the array, copies the first len byte +elements out of it, and then releases the array. Depending upon the +implementation, the Get call will either pin or copy the array +contents. +The code copies the data (for perhaps a second time), then calls Release; in this case +JNI_ABORT ensures there's no chance of a third copy.

    + +

    One can accomplish the same thing more simply:

    +
        env->GetByteArrayRegion(array, 0, len, buffer);
    + +

    This has several advantages:

    +
      +
    • Requires one JNI call instead of 2, reducing overhead. +
    • Doesn't require pinning or extra data copies. +
    • Reduces the risk of programmer error — no risk of forgetting + to call Release after something fails. +
    + +

    Similarly, you can use the Set<Type>ArrayRegion call +to copy data into an array, and GetStringRegion or +GetStringUTFRegion to copy characters out of a +String. + + + +

    Exceptions

    + +

    You must not call most JNI functions while an exception is pending. +Your code is expected to notice the exception (via the function's return value, +ExceptionCheck, or ExceptionOccurred) and return, +or clear the exception and handle it.

    + +

    The only JNI functions that you are allowed to call while an exception is +pending are:

    +
      +
    • DeleteGlobalRef +
    • DeleteLocalRef +
    • DeleteWeakGlobalRef +
    • ExceptionCheck +
    • ExceptionClear +
    • ExceptionDescribe +
    • ExceptionOccurred +
    • MonitorExit +
    • PopLocalFrame +
    • PushLocalFrame +
    • Release<PrimitiveType>ArrayElements +
    • ReleasePrimitiveArrayCritical +
    • ReleaseStringChars +
    • ReleaseStringCritical +
    • ReleaseStringUTFChars +
    + +

    Many JNI calls can throw an exception, but often provide a simpler way +of checking for failure. For example, if NewString returns +a non-NULL value, you don't need to check for an exception. However, if +you call a method (using a function like CallObjectMethod), +you must always check for an exception, because the return value is not +going to be valid if an exception was thrown.

    + +

    Note that exceptions thrown by interpreted code do not unwind native stack +frames, and Android does not yet support C++ exceptions. +The JNI Throw and ThrowNew instructions just +set an exception pointer in the current thread. Upon returning to managed +from native code, the exception will be noted and handled appropriately.

    + +

    Native code can "catch" an exception by calling ExceptionCheck or +ExceptionOccurred, and clear it with +ExceptionClear. As usual, +discarding exceptions without handling them can lead to problems.

    + +

    There are no built-in functions for manipulating the Throwable object +itself, so if you want to (say) get the exception string you will need to +find the Throwable class, look up the method ID for +getMessage "()Ljava/lang/String;", invoke it, and if the result +is non-NULL use GetStringUTFChars to get something you can +hand to printf(3) or equivalent.

    + + + +

    Extended Checking

    + +

    JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.

    + +

    The additional checks include:

    + +
      +
    • Arrays: attempting to allocate a negative-sized array.
    • +
    • Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.
    • +
    • Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
    • +
    • Critical calls: making a JNI call between a “critical” get and its corresponding release.
    • +
    • Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
    • +
    • Exceptions: making a JNI call while there’s an exception pending.
    • +
    • JNIEnv*s: using a JNIEnv* from the wrong thread.
    • +
    • jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
    • +
    • jmethodIDs: using the wrong kind of jmethodID when making a Call*Method JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).
    • +
    • References: using DeleteGlobalRef/DeleteLocalRef on the wrong kind of reference.
    • +
    • Release modes: passing a bad release mode to a release call (something other than 0, JNI_ABORT, or JNI_COMMIT).
    • +
    • Type safety: returning an incompatible type from your native method (returning a StringBuilder from a method declared to return a String, say).
    • +
    • UTF-8: passing an invalid Modified UTF-8 byte sequence to a JNI call.
    • +
    + +

    (Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)

    + +

    There are several ways to enable CheckJNI.

    + +

    If you’re using the emulator, CheckJNI is on by default.

    + +

    If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:

    + +
    adb shell stop
    +adb shell setprop dalvik.vm.checkjni true
    +adb shell start
    + +

    In either of these cases, you’ll see something like this in your logcat output when the runtime starts:

    + +
    D AndroidRuntime: CheckJNI is ON
    + +

    If you have a regular device, you can use the following command:

    + +
    adb shell setprop debug.checkjni 1
    + +

    This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Change the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time an app starts:

    + +
    D Late-enabling CheckJNI
    + + + + + +

    Native Libraries

    + +

    You can load native code from shared libraries with the standard +System.loadLibrary call. The +preferred way to get at your native code is:

    + +
      +
    • Call System.loadLibrary from a static class +initializer. (See the earlier example, where one is used to call +nativeClassInit.) The argument is the "undecorated" +library name, so to load "libfubar.so" you would pass in "fubar".
    • +
    • Provide a native function: jint JNI_OnLoad(JavaVM* vm, void* reserved)
    • +
    • In JNI_OnLoad, register all of your native methods. You +should declare +the methods "static" so the names don't take up space in the symbol table +on the device.
    • +
    + +

    The JNI_OnLoad function should look something like this if +written in C++:

    +
    jint JNI_OnLoad(JavaVM* vm, void* reserved)
    +{
    +    JNIEnv* env;
    +    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
    +        return -1;
    +    }
    +
    +    // Get jclass with env->FindClass.
    +    // Register methods with env->RegisterNatives.
    +
    +    return JNI_VERSION_1_6;
    +}
    + +

    You can also call System.load with the full path name of the +shared library. For Android apps, you may find it useful to get the full +path to the application's private data storage area from the context object.

    + +

    This is the recommended approach, but not the only approach. Explicit +registration is not required, nor is it necessary that you provide a +JNI_OnLoad function. +You can instead use "discovery" of native methods that are named in a +specific way (see the JNI spec for details), though this is less desirable because if a method signature is wrong you won't know +about it until the first time the method is actually used.

    + +

    One other note about JNI_OnLoad: any FindClass +calls you make from there will happen in the context of the class loader +that was used to load the shared library. Normally FindClass +uses the loader associated with the method at the top of the interpreted +stack, or if there isn't one (because the thread was just attached) it uses +the "system" class loader. This makes +JNI_OnLoad a convenient place to look up and cache class +object references.

    + + + +

    64-bit Considerations

    + +

    Android is currently expected to run on 32-bit platforms. In theory it +could be built for a 64-bit system, but that is not a goal at this time. +For the most part this isn't something that you will need to worry about +when interacting with native code, +but it becomes significant if you plan to store pointers to native +structures in integer fields in an object. To support architectures +that use 64-bit pointers, you need to stash your native pointers in a +long field rather than an int. + + + +

    Unsupported Features/Backwards Compatibility

    + +

    All JNI 1.6 features are supported, with the following exception:

    +
      +
    • DefineClass is not implemented. Android does not use + Java bytecodes or class files, so passing in binary class data + doesn't work.
    • +
    + +

    For backward compatibility with older Android releases, you may need to +be aware of:

    +
      +
    • Dynamic lookup of native functions +

      Until Android 2.0 (Eclair), the '$' character was not properly + converted to "_00024" during searches for method names. Working + around this requires using explicit registration or moving the + native methods out of inner classes. +

    • Detaching threads +

      Until Android 2.0 (Eclair), it was not possible to use a pthread_key_create + destructor function to avoid the "thread must be detached before + exit" check. (The runtime also uses a pthread key destructor function, + so it'd be a race to see which gets called first.) +

    • Weak global references +

      Until Android 2.2 (Froyo), weak global references were not implemented. + Older versions will vigorously reject attempts to use them. You can use + the Android platform version constants to test for support. +

      Until Android 4.0 (Ice Cream Sandwich), weak global references could only + be passed to NewLocalRef, NewGlobalRef, and + DeleteWeakGlobalRef. (The spec strongly encourages + programmers to create hard references to weak globals before doing + anything with them, so this should not be at all limiting.) +

      From Android 4.0 (Ice Cream Sandwich) on, weak global references can be + used like any other JNI references.

    • +
    • Local references +

      Until Android 4.0 (Ice Cream Sandwich), local references were + actually direct pointers. Ice Cream Sandwich added the indirection + necessary to support better garbage collectors, but this means that lots + of JNI bugs are undetectable on older releases. See + JNI Local Reference Changes in ICS for more details. +

    • Determining reference type with GetObjectRefType +

      Until Android 4.0 (Ice Cream Sandwich), as a consequence of the use of + direct pointers (see above), it was impossible to implement + GetObjectRefType correctly. Instead we used a heuristic + that looked through the weak globals table, the arguments, the locals + table, and the globals table in that order. The first time it found your + direct pointer, it would report that your reference was of the type it + happened to be examining. This meant, for example, that if + you called GetObjectRefType on a global jclass that happened + to be the same as the jclass passed as an implicit argument to your static + native method, you'd get JNILocalRefType rather than + JNIGlobalRefType. +

    + + + +

    FAQ: Why do I get UnsatisfiedLinkError?

    + +

    When working on native code it's not uncommon to see a failure like this:

    +
    java.lang.UnsatisfiedLinkError: Library foo not found
    + +

    In some cases it means what it says — the library wasn't found. In +other cases the library exists but couldn't be opened by dlopen(3), and +the details of the failure can be found in the exception's detail message.

    + +

    Common reasons why you might encounter "library not found" exceptions:

    +
      +
    • The library doesn't exist or isn't accessible to the app. Use + adb shell ls -l <path> to check its presence + and permissions. +
    • The library wasn't built with the NDK. This can result in + dependencies on functions or libraries that don't exist on the device. +
    + +

    Another class of UnsatisfiedLinkError failures looks like:

    +
    java.lang.UnsatisfiedLinkError: myfunc
    +        at Foo.myfunc(Native Method)
    +        at Foo.main(Foo.java:10)
    + +

    In logcat, you'll see:

    +
    W/dalvikvm(  880): No implementation found for native LFoo;.myfunc ()V
    + +

    This means that the runtime tried to find a matching method but was +unsuccessful. Some common reasons for this are:

    +
      +
    • The library isn't getting loaded. Check the logcat output for + messages about library loading. +
    • The method isn't being found due to a name or signature mismatch. This + is commonly caused by: +
        +
      • For lazy method lookup, failing to declare C++ functions + with extern "C" and appropriate + visibility (JNIEXPORT). Note that prior to Ice Cream + Sandwich, the JNIEXPORT macro was incorrect, so using a new GCC with + an old jni.h won't work. + You can use arm-eabi-nm + to see the symbols as they appear in the library; if they look + mangled (something like _Z15Java_Foo_myfuncP7_JNIEnvP7_jclass + rather than Java_Foo_myfunc), or if the symbol type is + a lowercase 't' rather than an uppercase 'T', then you need to + adjust the declaration. +
      • For explicit registration, minor errors when entering the + method signature. Make sure that what you're passing to the + registration call matches the signature in the log file. + Remember that 'B' is byte and 'Z' is boolean. + Class name components in signatures start with 'L', end with ';', + use '/' to separate package/class names, and use '$' to separate + inner-class names (Ljava/util/Map$Entry;, say). +
      +
    + +

    Using javah to automatically generate JNI headers may help +avoid some problems. + + + +

    FAQ: Why didn't FindClass find my class?

    + +

    Make sure that the class name string has the correct format. JNI class +names start with the package name and are separated with slashes, +such as java/lang/String. If you're looking up an array class, +you need to start with the appropriate number of square brackets and +must also wrap the class with 'L' and ';', so a one-dimensional array of +String would be [Ljava/lang/String;.

    + +

    If the class name looks right, you could be running into a class loader +issue. FindClass wants to start the class search in the +class loader associated with your code. It examines the call stack, +which will look something like: +

        Foo.myfunc(Native Method)
    +    Foo.main(Foo.java:10)
    +    dalvik.system.NativeStart.main(Native Method)
    + +

    The topmost method is Foo.myfunc. FindClass +finds the ClassLoader object associated with the Foo +class and uses that.

    + +

    This usually does what you want. You can get into trouble if you +create a thread yourself (perhaps by calling pthread_create +and then attaching it with AttachCurrentThread). +Now the stack trace looks like this:

    +
        dalvik.system.NativeStart.run(Native Method)
    + +

    The topmost method is NativeStart.run, which isn't part of +your application. If you call FindClass from this thread, the +JavaVM will start in the "system" class loader instead of the one associated +with your application, so attempts to find app-specific classes will fail.

    + +

    There are a few ways to work around this:

    +
      +
    • Do your FindClass lookups once, in + JNI_OnLoad, and cache the class references for later + use. Any FindClass calls made as part of executing + JNI_OnLoad will use the class loader associated with + the function that called System.loadLibrary (this is a + special rule, provided to make library initialization more convenient). + If your app code is loading the library, FindClass + will use the correct class loader. +
    • Pass an instance of the class into the functions that need + it, by declaring your native method to take a Class argument and + then passing Foo.class in. +
    • Cache a reference to the ClassLoader object somewhere + handy, and issue loadClass calls directly. This requires + some effort. +
    + + + +

    FAQ: How do I share raw data with native code?

    + +

    You may find yourself in a situation where you need to access a large +buffer of raw data from both managed and native code. Common examples +include manipulation of bitmaps or sound samples. There are two +basic approaches.

    + +

    You can store the data in a byte[]. This allows very fast +access from managed code. On the native side, however, you're +not guaranteed to be able to access the data without having to copy it. In +some implementations, GetByteArrayElements and +GetPrimitiveArrayCritical will return actual pointers to the +raw data in the managed heap, but in others it will allocate a buffer +on the native heap and copy the data over.

    + +

    The alternative is to store the data in a direct byte buffer. These +can be created with java.nio.ByteBuffer.allocateDirect, or +the JNI NewDirectByteBuffer function. Unlike regular +byte buffers, the storage is not allocated on the managed heap, and can +always be accessed directly from native code (get the address +with GetDirectBufferAddress). Depending on how direct +byte buffer access is implemented, accessing the data from managed code +can be very slow.

    + +

    The choice of which to use depends on two factors:

    +
      +
    1. Will most of the data accesses happen from code written in Java + or in C/C++? +
    2. If the data is eventually being passed to a system API, what form + must it be in? (For example, if the data is eventually passed to a + function that takes a byte[], doing processing in a direct + ByteBuffer might be unwise.) +
    + +

    If there's no clear winner, use a direct byte buffer. Support for them +is built directly into JNI, and performance should improve in future releases.

    diff --git a/docs/html/guide/practices/optimizing-for-3.0.jd b/docs/html/guide/practices/optimizing-for-3.0.jd index d6c621ea4287..65c56744ce6a 100644 --- a/docs/html/guide/practices/optimizing-for-3.0.jd +++ b/docs/html/guide/practices/optimizing-for-3.0.jd @@ -53,7 +53,7 @@ onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />
  • Supporting Tablets and Handsets
  • Compatibility Library
  • +href="{@docRoot}tools/extras/support-library.html">Compatibility Library
  • Google I/O App source code
  • @@ -108,7 +108,7 @@ SDK with the new platform:

    SDK starter package now.)

      -
    1. Launch the Android SDK +
    2. Launch the Android SDK Manager and install the following:
      • SDK Platform Android 3.0
      • @@ -280,15 +280,15 @@ use techniques such as reflection to check for the availability of certain APIs to help you add features from Android 3.0 without requiring you to change your {@code android:minSdkVersion} or build target, we're providing a static library called the Compatibility Library +href="{@docRoot}tools/extras/support-library.html">Compatibility Library (downloadable from the Android SDK Manager).

        This library includes APIs for fragments, loaders, and some updated classes. By +href="{@docRoot}guide/components/fragments.html">fragments, loaders, and some updated classes. By simply adding this library to your Android project, you can use these APIs in your application and remain compatible with Android 1.6. For information about how to get the library and start using it in your application, see the Compatibility Library document.

        +href="{@docRoot}tools/extras/support-library.html">Compatibility Library document.

    @@ -357,7 +357,7 @@ input events. Thus, instead of using one activity to select an article and anoth read the article, the user can select an article and read it all within the same activity.

    For more information, read the Fragments document.

    +href="{@docRoot}guide/components/fragments.html">Fragments document.

    Use new animation APIs for transitions

    @@ -374,7 +374,7 @@ New transformations are made possible with a set of object properties that defin position, orientation, transparency and more.

    For more information, read the Property Animation document.

    +href="{@docRoot}guide/topics/graphics/prop-animation.html">Property Animation document.

    Enable hardware acceleration

    @@ -412,15 +412,15 @@ application, such as drag and drop APIs, new Bluetooth APIs, a system-wide clipb new graphics engine called Renderscript, and more.

    To learn more about the APIs mentioned above and more, see the Android 3.0 Platform document.

    +href="{@docRoot}about/versions/android-3.0.html">Android 3.0 Platform document.

    Look at some samples

    Many of the new features and APIs that are described above and in the Android 3.0 Platform document also have accompanying +href="{@docRoot}about/versions/android-3.0.html#api">Android 3.0 Platform document also have accompanying samples that allow you to preview the effects and can help you understand how to use them. To get -the samples, download them from the SDK repository using the Android SDK Manager. After downloading the samples ("Samples for SDK API 11"), you can find them in <sdk_root>/samples/android-11/. The following list provides links to the browsable source code for some of the samples:

    @@ -474,7 +474,7 @@ android:targetSdkVersion} set to {@code "4"} or higher, then the Android sys application's layout and assets to fit the current device screen, whether the device screen is smaller or larger than the one for which you originally designed your application. As such, you should always test your application on real or virtual devices with various screen sizes +href="{@docRoot}tools/devices/index.html">virtual devices with various screen sizes and densities.

    Although we recommend that you design your application to function properly on multiple @@ -641,7 +641,7 @@ orientation. When the user rotates the screen, the system restarts the current a onCreate()}) in immediate succession. You should design your activity to account for these changes in the lifecycle, so the activity can save and restore its state. You can learn about the necessary lifecycle callback methods and how to save and restore the activity state in the Activities +href="{@docRoot}guide/components/activities.html#Lifecycle">Activities document. If your activity state is more complex and cannot retain it using the normal lifecycle callback methods, you can use alternative techniques described in Handling Runtime Changes.

    diff --git a/docs/html/guide/practices/performance.jd b/docs/html/guide/practices/performance.jd new file mode 100644 index 000000000000..078999becc39 --- /dev/null +++ b/docs/html/guide/practices/performance.jd @@ -0,0 +1,410 @@ +page.title=Designing for Performance +@jd:body + + + +

    An Android application will run on a mobile device with limited computing +power and storage, and constrained battery life. Because of +this, it should be efficient. Battery life is one reason you might +want to optimize your app even if it already seems to run "fast enough". +Battery life is important to users, and Android's battery usage breakdown +means users will know if your app is responsible draining their battery.

    + +

    Note that although this document primarily covers micro-optimizations, +these will almost never make or break your software. Choosing the right +algorithms and data structures should always be your priority, but is +outside the scope of this document.

    + + +

    Introduction

    + +

    There are two basic rules for writing efficient code:

    +
      +
    • Don't do work that you don't need to do.
    • +
    • Don't allocate memory if you can avoid it.
    • +
    + +

    Optimize Judiciously

    + +

    This document is about Android-specific micro-optimization, so it assumes +that you've already used profiling to work out exactly what code needs to be +optimized, and that you already have a way to measure the effect (good or bad) +of any changes you make. You only have so much engineering time to invest, so +it's important to know you're spending it wisely. + +

    (See Closing Notes for more on profiling and +writing effective benchmarks.) + +

    This document also assumes that you made the best decisions about data +structures and algorithms, and that you've also considered the future +performance consequences of your API decisions. Using the right data +structures and algorithms will make more difference than any of the advice +here, and considering the performance consequences of your API decisions will +make it easier to switch to better implementations later (this is more +important for library code than for application code). + +

    (If you need that kind of advice, see Josh Bloch's Effective Java, +item 47.)

    + +

    One of the trickiest problems you'll face when micro-optimizing an Android +app is that your app is pretty much guaranteed to be running on multiple +hardware platforms. Different versions of the VM running on different +processors running at different speeds. It's not even generally the case +that you can simply say "device X is a factor F faster/slower than device Y", +and scale your results from one device to others. In particular, measurement +on the emulator tells you very little about performance on any device. There +are also huge differences between devices with and without a JIT: the "best" +code for a device with a JIT is not always the best code for a device +without.

    + +

    If you want to know how your app performs on a given device, you need to +test on that device.

    + + +

    Avoid Creating Unnecessary Objects

    + +

    Object creation is never free. A generational GC with per-thread allocation +pools for temporary objects can make allocation cheaper, but allocating memory +is always more expensive than not allocating memory.

    + +

    If you allocate objects in a user interface loop, you will force a periodic +garbage collection, creating little "hiccups" in the user experience. The +concurrent collector introduced in Gingerbread helps, but unnecessary work +should always be avoided.

    + +

    Thus, you should avoid creating object instances you don't need to. Some +examples of things that can help:

    + +
      +
    • If you have a method returning a string, and you know that its result + will always be appended to a StringBuffer anyway, change your signature + and implementation so that the function does the append directly, + instead of creating a short-lived temporary object.
    • +
    • When extracting strings from a set of input data, try + to return a substring of the original data, instead of creating a copy. + You will create a new String object, but it will share the char[] + with the data. (The trade-off being that if you're only using a small + part of the original input, you'll be keeping it all around in memory + anyway if you go this route.)
    • +
    + +

    A somewhat more radical idea is to slice up multidimensional arrays into +parallel single one-dimension arrays:

    + +
      +
    • An array of ints is a much better than an array of Integers, + but this also generalizes to the fact that two parallel arrays of ints + are also a lot more efficient than an array of (int,int) + objects. The same goes for any combination of primitive types.
    • +
    • If you need to implement a container that stores tuples of (Foo,Bar) + objects, try to remember that two parallel Foo[] and Bar[] arrays are + generally much better than a single array of custom (Foo,Bar) objects. + (The exception to this, of course, is when you're designing an API for + other code to access; in those cases, it's usually better to trade + good API design for a small hit in speed. But in your own internal + code, you should try and be as efficient as possible.)
    • +
    + +

    Generally speaking, avoid creating short-term temporary objects if you +can. Fewer objects created mean less-frequent garbage collection, which has +a direct impact on user experience.

    + + + +

    Performance Myths

    + +

    Previous versions of this document made various misleading claims. We +address some of them here.

    + +

    On devices without a JIT, it is true that invoking methods via a +variable with an exact type rather than an interface is slightly more +efficient. (So, for example, it was cheaper to invoke methods on a +HashMap map than a Map map, even though in both +cases the map was a HashMap.) It was not the case that this +was 2x slower; the actual difference was more like 6% slower. Furthermore, +the JIT makes the two effectively indistinguishable.

    + +

    On devices without a JIT, caching field accesses is about 20% faster than +repeatedly accesssing the field. With a JIT, field access costs about the same +as local access, so this isn't a worthwhile optimization unless you feel it +makes your code easier to read. (This is true of final, static, and static +final fields too.) + + +

    Prefer Static Over Virtual

    + +

    If you don't need to access an object's fields, make your method static. +Invocations will be about 15%-20% faster. +It's also good practice, because you can tell from the method +signature that calling the method can't alter the object's state.

    + + +

    Avoid Internal Getters/Setters

    + +

    In native languages like C++ it's common practice to use getters (e.g. +i = getCount()) instead of accessing the field directly (i += mCount). This is an excellent habit for C++, because the compiler can +usually inline the access, and if you need to restrict or debug field access +you can add the code at any time.

    + +

    On Android, this is a bad idea. Virtual method calls are expensive, +much more so than instance field lookups. It's reasonable to follow +common object-oriented programming practices and have getters and setters +in the public interface, but within a class you should always access +fields directly.

    + +

    Without a JIT, direct field access is about 3x faster than invoking a +trivial getter. With the JIT (where direct field access is as cheap as +accessing a local), direct field access is about 7x faster than invoking a +trivial getter. This is true in Froyo, but will improve in the future when +the JIT inlines getter methods.

    + +

    Note that if you're using ProGuard, you can have the best +of both worlds because ProGuard can inline accessors for you.

    + + +

    Use Static Final For Constants

    + +

    Consider the following declaration at the top of a class:

    + +
    static int intVal = 42;
    +static String strVal = "Hello, world!";
    + +

    The compiler generates a class initializer method, called +<clinit>, that is executed when the class is first used. +The method stores the value 42 into intVal, and extracts a +reference from the classfile string constant table for strVal. +When these values are referenced later on, they are accessed with field +lookups.

    + +

    We can improve matters with the "final" keyword:

    + +
    static final int intVal = 42;
    +static final String strVal = "Hello, world!";
    + +

    The class no longer requires a <clinit> method, +because the constants go into static field initializers in the dex file. +Code that refers to intVal will use +the integer value 42 directly, and accesses to strVal will +use a relatively inexpensive "string constant" instruction instead of a +field lookup. (Note that this optimization only applies to primitive types and +String constants, not arbitrary reference types. Still, it's good +practice to declare constants static final whenever possible.)

    + + +

    Use Enhanced For Loop Syntax

    + +

    The enhanced for loop (also sometimes known as "for-each" loop) can be used +for collections that implement the Iterable interface and for arrays. +With collections, an iterator is allocated to make interface calls +to hasNext() and next(). With an ArrayList, a hand-written counted loop is +about 3x faster (with or without JIT), but for other collections the enhanced +for loop syntax will be exactly equivalent to explicit iterator usage.

    + +

    There are several alternatives for iterating through an array:

    + +
        static class Foo {
    +        int mSplat;
    +    }
    +    Foo[] mArray = ...
    +
    +    public void zero() {
    +        int sum = 0;
    +        for (int i = 0; i < mArray.length; ++i) {
    +            sum += mArray[i].mSplat;
    +        }
    +    }
    +
    +    public void one() {
    +        int sum = 0;
    +        Foo[] localArray = mArray;
    +        int len = localArray.length;
    +
    +        for (int i = 0; i < len; ++i) {
    +            sum += localArray[i].mSplat;
    +        }
    +    }
    +
    +    public void two() {
    +        int sum = 0;
    +        for (Foo a : mArray) {
    +            sum += a.mSplat;
    +        }
    +    }
    +
    + +

    zero() is slowest, because the JIT can't yet optimize away +the cost of getting the array length once for every iteration through the +loop.

    + +

    one() is faster. It pulls everything out into local +variables, avoiding the lookups. Only the array length offers a performance +benefit.

    + +

    two() is fastest for devices without a JIT, and +indistinguishable from one() for devices with a JIT. +It uses the enhanced for loop syntax introduced in version 1.5 of the Java +programming language.

    + +

    To summarize: use the enhanced for loop by default, but consider a +hand-written counted loop for performance-critical ArrayList iteration.

    + +

    (See also Effective Java item 46.)

    + + +

    Consider Package Instead of Private Access with Private Inner Classes

    + +

    Consider the following class definition:

    + +
    public class Foo {
    +    private class Inner {
    +        void stuff() {
    +            Foo.this.doStuff(Foo.this.mValue);
    +        }
    +    }
    +
    +    private int mValue;
    +
    +    public void run() {
    +        Inner in = new Inner();
    +        mValue = 27;
    +        in.stuff();
    +    }
    +
    +    private void doStuff(int value) {
    +        System.out.println("Value is " + value);
    +    }
    +}
    + +

    The key things to note here are that we define a private inner class +(Foo$Inner) that directly accesses a private method and a private +instance field in the outer class. This is legal, and the code prints "Value is +27" as expected.

    + +

    The problem is that the VM considers direct access to Foo's +private members from Foo$Inner to be illegal because +Foo and Foo$Inner are different classes, even though +the Java language allows an inner class to access an outer class' private +members. To bridge the gap, the compiler generates a couple of synthetic +methods:

    + +
    /*package*/ static int Foo.access$100(Foo foo) {
    +    return foo.mValue;
    +}
    +/*package*/ static void Foo.access$200(Foo foo, int value) {
    +    foo.doStuff(value);
    +}
    + +

    The inner class code calls these static methods whenever it needs to +access the mValue field or invoke the doStuff method +in the outer class. What this means is that the code above really boils down to +a case where you're accessing member fields through accessor methods. +Earlier we talked about how accessors are slower than direct field +accesses, so this is an example of a certain language idiom resulting in an +"invisible" performance hit.

    + +

    If you're using code like this in a performance hotspot, you can avoid the +overhead by declaring fields and methods accessed by inner classes to have +package access, rather than private access. Unfortunately this means the fields +can be accessed directly by other classes in the same package, so you shouldn't +use this in public API.

    + + +

    Use Floating-Point Judiciously

    + +

    As a rule of thumb, floating-point is about 2x slower than integer on +Android devices. This is true on a FPU-less, JIT-less G1 and a Nexus One with +an FPU and the JIT. (Of course, absolute speed difference between those two +devices is about 10x for arithmetic operations.)

    + +

    In speed terms, there's no difference between float and +double on the more modern hardware. Space-wise, double +is 2x larger. As with desktop machines, assuming space isn't an issue, you +should prefer double to float.

    + +

    Also, even for integers, some chips have hardware multiply but lack +hardware divide. In such cases, integer division and modulus operations are +performed in software — something to think about if you're designing a +hash table or doing lots of math.

    + + +

    Know And Use The Libraries

    + +

    In addition to all the usual reasons to prefer library code over rolling +your own, bear in mind that the system is at liberty to replace calls +to library methods with hand-coded assembler, which may be better than the +best code the JIT can produce for the equivalent Java. The typical example +here is String.indexOf and friends, which Dalvik replaces with +an inlined intrinsic. Similarly, the System.arraycopy method +is about 9x faster than a hand-coded loop on a Nexus One with the JIT.

    + +

    (See also Effective Java item 47.)

    + + +

    Use Native Methods Judiciously

    + +

    Native code isn't necessarily more efficient than Java. For one thing, +there's a cost associated with the Java-native transition, and the JIT can't +optimize across these boundaries. If you're allocating native resources (memory +on the native heap, file descriptors, or whatever), it can be significantly +more difficult to arrange timely collection of these resources. You also +need to compile your code for each architecture you wish to run on (rather +than rely on it having a JIT). You may even have to compile multiple versions +for what you consider the same architecture: native code compiled for the ARM +processor in the G1 can't take full advantage of the ARM in the Nexus One, and +code compiled for the ARM in the Nexus One won't run on the ARM in the G1.

    + +

    Native code is primarily useful when you have an existing native codebase +that you want to port to Android, not for "speeding up" parts of a Java app.

    + +

    If you do need to use native code, you should read our +JNI Tips.

    + +

    (See also Effective Java item 54.)

    + + +

    Closing Notes

    + +

    One last thing: always measure. Before you start optimizing, make sure you +have a problem. Make sure you can accurately measure your existing performance, +or you won't be able to measure the benefit of the alternatives you try.

    + +

    Every claim made in this document is backed up by a benchmark. The source +to these benchmarks can be found in the code.google.com "dalvik" project.

    + +

    The benchmarks are built with the +Caliper microbenchmarking +framework for Java. Microbenchmarks are hard to get right, so Caliper goes out +of its way to do the hard work for you, and even detect some cases where you're +not measuring what you think you're measuring (because, say, the VM has +managed to optimize all your code away). We highly recommend you use Caliper +to run your own microbenchmarks.

    + +

    You may also find +Traceview useful +for profiling, but it's important to realize that it currently disables the JIT, +which may cause it to misattribute time to code that the JIT may be able to win +back. It's especially important after making changes suggested by Traceview +data to ensure that the resulting code actually runs faster when run without +Traceview. diff --git a/docs/html/guide/practices/responsiveness.jd b/docs/html/guide/practices/responsiveness.jd new file mode 100644 index 000000000000..a00e3aa65114 --- /dev/null +++ b/docs/html/guide/practices/responsiveness.jd @@ -0,0 +1,140 @@ +page.title=Designing for Responsiveness +@jd:body + +

    + +
    + +
    +Screenshot of ANR dialog box +

    Figure 1. An ANR dialog displayed to the user.

    +
    + +

    It's possible to write code that wins every performance test in the world, +but still sends users in a fiery rage when they try to use the application. +These are the applications that aren't responsive enough — the +ones that feel sluggish, hang or freeze for significant periods, or take too +long to process input.

    + +

    In Android, the system guards against applications that are insufficiently +responsive for a period of time by displaying a dialog to the user, called the +Application Not Responding (ANR) dialog, shown at right in Figure 1. The user +can choose to let the application continue, but the user won't appreciate having +to act on this dialog every time he or she uses your application. It's critical +to design responsiveness into your application, so that the system never has +cause to display an ANR dialog to the user.

    + +

    Generally, the system displays an ANR if an application cannot respond to +user input. For example, if an application blocks on some I/O operation +(frequently a network access), then the main application thread won't be able to +process incoming user input events. After a time, the system concludes that the +application is frozen, and displays the ANR to give the user the option to kill +it.

    + +

    Similarly, if your application spends too much time building an elaborate in-memory +structure, or perhaps computing the next move in a game, the system will +conclude that your application has hung. It's always important to make +sure these computations are efficient using the techniques above, but even the +most efficient code still takes time to run.

    + +

    In both of these cases, the recommended approach is to create a child thread and do +most of your work there. This keeps the main thread (which drives the user +interface event loop) running and prevents the system from concluding that your code +has frozen. Since such threading usually is accomplished at the class +level, you can think of responsiveness as a class problem. (Compare +this with basic performance, which was described above as a method-level +concern.)

    + +

    This document describes how the Android system determines whether an +application is not responding and provides guidelines for ensuring that your +application stays responsive.

    + +

    What Triggers ANR?

    + +

    In Android, application responsiveness is monitored by the Activity Manager +and Window Manager system services. Android will display the ANR dialog +for a particular application when it detects one of the following +conditions:

    +
      +
    • No response to an input event (e.g. key press, screen touch) + within 5 seconds
    • +
    • A {@link android.content.BroadcastReceiver BroadcastReceiver} + hasn't finished executing within 10 seconds
    • +
    + +

    How to Avoid ANR

    + +

    Given the above definition for ANR, let's examine why this can occur in +Android applications and how best to structure your application to avoid ANR.

    + +

    Android applications normally run entirely on a single (i.e. main) thread. +This means that anything your application is doing in the main thread that +takes a long time to complete can trigger the ANR dialog because your +application is not giving itself a chance to handle the input event or Intent +broadcast.

    + +

    Therefore any method that runs in the main thread should do as little work +as possible. In particular, Activities should do as little as possible to set +up in key life-cycle methods such as onCreate() and +onResume(). Potentially long running operations such as network +or database operations, or computationally expensive calculations such as +resizing bitmaps should be done in a child thread (or in the case of databases +operations, via an asynchronous request). However, this does not mean that +your main thread should block while waiting for the child thread to +complete — nor should you call Thread.wait() or +Thread.sleep(). Instead of blocking while waiting for a child +thread to complete, your main thread should provide a {@link +android.os.Handler Handler} for child threads to post back to upon completion. +Designing your application in this way will allow your main thread to remain +responsive to input and thus avoid ANR dialogs caused by the 5 second input +event timeout. These same practices should be followed for any other threads +that display UI, as they are also subject to the same timeouts.

    + +

    You can use {@link android.os.StrictMode} to help find potentially +long running operations such as network or database operations that +you might accidentally be doing your main thread.

    + +

    The specific constraint on IntentReceiver execution time emphasizes what +they were meant to do: small, discrete amounts of work in the background such +as saving a setting or registering a Notification. So as with other methods +called in the main thread, applications should avoid potentially long-running +operations or calculations in BroadcastReceivers. But instead of doing intensive +tasks via child threads (as the life of a BroadcastReceiver is short), your +application should start a {@link android.app.Service Service} if a +potentially long running action needs to be taken in response to an Intent +broadcast. As a side note, you should also avoid starting an Activity from an +Intent Receiver, as it will spawn a new screen that will steal focus from +whatever application the user is currently has running. If your application +has something to show the user in response to an Intent broadcast, it should +do so using the {@link android.app.NotificationManager Notification +Manager}.

    + +

    Reinforcing Responsiveness

    + +

    Generally, 100 to 200ms is the threshold beyond which users will perceive +lag (or lack of "snappiness," if you will) in an application. As such, here +are some additional tips beyond what you should do to avoid ANR that will help +make your application seem responsive to users.

    + +
      +
    • If your application is doing work in the background in response to + user input, show that progress is being made ({@link + android.widget.ProgressBar ProgressBar} and {@link + android.app.ProgressDialog ProgressDialog} are useful for this).
    • +
    • For games specifically, do calculations for moves in a child + thread.
    • +
    • If your application has a time-consuming initial setup phase, consider + showing a splash screen or rendering the main view as quickly as possible + and filling in the information asynchronously. In either case, you should + indicate somehow that progress is being made, lest the user perceive that + the application is frozen.
    • +
    diff --git a/docs/html/guide/practices/screens-distribution.jd b/docs/html/guide/practices/screens-distribution.jd index a7c4a8ee791c..90ac752f7008 100644 --- a/docs/html/guide/practices/screens-distribution.jd +++ b/docs/html/guide/practices/screens-distribution.jd @@ -213,4 +213,4 @@ sizes, especially, is within reason using a single APK, as long as you follow th Supporting Multiple Screens.

    If you need more information about how to publish multiple APKs on Google Play, read Multiple APK Support.

    +href="{@docRoot}guide/google/play/publishing/multiple-apks.html">Multiple APK Support.

    diff --git a/docs/html/guide/practices/screens-support-1.5.jd b/docs/html/guide/practices/screens-support-1.5.jd index 4c6fb99f9397..15f069535df2 100644 --- a/docs/html/guide/practices/screens-support-1.5.jd +++ b/docs/html/guide/practices/screens-support-1.5.jd @@ -59,7 +59,7 @@ below.

    Note: Before you begin, you should first decide whether it's even necessary to support Android 1.5. To see the relative number of devices that are still running Android 1.5, see the Platform Versions +href="http://developer.android.com/about/dashboards/index.html">Platform Versions Dashboard.

    diff --git a/docs/html/guide/practices/screens_support.jd b/docs/html/guide/practices/screens_support.jd index a870b223c6ac..ca29589b4204 100644 --- a/docs/html/guide/practices/screens_support.jd +++ b/docs/html/guide/practices/screens_support.jd @@ -57,7 +57,7 @@ href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResou Providing Alternative Resources
  • Icon Design Guidelines
  • -
  • Managing Virtual Devices
  • +
  • Managing Virtual Devices
  • @@ -1253,7 +1253,7 @@ Manager with a selection of AVDs, for testing various screen configurations.

    to emulate some of the most common screen configurations.

    For more information about creating and using AVDs to test your application, see Managing AVDs with AVD +href="{@docRoot}tools/devices/managing-avds.html">Managing AVDs with AVD Manager.

    @@ -1366,5 +1366,5 @@ the emulator with the -scale option. For example:

    between 0.1 and 3 that represents the desired scaling factor.

    For more information about creating AVDs from the command line, see Managing AVDs from the +href="{@docRoot}tools/devices/managing-avds-cmdline.html">Managing AVDs from the Command Line

    diff --git a/docs/html/guide/practices/seamlessness.jd b/docs/html/guide/practices/seamlessness.jd new file mode 100644 index 000000000000..ec6b7fdff73c --- /dev/null +++ b/docs/html/guide/practices/seamlessness.jd @@ -0,0 +1,249 @@ +page.title=Designing for Seamlessness +@jd:body + + + +

    Even if your application is fast and responsive, certain design decisions can +still cause problems for users — because of unplanned interactions with +other applications or dialogs, inadvertent loss of data, unintended blocking, +and so on. To avoid these problems, it helps to understand the context in which +your applications run and the system interactions that can affect your +application. In short, you should strive to develop an application that +interacts seamlessly with the system and with other applications.

    + +

    A common seamlessness problem is when an application's background process +— for example, a service or broadcast receiver — pops up a dialog in +response to some event. This may seem like harmless behavior, especially when +you are building and testing your application in isolation, on the emulator. +However, when your application is run on an actual device, your application may +not have user focus at the time your background process displays the dialog. So +it could end up that your application would display it's dialog behind the +active application, or it could take focus from the current application and +display the dialog in front of whatever the user was doing (such as dialing a +phone call, for example). That behavior would not work for your application or +for the user.

    + +

    To avoid these problems, your application should use the proper system +facility for notifying the user — the +{@link android.app.Notification Notification} classes. Using +notifications, your application can signal the user that an event has +taken place, by displaying an icon in the status bar rather than taking +focus and interrupting the user.

    + +

    Another example of a seamlessness problem is when an activity inadvertently +loses state or user data because it doesn't correctly implement the onPause() +and other lifecycle methods. Or, if your application exposes data intended to be +used by other applications, you should expose it via a ContentProvider, rather +than (for example) doing so through a world-readable raw file or database.

    + +

    What those examples have in common is that they involve cooperating nicely +with the system and other applications. The Android system is designed to treat +applications as a sort of federation of loosely-coupled components, rather than +chunks of black-box code. This allows you as the developer to view the entire +system as just an even-larger federation of these components. This benefits you +by allowing you to integrate cleanly and seamlessly with other applications, and +so you should design your own code to return the favor.

    + +

    This document discusses common seamlessness problems and how to avoid them.

    + +

    Don't Drop Data

    + +

    Always keep in mind that Android is a mobile platform. It may seem obvious to +say it, but it's important to remember that another Activity (such as the +"Incoming Phone Call" app) can pop up over your own Activity at any moment. +This will fire the onSaveInstanceState() and onPause() methods, and will likely result in +your application being killed.

    + +

    If the user was editing data in your application when the other Activity +appeared, your application will likely lose that data when your application is +killed. Unless, of course, you save the work in progress first. The "Android +Way" is to do just that: Android applications that accept or edit input should +override the onSaveInstanceState() method and save their state in some appropriate +fashion. When the user revisits the application, she should be able to +retrieve her data.

    + +

    A classic example of a good use of this behavior is a mail application. If the +user was composing an email when another Activity started up, the application +should save the in-process email as a draft.

    + +

    Don't Expose Raw Data

    + +

    If you wouldn't walk down the street in your underwear, neither should your +data. While it's possible to expose certain kinds of application to the world +to read, this is usually not the best idea. Exposing raw data requires other +applications to understand your data format; if you change that format, you'll +break any other applications that aren't similarly updated.

    + +

    The "Android Way" is to create a ContentProvider to expose your data to other +applications via a clean, well-thought-out, and maintainable API. Using a +ContentProvider is much like inserting a Java language interface to split up and +componentize two tightly-coupled pieces of code. This means you'll be able to +modify the internal format of your data without changing the interface exposed +by the ContentProvider, and this without affecting other applications.

    + +

    Don't Interrupt the User

    + +

    If the user is running an application (such as the Phone application during a +call) it's a pretty safe bet he did it on purpose. That's why you should avoid +spawning activities except in direct response to user input from the current +Activity.

    + +

    That is, don't call startActivity() from BroadcastReceivers or Services running in +the background. Doing so will interrupt whatever application is currently +running, and result in an annoyed user. Perhaps even worse, your Activity may +become a "keystroke bandit" and receive some of the input the user was in the +middle of providing to the previous Activity. Depending on what your +application does, this could be bad news.

    + +

    Instead of spawning Activity UIs directly from the background, you should +instead use the NotificationManager to set Notifications. These will appear in +the status bar, and the user can then click on them at his leisure, to see +what your application has to show him.

    + +

    (Note that all this doesn't apply to cases where your own Activity is already +in the foreground: in that case, the user expects to see your next Activity in +response to input.)

    + +

    Got a Lot to Do? Do it in a Thread

    + +

    If your application needs to perform some expensive or long-running +computation, you should probably move it to a thread. This will prevent the +dreaded "Application Not Responding" dialog from being displayed to the user, +with the ultimate result being the fiery demise of your application.

    + +

    By default, all code in an Activity as well as all its Views run in the same +thread. This is the same thread that also handles UI events. For example, when +the user presses a key, a key-down event is added to the Activity's main +thread's queue. The event handler system needs to dequeue and handle that +event quickly; if it doesn't, the system concludes after a few seconds that +the application is hung and offers to kill it for the user.

    + +

    If you have long-running code, running it inline in your Activity will run it +on the event handler thread, effectively blocking the event handler. This will +delay input processing, and result in the ANR dialogs. To avoid this, move +your computations to a thread. This Design for Responsiveness document +discusses how to do that..

    + +

    Don't Overload a Single Activity Screen

    + +

    Any application worth using will probably have several different screens. +When designing the screens of your UI, be sure to make use of multiple Activity +object instances.

    + +

    Depending on your development background, you may interpret an Activity as +similar to something like a Java Applet, in that it is the entry point for +your application. However, that's not quite accurate: where an Applet subclass +is the single entry point for a Java Applet, an Activity should be thought of +as one of potentially several entry points to your application. The only +difference between your "main" Activity and any others you might have is that +the "main" one just happens to be the only one that expressed an interest in +the "android.intent.action.MAIN" action in your AndroidManifest..xml file.

    + +

    So, when designing your application, think of your application as a federation +of Activity objects. This will make your code a lot more maintainable in the long +run, and as a nice side effect also plays nicely with Android's application +history and "backstack" model.

    + +

    Extend System Themes

    + +

    When it comes to the look-and-feel of the user interface, it's important to +blend in nicely. Users are jarred by applications which contrast with the user +interface they've come to expect. When designing your UIs, you should try and +avoid rolling your own as much as possible. Instead, use a Theme. You +can override or extend those parts of the theme that you need to, but at least +you're starting from the same UI base as all the other applications. For all +the details, read Styles and Themes.

    + +

    Design Your UI to Work with Multiple Screen Resolutions

    + +

    Different Android-powered devices will support different screen resolutions. +Some will even be able to change resolutions on the fly, such as by switching +to landscape mode. It's important to make sure your layouts and drawables +are flexible enough to display properly on a variety of device screens.

    + +

    Fortunately, this is very easy to do. In brief, what you must do is +provide different versions of your artwork (if you use any) for the key +resolutions, and then design your layout to accommodate various dimensions. +(For example, avoid using hard-coded positions and instead use relative +layouts.) If you do that much, the system handles the rest, and your +application looks great on any device.

    + +

    Assume the Network is Slow

    + +

    Android devices will come with a variety of network-connectivity options. All +will have some data-access provision, though some will be faster than others. +The lowest common denominator, however, is GPRS, the non-3G data service for +GSM networks. Even 3G-capable devices will spend lots of time on non-3G +networks, so slow networks will remain a reality for quite a long time to +come.

    + +

    That's why you should always code your applications to minimize network +accesses and bandwidth. You can't assume the network is fast, so you should +always plan for it to be slow. If your users happen to be on faster networks, +then that's great — their experience will only improve. You want to avoid the +inverse case though: applications that are usable some of the time, but +frustratingly slow the rest based on where the user is at any given moment are +likely to be unpopular.

    + +

    One potential gotcha here is that it's very easy to fall into this trap if +you're using the emulator, since the emulator uses your desktop computer's +network connection. That's almost guaranteed to be much faster than a cell +network, so you'll want to change the settings on the emulator that simulate +slower network speeds. You can do this in Eclipse, in the "Emulator Settings" +tab of your launch configuration or via a command-line +option when starting the emulator.

    + +

    Don't Assume Touchscreen or Keyboard

    + +

    +Android will support a variety of handset form-factors. That's a fancy way of +saying that some Android devices will have full "QWERTY" keyboards, while +others will have 40-key, 12-key, or even other key configurations. Similarly, +some devices will have touch-screens, but many won't. +

    +When building your applications, keep that in mind. Don't make assumptions +about specific keyboard layouts -- unless, of course, you're really interested +in restricting your application so that it can only be used on those devices. +

    + +

    Do Conserve the Device Battery

    +

    +A mobile device isn't very mobile if it's constantly plugged into the +wall. Mobile devices are battery-powered, and the longer we can make that +battery last on a charge, the happier everyone is — especially the user. +Two of the biggest consumers of battery power are the processor, and the +radio; that's why it's important to write your applications to do as little +work as possible, and use the network as infrequently as possible. +

    +Minimizing the amount of processor time your application uses really comes +down to writing efficient +code. To minimize the power drain from using the radio, be sure to handle +error conditions gracefully, and only fetch what you need. For example, don't +constantly retry a network operation if one failed. If it failed once, it's +likely because the user has no reception, so it's probably going to fail again +if you try right away; all you'll do is waste battery power. +

    +Users are pretty smart: if your program is power-hungry, you can count on +them noticing. The only thing you can be sure of at that point is that your +program won't stay installed very long. +

    diff --git a/docs/html/guide/practices/security.jd b/docs/html/guide/practices/security.jd index eeaac44e3940..48ccdebcfc93 100644 --- a/docs/html/guide/practices/security.jd +++ b/docs/html/guide/practices/security.jd @@ -20,8 +20,7 @@ page.title=Designing for Security
    1. Android Security Overview
    2. -
    3. Android Security -And Permissions
    4. +
    5. Permissions

    Android was designed so that most developers will be able to build @@ -136,7 +135,7 @@ dynamic permission grants on a case-by-case basis.

    To provide additional protection for sensitive data, some applications choose to encrypt local files using a key that is not accessible to the application. (For example, a key can be placed in a KeyStore and +href="{@docRoot}reference/java/security/KeyStore.html">KeyStore and protected with a user password that is not stored on the device). While this does not protect data from a root compromise that can monitor the user inputting the password, it can provide protection for a lost device without

    See also

      -
    1. Fragments
    2. +
    3. Fragments
    4. Action Bar
    5. Supporting Multiple Screens
    @@ -85,7 +85,7 @@ activity), which has its own lifecycle and which you can add or remove while the running.

    If you haven't used fragments yet, start by reading the Fragments developer guide.

    +href="{@docRoot}guide/components/fragments.html">Fragments developer guide.

    @@ -141,16 +141,16 @@ bar below.

    Remaining backward-compatible

    If you want to use fragments in your application and remain compatible with versions of Android older than 3.0, you can do so by using the Android Support Library (downloadable from the +href="{@docRoot}tools/extras/support-library.html">Support Library (downloadable from the SDK Manager).

    The support library includes APIs for fragments, loaders, and other APIs added in newer +href="{@docRoot}guide/components/fragments.html">fragments, loaders, and other APIs added in newer versions of Android. By simply adding this library to your Android project, you can use backward-compatible versions of these APIs in your application and remain compatible with Android 1.6 (your {@code android:minSdkVersion} value can be as low as {@code "4"}). For information about how to get the -library and start using it, see the Support +library and start using it, see the Support Library document.

    The support library does not provide APIs for the action bar, but you can use diff --git a/docs/html/guide/practices/ui_guidelines/activity_task_design.jd b/docs/html/guide/practices/ui_guidelines/activity_task_design.jd index 8e4528e8553a..cb2bc373bbf1 100644 --- a/docs/html/guide/practices/ui_guidelines/activity_task_design.jd +++ b/docs/html/guide/practices/ui_guidelines/activity_task_design.jd @@ -19,7 +19,7 @@ parent.link=index.html for App Structure and Navigation, or the developer guide about Tasks and Back Stack.

    +href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack.

    See also

      -
    1. Application Fundamentals
    2. +
    3. Application Fundamentals
    @@ -121,9 +121,9 @@ need to

    Be sure to look at the Design Tips section for guidelines, tips, and things to avoid. This document is a - complement to the Application + complement to the Application Fundamentals documentation (particularly the Tasks and Back Stack +href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack document), which covers the underlying mechanics for programmers.

    @@ -189,7 +189,7 @@ document),

    An activity handles a particular type of content (data) and accepts a set of related user actions. Each activity has a - lifecycle that is + lifecycle that is independent of the other activities in its application or task — each activity is launched (started) independently, and the user or system can start, @@ -268,7 +268,7 @@ independent of the other An activity is the most prominent of four components of an application. The other components are service, content provider and broadcast receiver. For more details on activities, see the - Activities document. + Activities document.

    @@ -750,7 +750,7 @@ itself.

    For more about intents, see Intents and Intent Filters. +href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters.

    @@ -947,7 +947,7 @@ href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Fi Home screen), or from a shortcut icon on the Home screen, or from the task switcher. (The mechanism for this is for the activity to have an - intent filter with action + intent filter with action MAIN and category LAUNCHER.) diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd b/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd index 4b6768f5d8e5..28817fdd9282 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_launcher.jd @@ -241,8 +241,8 @@ that launcher icons are legible across on any background color.

    Application Icons on Google Play

    -

    If you are publishing your application on -Google Play, you will also need to provide a 512 x 512 pixel, high-resolution application icon +

    If you are publishing your app on +Google Play, you will also need to provide a 512 x 512 pixel, high-resolution application icon in the developer console at upload time. This icon will be used in various locations on Google Play and does not replace your launcher icon.

    diff --git a/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd b/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd index 85a3cc860242..f6c2247c2bbf 100644 --- a/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd +++ b/docs/html/guide/practices/ui_guidelines/icon_design_launcher_archive.jd @@ -58,7 +58,7 @@ suggestions on how to work with multiple sets of icons.

    Application Icons on Google Play

    -

    If you are publishing +

    If you are publishing your application on Google Play, you will also need to provide a 512x512 pixel, high-resolution application icon in the developer console at upload-time. diff --git a/docs/html/guide/practices/ui_guidelines/widget_design.jd b/docs/html/guide/practices/ui_guidelines/widget_design.jd index d7894070e700..616f9aeb98e7 100644 --- a/docs/html/guide/practices/ui_guidelines/widget_design.jd +++ b/docs/html/guide/practices/ui_guidelines/widget_design.jd @@ -229,7 +229,7 @@ in the Developer's Guide for information on how to achieve this with la practice to define this shape using nine patches; one for each screen density (see Supporting Multiple Screens for details). Nine-patches can be created with the draw9patch tool, or simply with a +href="{@docRoot}tools/help/draw9patch.html">draw9patch tool, or simply with a graphics editing program such as Adobe® Photoshop. This will allow the widget background shape to take up the entire available space. The nine-patch should be edge-to-edge with no transparent pixels providing extra margins, save for perhaps a few border pixels for subtle diff --git a/docs/html/guide/publishing/app-signing.jd b/docs/html/guide/publishing/app-signing.jd deleted file mode 100644 index 5bd9be559497..000000000000 --- a/docs/html/guide/publishing/app-signing.jd +++ /dev/null @@ -1,618 +0,0 @@ -page.title=Signing Your Applications -@jd:body - -

    -
    - -

    Quickview

    - -
      -
    • All Android apps must be signed
    • -
    • You can sign with a self-signed key
    • -
    • How you sign your apps is critical — read this document carefully
    • -
    • Determine your signing strategy early in the development process
    • -
    - -

    In this document

    - -
      -
    1. Signing Process
    2. -
    3. Signing Strategies
    4. -
    5. Basic Setup for Signing
    6. -
    7. Signing in Debug Mode
    8. -
    9. Signing Release Mode -
        -
      1. Obtain a suitable private key
      2. -
      3. Compile the application in release mode
      4. -
      5. Sign your application with your private key
      6. -
      7. Align the final APK package
      8. -
      9. Compile and sign with Eclipse ADT
      10. -
      -
    10. -
    11. Securing Your Private Key
    12. - -
    - -

    See also

    - -
      -
    1. Versioning Your Applications
    2. -
    3. Preparing to Publish
    4. -
    - -
    -
    - -

    The Android system requires that all installed applications be digitally signed with a -certificate whose private key is held by the application's developer. The Android system uses the -certificate as a means of identifying the author of an application and establishing trust -relationships between applications. The certificate is not used to control which applications the -user can install. The certificate does not need to be signed by a certificate authority: it is -perfectly allowable, and typical, for Android applications to use self-signed certificates.

    - -

    The important points to understand about signing Android applications are:

    - -
      -
    • All applications must be signed. The system will not install an application -on an emulator or a device if it is not signed.
    • -
    • To test and debug your application, the build tools sign your application with a special debug - key that is created by the Android SDK build tools.
    • -
    • When you are ready to release your application for end-users, you must sign it with a suitable - private key. You cannot publish an application that is signed with the debug key generated - by the SDK tools.
    • -
    • You can use self-signed certificates to sign your applications. No certificate authority is - needed.
    • -
    • The system tests a signer certificate's expiration date only at install time. If an -application's signer certificate expires after the application is installed, the application -will continue to function normally.
    • -
    • You can use standard tools — Keytool and Jarsigner — to generate keys and -sign your application {@code .apk} files.
    • -
    • After you sign your application for release, we recommend that you use the - zipalign tool to optimize the final APK package.
    • -
    - -

    The Android system will not install or run an application that is not signed appropriately. This -applies wherever the Android system is run, whether on an actual device or on the emulator. -For this reason, you must set up signing for your application before you can -run it or debug it on an emulator or device.

    - -

    Signing Process

    - -

    The Android build process signs your application differently depending on which build mode you -use to build your application. There are two build modes: debug mode and release -mode. You use debug mode when you are developing and testing your application. You use -release mode when you want to build a release version of your application that you can -distribute directly to users or publish on an application marketplace such as Google Play.

    - -

    When you build in debug mode the Android SDK build tools use the Keytool utility -(included in the JDK) to create a debug key. Because the SDK build tools created the debug key, -they know the debug key's alias and password. Each time you compile your application in debug mode, -the build tools use the debug key along with the Jarsigner utility (also included in the JDK) to -sign your application's .apk file. Because the alias and password are known to the SDK -build tools, the tools don't need to prompt you for the debug key's alias and password each time -you compile.

    - -

    When you build in release mode you use your own private key to sign your application. If -you don't have a private key, you can use the Keytool utility to create one for you. When you -compile your application in release mode, the build tools use your private key along with the -Jarsigner utility to sign your application's .apk file. Because the certificate and -private key you use are your own, you will have to provide the password for the keystore and key -alias.

    - -

    The debug signing process happens automatically when you run or debug your application using -Eclipse with the ADT plugin. Debug signing also happens automatically when you use the Ant build -script with the debug option. You can automate the release signing process by using the -Eclipse Export Wizard or by modifying the Ant build script and building with the -release option.

    - -

    Signing Strategies

    - -

    Some aspects of application signing may affect how you approach the development -of your application, especially if you are planning to release multiple -applications.

    - -

    In general, the recommended strategy for all developers is to sign -all of your applications with the same certificate, throughout the expected -lifespan of your applications. There are several reasons why you should do so:

    - -
      -
    • Application upgrade – As you release updates to your application, you -will want to continue to sign the updates with the same certificate or set of -certificates, if you want users to upgrade seamlessly to the new version. When -the system is installing an update to an application, it compares the -certificate(s) in the new version with those in the existing version. If the -certificates match exactly, including both the certificate data and order, then -the system allows the update. If you sign the new version without using matching -certificates, you will also need to assign a different package name to the -application — in this case, the user installs the new version as a -completely new application.
    • - -
    • Application modularity – The Android system allows applications that -are signed by the same certificate to run in the same process, if the -applications so requests, so that the system treats them as a single application. -In this way you can deploy your application in modules, and users can update -each of the modules independently if needed.
    • - -
    • Code/data sharing through permissions – The Android system provides -signature-based permissions enforcement, so that an application can expose -functionality to another application that is signed with a specified -certificate. By signing multiple applications with the same certificate and -using signature-based permissions checks, your applications can share code and -data in a secure manner.
    • - -
    - -

    Another important consideration in determining your signing strategy is -how to set the validity period of the key that you will use to sign your -applications.

    - -
      -
    • If you plan to support upgrades for a single application, you should ensure -that your key has a validity period that exceeds the expected lifespan of -that application. A validity period of 25 years or more is recommended. -When your key's validity period expires, users will no longer be -able to seamlessly upgrade to new versions of your application.
    • - -
    • If you will sign multiple distinct applications with the same key, -you should ensure that your key's validity period exceeds the expected -lifespan of all versions of all of the applications, including -dependent applications that may be added to the suite in the future.
    • - -
    • If you plan to publish your application(s) on Google Play, the -key you use to sign the application(s) must have a validity period -ending after 22 October 2033. Google Play enforces this requirement -to ensure that users can seamlessly upgrade applications when -new versions are available.
    • -
    - -

    As you design your application, keep these points in mind and make sure to -use a suitable certificate to sign your applications.

    - -

    Basic Setup for Signing

    - -

    Before you begin, make sure that the Keytool utility and Jarsigner utility are available to -the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell -the SDK build tools how to find these utilities by setting your JAVA_HOME environment -variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and -Jarsigner to your PATH variable.

    - -

    If you are developing on a version of Linux that originally came with GNU Compiler for -Java, make sure that the system is using the JDK version of Keytool, rather than the gcj -version. If Keytool is already in your PATH, it might be pointing to a symlink at -/usr/bin/keytool. In this case, check the symlink target to be sure it points -to the Keytool in the JDK.

    - -

    Signing in Debug Mode

    - -

    The Android build tools provide a debug signing mode that makes it easier for you -to develop and debug your application, while still meeting the Android system -requirement for signing your APK. -When using debug mode to build your app, the SDK tools invoke Keytool to automatically create -a debug keystore and key. This debug key is then used to automatically sign the APK, so -you do not need to sign the package with your own key.

    - -

    The SDK tools create the debug keystore/key with predetermined names/passwords:

    -
      -
    • Keystore name: "debug.keystore"
    • -
    • Keystore password: "android"
    • -
    • Key alias: "androiddebugkey"
    • -
    • Key password: "android"
    • -
    • CN: "CN=Android Debug,O=Android,C=US"
    • -
    - -

    If necessary, you can change the location/name of the debug keystore/key or -supply a custom debug keystore/key to use. However, any custom debug -keystore/key must use the same keystore/key names and passwords as the default -debug key (as described above). (To do so in Eclipse/ADT, go to -Windows > Preferences > -Android > Build.)

    - -

    Caution: You cannot release your application -to the public when signed with the debug certificate.

    - -

    Eclipse Users

    - -

    If you are developing in Eclipse/ADT (and have set up Keytool and Jarsigner as described above in -Basic Setup for Signing), -signing in debug mode is enabled by default. When you run or debug your -application, ADT signs the {@code .apk} file with the debug certificate, runs {@code zipalign} on -the package, then installs it on -the selected emulator or connected device. No specific action on your part is needed, -provided ADT has access to Keytool.

    - -

    Ant Users

    - -

    If you are using Ant to build your {@code .apk} file, debug signing mode -is enabled by using the debug option with the ant command -(assuming that you are using a build.xml file generated by the -android tool). When you run ant debug to -compile your app, the build script generates a keystore/key and signs the APK for you. -The script then also aligns the APK with the zipalign tool. -No other action on your part is needed. Read -Building and Running Apps -on the Command Line for more information.

    - - -

    Expiry of the Debug Certificate

    - -

    The self-signed certificate used to sign your application in debug mode (the default on -Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.

    - -

    When the certificate expires, you will get a build error. On Ant builds, the error -looks like this:

    - -
    debug:
    -[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
    -[exec] Debug Certificate expired on 8/4/08 3:43 PM
    - -

    In Eclipse/ADT, you will see a similar error in the Android console.

    - -

    To fix this problem, simply delete the debug.keystore file. -The default storage location for AVDs is in ~/.android/ on OS X and Linux, -in C:\Documents and Settings\<user>\.android\ on Windows XP, and in -C:\Users\<user>\.android\ on Windows Vista and Windows 7.

    - - -

    The next time you build, the build tools will regenerate a new keystore and debug key.

    - -

    Note that, if your development machine is using a non-Gregorian locale, the build -tools may erroneously generate an already-expired debug certificate, so that you get an -error when trying to compile your application. For workaround information, see the -troubleshooting topic -I can't compile my app because the build tools generated an expired debug -certificate.

    - - -

    Signing in Release Mode

    - -

    When your application is ready for release to other users, you must:

    -
      -
    1. Obtain a suitable private key
    2. -
    3. Compile the application in release mode
    4. -
    5. Sign your application with your private key
    6. -
    7. Align the final APK package
    8. -
    - -

    If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard -to perform the compile, sign, and align procedures. The Export Wizard even allows you to -generate a new keystore and private key in the process. So if you use Eclipse, you can -skip to Compile and sign with Eclipse ADT.

    - - - -

    1. Obtain a suitable private key

    - -

    In preparation for signing your application, you must first ensure that -you have a suitable private key with which to sign. A suitable private -key is one that:

    - -
      -
    • Is in your possession
    • -
    • Represents the personal, corporate, or organizational entity to be identified -with the application
    • -
    • Has a validity period that exceeds the expected lifespan of the application -or application suite. A validity period of more than 25 years is recommended. -

      If you plan to publish your application(s) on Google Play, note that a -validity period ending after 22 October 2033 is a requirement. You can not upload an -application if it is signed with a key whose validity expires before that date. -

    • -
    • Is not the debug key generated by the Android SDK tools.
    • -
    - -

    The key may be self-signed. If you do not have a suitable key, you must -generate one using Keytool. Make sure that you have Keytool available, as described -in Basic Setup.

    - -

    To generate a self-signed key with Keytool, use the keytool -command and pass any of the options listed below (and any others, as -needed).

    - -

    Warning: Keep your private key secure. -Before you run Keytool, make sure to read -Securing Your Private Key for a discussion of how to keep -your key secure and why doing so is critically important to you and to users. In -particular, when you are generating your key, you should select strong passwords -for both the keystore and key.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Keytool OptionDescription
    -genkeyGenerate a key pair (public and private -keys)
    -vEnable verbose output.
    -alias <alias_name>An alias for the key. Only -the first 8 characters of the alias are used.
    -keyalg <alg>The encryption algorithm to use -when generating the key. Both DSA and RSA are supported.
    -keysize <size>The size of each generated key -(bits). If not supplied, Keytool uses a default key size of 1024 bits. In -general, we recommend using a key size of 2048 bits or higher.
    -dname <name>

    A Distinguished Name that describes -who created the key. The value is used as the issuer and subject fields in the -self-signed certificate.

    Note that you do not need to specify this option -in the command line. If not supplied, Jarsigner prompts you to enter each -of the Distinguished Name fields (CN, OU, and so on).

    -keypass <password>

    The password for the -key.

    As a security precaution, do not include this option in your command -line. If not supplied, Keytool prompts you to enter the password. In this way, -your password is not stored in your shell history.

    -validity <valdays>

    The validity period for the -key, in days.

    Note: A value of 10000 or greater is recommended.

    -keystore <keystore-name>.keystoreA name -for the keystore containing the private key.
    -storepass <password>

    A password for the -keystore.

    As a security precaution, do not include this option in your -command line. If not supplied, Keytool prompts you to enter the password. In -this way, your password is not stored in your shell history.

    - -

    Here's an example of a Keytool command that generates a private key:

    - -
    $ keytool -genkey -v -keystore my-release-key.keystore
    --alias alias_name -keyalg RSA -keysize 2048 -validity 10000
    - -

    Running the example command above, Keytool prompts you to provide -passwords for the keystore and key, and to provide the Distinguished -Name fields for your key. It then generates the keystore as a file called -my-release-key.keystore. The keystore and key are -protected by the passwords you entered. The keystore contains -a single key, valid for 10000 days. The alias is a name that you — -will use later, to refer to this keystore when signing your application.

    - -

    For more information about Keytool, see the documentation at - -http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

    - - - -

    2. Compile the application in release mode

    - -

    In order to release your application to users, you must compile it in release mode. -In release mode, the compiled application is not signed by default and you will need -to sign it with your private key.

    - -

    Caution: -You can not release your application unsigned, or signed with the debug key.

    - -

    With Eclipse

    - -

    To export an unsigned APK from Eclipse, right-click the project in the Package -Explorer and select Android Tools > Export Unsigned Application -Package. Then specify the file location for the unsigned APK. -(Alternatively, open your AndroidManifest.xml file in Eclipse, select -the Manifest tab, and click Export an unsigned APK.)

    - -

    Note that you can combine the compiling and signing steps with the Export Wizard. See -Compiling and signing with Eclipse ADT.

    - -

    With Ant

    - -

    If you are using Ant, you can enable release mode by using the release option -with the ant command. For example, if you are running Ant from the -directory containing your {@code build.xml} file, the command would look like this:

    - -
    $ ant release
    - -

    By default, the build script compiles the application APK without signing it. The output file -in your project {@code bin/} will be <your_project_name>-unsigned.apk. -Because the application APK is still unsigned, you must manually sign it with your private -key and then align it using {@code zipalign}.

    - -

    However, the Ant build script can also perform the signing -and aligning for you, if you have provided the path to your keystore and the name of -your key alias in the project's {@code ant.properties} file. With this information provided, -the build script will prompt you for your keystore and alias password when you perform -ant release, it will sign the package and then align it. The final output -file in {@code bin/} will instead be -<your_project_name>-release.apk. With these steps -automated for you, you're able to skip the manual procedures below (steps 3 and 4). -To learn how to specify your keystore and alias in the {@code ant.properties} file, -see -Building and Running Apps on the Command Line.

    - - - -

    3. Sign your application with your private key

    - -

    When you have an application package that is ready to be signed, you can do sign it -using the Jarsigner tool. Make sure that you have Jarsigner available on your -machine, as described in Basic Setup. Also, make sure that -the keystore containing your private key is available.

    - -

    To sign your application, you run Jarsigner, referencing both the -application's APK and the keystore containing the private key with which to -sign the APK. The table below shows the options you could use.

    - - - - - - - - - - - - - - - - - - - - - - - - -
    Jarsigner OptionDescription
    -keystore <keystore-name>.keystoreThe name of -the keystore containing your private key.
    -verboseEnable verbose output.
    -sigalgThe name of the signature algorithim to use in signing the APK. -Use the value {@code MD5withRSA}.
    -digestalgThe message digest algorithim to use in processing the entries -of an APK. Use the value {@code SHA1}.
    -storepass <password>

    The password for the -keystore.

    As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Jarsigner prompts you to enter the password. In this -way, your password is not stored in your shell history.

    -keypass <password>

    The password for the private -key.

    As a security precaution, do not include this option -in your command line unless you are working at a secure computer. -If not supplied, Jarsigner prompts you to enter the password. In this -way, your password is not stored in your shell history.

    - -

    Here's how you would use Jarsigner to sign an application package called -my_application.apk, using the example keystore created above. -

    - -
    $ jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore my-release-key.keystore
    -my_application.apk alias_name
    - -

    Running the example command above, Jarsigner prompts you to provide -passwords for the keystore and key. It then modifies the APK -in-place, meaning the APK is now signed. Note that you can sign an -APK multiple times with different keys.

    - -

    Caution: As of JDK 7, the default signing algorithim has -changed, requiring you to specify the signature and digest algorithims ({@code -sigalg} and {@code --digestalg}) when you sign an APK.

    - -

    To verify that your APK is signed, you can use a command like this:

    - -
    $ jarsigner -verify my_signed.apk
    - -

    If the APK is signed properly, Jarsigner prints "jar verified". -If you want more details, you can try one of these commands:

    - -
    $ jarsigner -verify -verbose my_application.apk
    - -

    or

    - -
    $ jarsigner -verify -verbose -certs my_application.apk
    - -

    The command above, with the -certs option added, will show you the -"CN=" line that describes who created the key.

    - -

    Note: If you see "CN=Android Debug", this means the APK was -signed with the debug key generated by the Android SDK. If you intend to release -your application, you must sign it with your private key instead of the debug -key.

    - -

    For more information about Jarsigner, see the documentation at - -http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jarsigner.html

    - - -

    4. Align the final APK package

    - -

    Once you have signed the APK with your private key, run zipalign on the file. -This tool ensures that all uncompressed data starts with a particular byte alignment, -relative to the start of the file. Ensuring alignment at 4-byte boundaries provides -a performance optimization when installed on a device. When aligned, the Android -system is able to read files with {@code mmap()}, even if -they contain binary data with alignment restrictions, rather than copying all -of the data from the package. The benefit is a reduction in the amount of -RAM consumed by the running application.

    - -

    The zipalign tool is provided with the Android SDK, inside the -tools/ directory. To align your signed APK, execute:

    - -
    $ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
    - -

    The {@code -v} flag turns on verbose output (optional). {@code 4} is the -byte-alignment (don't use anything other than 4). The first file argument is -your signed {@code .apk} file (the input) and the second file is the destination {@code .apk} file -(the output). If you're overriding an existing APK, add the {@code -f} flag.

    - -

    Caution: Your input APK must be signed with your -private key before you optimize the package with {@code zipalign}. -If you sign it after using {@code zipalign}, it will undo the alignment.

    - -

    For more information, read about the -zipalign tool. - - -

    Compile and sign with Eclipse ADT

    - -

    If you are using Eclipse with the ADT plugin, you can use the Export Wizard to -export a signed APK (and even create a new keystore, -if necessary). The Export Wizard performs all the interaction with -the Keytool and Jarsigner for you, which allows you to sign the package using a GUI -instead of performing the manual procedures to compile, sign, -and align, as discussed above. Once the wizard has compiled and signed your package, -it will also perfom package alignment with {@code zipalign}. -Because the Export Wizard uses both Keytool and Jarsigner, you should -ensure that they are accessible on your computer, as described above -in the Basic Setup for Signing.

    - -

    To create a signed and aligned APK in Eclipse:

    - -
      -
    1. Select the project in the Package -Explorer and select File > Export.
    2. -
    3. Open the Android folder, select Export Android Application, - and click Next. -

      The Export Android Application wizard now starts, which will - guide you through the process of signing your application, - including steps for selecting the private key with which to sign the APK - (or creating a new keystore and private key).

      -
    4. Complete the Export Wizard and your application will be compiled, - signed, aligned, and ready for distribution.
    5. -
    - - - -

    Securing Your Private Key

    - -

    Maintaining the security of your private key is of critical importance, both -to you and to the user. If you allow someone to use your key, or if you leave -your keystore and passwords in an unsecured location such that a third-party -could find and use them, your authoring identity and the trust of the user -are compromised.

    - -

    If a third party should manage to take your key without your knowledge or -permission, that person could sign and distribute applications that maliciously -replace your authentic applications or corrupt them. Such a person could also -sign and distribute applications under your identity that attack other -applications or the system itself, or corrupt or steal user data.

    - -

    Your reputation as a developer entity depends on your securing your private -key properly, at all times, until the key is expired. Here are some tips for -keeping your key secure:

    - -
      -
    • Select strong passwords for the keystore and key.
    • -
    • When you generate your key with Keytool, do not supply the --storepass and -keypass options at the command line. -If you do so, your passwords will be available in your shell history, -which any user on your computer could access.
    • -
    • Similarly, when signing your applications with Jarsigner, -do not supply the -storepass and -keypass -options at the command line.
    • -
    • Do not give or lend anyone your private key, and do not let unauthorized -persons know your keystore and key passwords.
    • -
    - -

    In general, if you follow common-sense precautions when generating, using, -and storing your key, it will remain secure.

    \ No newline at end of file diff --git a/docs/html/guide/publishing/licensing.html b/docs/html/guide/publishing/licensing.html deleted file mode 100644 index 8e97f328da3c..000000000000 --- a/docs/html/guide/publishing/licensing.html +++ /dev/null @@ -1,11 +0,0 @@ - - - -Redirecting... - - -

    You should have been redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/publishing/preparing.jd b/docs/html/guide/publishing/preparing.jd deleted file mode 100644 index 8e75728edcd1..000000000000 --- a/docs/html/guide/publishing/preparing.jd +++ /dev/null @@ -1,358 +0,0 @@ -page.title=Preparing for Release -@jd:body - -
    -
    -

    Quickview

    -
      -
    • Learn which resources you'll need to release your app.
    • -
    • Find out how to configure and build your app for release.
    • -
    • Learn best practices for releasing your app.
    • -
    -

    In this document

    -
      -
    1. Introduction
    2. -
    3. Gathering Materials and Resources
    4. -
    5. Configuring Your Application
    6. -
    7. Building Your Application
    8. -
    9. Preparing External Servers and Resources
    10. -
    11. Testing Your Application for Release
    12. -
    -

    See also

    -
      -
    1. Publishing Overview
    2. -
    3. Signing Your Applications
    4. -
    5. Publishing on Google Play
    6. -
    -
    -
    - -

    Before you distribute your Android application to users you need to prepare it for release. The -preparation process is a required development -task for all Android applications and is the first step in the publishing process (see figure -1).

    - -

    When you prepare your application for release, you configure, build, and test a release -version of your application. The configuration tasks are straightforward, involving basic code -cleanup and code modification tasks that help optimize your application. The build process is -similar to the debug build process and can be done using JDK and Android SDK tools. The testing -tasks serve as a final check, ensuring that your application performs as expected under real-world -conditions. When you are finished preparing your application for release you have a signed -.apk file, which you can distribute directly to users or distribute through an -application marketplace such as Google Play.

    - -

    This document summarizes the main tasks you need to perform to prepare your application for -release. The tasks that are described in this document apply to all Android applications regardless -how they are released or distributed to users. If you are releasing your application through Google -Play, you should also read Publishing on -Google Play to be sure your release-ready application satisfies all Google Play -requirements.

    - -

    Note: As a best practice, your application should meet all of your -release criteria for functionality, performance, and stability before you perform the tasks outlined -in this document.

    - -Shows how the preparation process fits into the development process -

    - Figure 1. Preparing for release is a required development -task and is the first step in the publishing process. -

    - -

    Introduction

    - -

    To release your application to users you need to create a release-ready package that users can -install and run on their Android-powered devices. The release-ready package contains the same -components as the debug .apk file — compiled source code, resources, manifest -file, and so on — and it is built using the same build tools. However, unlike the debug -.apk file, the release-ready .apk file is signed with your own certificate -and it is optimized with the zipalign tool.

    - -
    - Shows the five tasks you perform to prepare your app for release -

    - Figure 2. You perform five main tasks to prepare your application for - release. -

    -
    - -

    The signing and optimization tasks are usually seamless if you are building your application with -Eclipse and the ADT plugin or with the Ant build script (included with the Android SDK). For -example, you can use the Eclipse Export Wizard to compile, sign, and optimize your application all -at once. You can also configure the Ant build script to do the same when you build from the command -line.

    - -

    To prepare your application for release you typically perform five main tasks (see figure 2). -Each main task may include one or more smaller tasks depending on how you are releasing your -application. For example, if you are releasing your application through Google Play you may want -to add special filtering rules to your manifest while you are configuring your application for -release. Similarly, to meet Google Play publishing guidelines you may have to prepare screenshots -and create promotional text while you are gathering materials for release.

    - -

    You usually perform the tasks listed in figure 2 after you have throroughly debugged and tested -your application. The Android SDK contains several tools to help you test and debug your Android -applications. For more information, see the Debugging and Testing sections in the Dev Guide.

    - -

    Gathering Materials and Resources

    - -

    To begin preparing your application for release you need to gather several supporting items. At a -minimum this includes cryptographic keys for signing your application and an application icon. You -might also want to include an end-user license agreement.

    - -

    Cryptographic keys

    - -

    The Android system requires that each installed application be digitally signed with a -certificate that is owned by the application's developer (that is, a certificate for which the -developer holds the private key). The Android system uses the certificate as a means of identifying -the author of an application and establishing trust relationships between applications. The -certificate that you use for signing does not need to be signed by a certificate authority; the -Android system allows you to sign your applications with a self-signed certificate. To learn about -certificate requirements, see Obtain a -suitable private key.

    - -

    Important: Your application must be signed with a cryptographic -key whose validity period ends after 22 October 2033.

    - -

    You may also have to obtain other release keys if your application accesses a service or uses a -third-party library that requires you to use a key that is based on your private key. For example, -if your application uses the MapView -class, which is part of the Google Maps external -library, you will need to register your application with the Google Maps service and obtain -a Maps API key. For information about getting a Maps API key, see Obtaining a Maps API -key.

    - -

    Application Icon

    - -

    Be sure you have an application icon and that it meets the recommended icon guidelines. Your -application's icon helps users identify your application on a device's Home -screen and in the Launcher window. It also appears in Manage Applications, My Downloads, and -elsewhere. In addition, publishing services such as Google Play display your icon to users.

    - -

    Note: If you are releasing your application on Google Play, you -need to create a high resolution - version of your icon. See Graphic -Assets for your Application for more information.

    - -

    End-user License Agreement

    - -

    Consider preparing an End User License Agreement (EULA) for your application. A EULA can help -protect your person, organization, and intellectual property, and we recommend that you provide one -with your application.

    - -

    Miscellaneous Materials

    - -

    You might also have to prepare promotional and marketing materials to publicize your application. -For example, if you are releasing your application on Google Play you will need to prepare some -promotional text and you will need to create screenshots of your application. For more -information, see - -Graphic Assets for your Application

    - -

    Configuring Your Application for Release

    - -

    After you gather all of your supporting materials you can start configuring your application -for release. This section provides a summary of the configuration changes we recommend that you make -to your source code, resource files, and application manifest prior to releasing your application. -Although most of the configuration changes listed in this section are optional, they are -considered good coding practices and we encourage you to implement them. In some cases, -you may have already made these configuration changes as part of your development process.

    - -

    Choose a good package name

    - -

    Make sure you choose a package name that is suitable over the life of your application. You -cannot change the package name after you distribute your application to users. You can set the -package name in application's manifest file. For more information, see the package attribute -documentation.

    - -

    Turn off logging and debugging

    - -

    Make sure you deactivate logging and disable the debugging option before you build your -application for release. You can deactivate logging by removing calls to -{@link android.util.Log} methods in your source files. You can disable debugging by removing the -android:debuggable attribute from the <application> tag in your -manifest file, or by setting the android:debuggable attribute to -false in your manifest file. Also, remove any log files or static test files that -were created in your project.

    - -

    Also, you should remove all {@link android.os.Debug} tracing calls that you -added to your code, such as {@link android.os.Debug#startMethodTracing()} and -{@link android.os.Debug#stopMethodTracing()} method calls.

    - -

    Clean up your project directories

    - -

    Clean up your project and make sure it conforms to the directory structure described in Android Projects. -Leaving stray or orphaned files in your project can prevent your application from compiling and -cause your application to behave unpredictably. At a minimum you should do the following cleanup -tasks:

    - -
      -
    • Review the contents of your jni/, lib/, and src/ - directories. The jni/ directory should contain only source files associated with the - Android NDK, such as - .c, .cpp, .h, and .mk files. The - lib/ directory should contain only third-party library files or private library - files, including prebuilt shared and static libraries (for example, .so files). The - src/ directory should contain only the source files for your application - (.java and .aidl files). The src/ directory should not - contain any .jar files.
    • -
    • Check your project for private or proprietary data files that your application does not use - and remove them. For example, look in your project's res/ directory for old - drawable files, layout files, and values files that you are no longer using and delete them.
    • -
    • Check your lib/ directory for test libraries and remove them if they are no - longer being used by your application.
    • -
    • Review the contents of your assets/ directory and your res/raw/ - directory for raw asset files and static files that you need to update or remove prior to - release.
    • -
    - -

    Review and update your manifest settings

    - -

    Verify that the following manifest items are set correctly:

    - -
      -
    • - <uses-permission> element -

      You should specify only those permissions that are relevant and required for your application.

      -
    • -
    • android:icon and android:label attributes -

      You must specify values for these attributes, which are located in the - <application> - element.

      -
    • -
    • android:versionCode and android:versionName attributes. -

      We recommend that you specify values for these attributes, which are located in the - <manifest> - element. For more information see - Versioning your Application.

      -
    • -
    - -

    There are several additional manifest elements that you can set if you are releasing your -application on Google Play. For example, the android:minSdkVersion and -android:targetSdkVersion attributes, which are located in the <uses-sdk> element. For more -information about these and other Google Play settings, see Filters on Google Play.

    - -

    Address compatibility issues

    - -

    Android provides several tools and techniques to make your application compatible with a wide -range of devices. To make your application available to the largest number of users, consider -doing the following:

    - -
      -
    • Add support for multiple screen configurations -

      Make sure you meet the - - best practices for supporting multiple screens. By supporting multiple screen configurations - you can create an application that functions properly and looks good on any of the screen sizes - supported by Android.

      -
    • -
    • Optimize your application for Android 3.0 devices. -

      If your application is designed for devices older than Android 3.0, make it compatible - with Android 3.0 devices by following the guidelines and best practices described in - Optimizing Apps for Android 3.0 - .

      -
    • -
    • Consider using the Support Library -

      If your application is designed for devices running Android 3.x, make your application - compatible with older versions of Android by adding the - Support Library to your - application project. The Support Library provides static support libraries that you can add to - your Android application, which enables you to use APIs that are either not available on - older platform versions or use utility APIs that are not part of the framework APIs.

      -
    • -
    - -

    Update URLs for servers and services

    - -

    If your application accesses remote servers or services, make sure you are using the production -URL or path for the server or service and not a test URL or path.

    - -

    Implement Licensing (if you are releasing on Google Play)

    - -

    If you are releasing a paid application through Google Play, consider adding support for -Google Play Licensing. Licensing lets you control access to your application based on whether the -current user has purchased it. Using Google Play Licensing is optional even if you are -releasing your app through Google Play.

    - -

    For more information about Google Play Licensing Service and how to use it in your -application, see Application Licensing.

    - -

    Building Your Application for Release

    - -

    After you finish configuring your application you can build it into a release-ready -.apk fle that is signed and optimized. The JDK includes the tools for signing the -.apk file (Keytool and Jarsigner); the Android SDK includes the tools for compiling and -optimizing the .apk file. If you are using Eclipse with the ADT plugin or you are using -the Ant build script from the command line, you can automate the entire build process.

    - -

    Building with Eclipse

    - -

    You can use the Eclipse Export Wizard to build a release-ready .apk file that is -signed with your private key and optimized. To learn how to run the Export Wizard, see -Compile and sign with Eclipse -ADT. The Export Wizard compiles your application for release, signs your application with your -private key, and optimizes your application with the zipalign tool. The Export Wizard should run -successfully if you have run or debugged your application from Eclipse and you have no errors in -your application (see Building -and Running from Eclipse with ADT for more information.

    - -

    The Export Wizard assumes that you have a certificate and private key -suitable for signing your application. If you do not have a suitable certificate and private key, -the Export Wizard will help you generate one (see -Signing Your Applications for more -information about the signing process and signing guidelines.

    - -

    Building with Ant

    - -

    You can use the Ant build script (included in the Android SDK) to build a release-ready -.apk file that is signed with your private key and optimized. To learn how to do this, -see Building in -Release Mode. This build method assumes you have a certificate and -private key suitable for signing your application. If you do not have a suitable certificate and -private key, the Export Wizard will help you generate one (see -Signing Your Applications for more -information about the signing process and signing guidelines.

    - -

    Preparing External Servers and Resources

    - -

    If your application relies on a remote server, make sure the server is secure and that it is -configured for production use. This is particularly important if you are implementing in-app billing in your application and you are -performing the signature verification step on a remote server.

    - -

    Also, if your application fetches content from a remote server or a real-time service (such as a -content feed), be sure the content you are providing is up to date and production-ready.

    - -

    Testing Your Application for Release

    - -

    Testing the release version of your application helps ensure that your application runs properly -under realistic device and network conditions. Ideally, you should test your application on at least -one handset-sized device and one tablet-sized device to verify that your user interface elements are -sized correctly and that your application's performance and battery efficiency are acceptable.

    - -

    As a starting point for testing, see -What to Test. This article provides -a summary of common Android situations that you should consider when you are testing. When you are -done testing and you are satisfied that the release version of your application -behaves correctly, you can release your application to users. For more information, see -Releasing Your -Application to Users. If you are publishing your application on Google Play, see -Publishing on Google Play.

    - - diff --git a/docs/html/guide/publishing/publishing.jd b/docs/html/guide/publishing/publishing.jd deleted file mode 100644 index b9513ab034ef..000000000000 --- a/docs/html/guide/publishing/publishing.jd +++ /dev/null @@ -1,703 +0,0 @@ -page.title=Publishing on Google Play -@jd:body - -
    -
    - -

    Quickview

    - -
      -
    • Learn how to publish and update apps on Google Play.
    • -
    • Find out how to create links to apps that are published on Google Play.
    • -
    • Learn about Google Play features.
    • -
    - - -

    In this document

    - -
      -
    1. About Google Play -
    2. Publishing Apps on Google Play
    3. -
    4. Publishing Updates on Google Play
    5. -
    6. Using Google Play Licensing Service
    7. -
    8. Using Google Play In-app Billing
    9. -
    10. Linking to Your Apps on Google Play -
        -
      1. Opening an app's details page
      2. -
      3. Performing a search
      4. -
      5. Build a Google Play button
      6. -
      7. Summary of URI formats
      8. -
      -
    11. -
    - -

    See also

    - -
      -
    1. Publishing Overview
    2. -
    3. Preparing for Release
    4. -
    - -
    - -
    - -

    Already know about Google Play and want to get started?

    -

    Go to Google Play, create a developer -account, and upload your application. For more information about required assets, listing details, -and publishing options, see Upload -Applications.

    -
    -
    - -
    -
    - -

    One of the most effective ways to get your application into users' hands is to -publish it on an application marketplace like Google Play. Publishing on Google Play is a -straightforward process that you can do in just a few simple steps—register, configure, -upload, and publish. Registration takes only a few minutes and needs to be done only once. -The configuration and publishing steps can all be done through the Google Play Android Developer Console -after you register as a Google Play developer.

    - -

    To start publishing on Google Play, first read this topic and then go to the Google Play Android Developer Console and register as -a Google Play developer.

    - - -

    About Google Play

    - -

    Google Play is a robust publishing platform that helps you publicize, sell, and distribute -your Android applications to users around the world. When you release your applications through -Google Play you have access to a suite of developer tools that let you analyze your sales, -identify market trends, and control who your applications are being distributed to. You also have -access to several revenue-enhancing features, such as in-app billing and -application licensing.

    - -

    Before you can publish applications on Google Play, you need to register as a Google Play developer. During the -registration process you will need to create a developer profile, pay a registration fee, and agree -to the Google Play -Developer Distribution Agreement. After you register you can access the Developer -Console, where you can upload applications, configure publishing options, and monitor publishing -data. If you want to sell your applications or use the in-app billing feature, you will also need -to set up a Google Checkout merchant account. For more information about the registration process, -see -Developer Registration.

    - -

    Publishing Apps on Google Play

    - -

    Publishing your application on Google Play is a simple process that involves three basic -tasks (see figure 1):

    - -
      -
    • Creating various graphical assets that -accompany your app on Google Play.
    • -
    • Using the Google Play Developer Console to configure publishing options, -specify listing details, and upload your app and graphical assets to Google Play.
    • -
    • Reviewing your publishing settings and changing the release -status of your app from Unpublished to Published.
    • -
    - -Shows the three steps that are required to publish on Google Play -

    - Figure 1. To publish apps on Google Play you must first prepare your app for release and then perform -three simple tasks. -

    - -

    Important: You must prepare your application for release before you -can publish it on Google Play. When you prepare your application for release you configure it for -release and build it in release mode. Building in release mode signs your application's {@code .apk} -file with your private release key. You cannot publish an application on Google Play unless it is -signed with your own private release key.

    - -

    Preparing promotional materials

    - -

    To fully leverage the marketing and publicity capabilities of Google Play, you need to create -several graphical assets that accompany your app on Google Play, such as screenshots, videos, -promotional graphics, and promotional text. At a minimum you must provide two screenshots of your -application and a high resolution application icon. The screenshots are displayed on the details -page for your application on Google Play, and the high resolution application icon is displayed -in various locations throughout Google Play. The high resolution icon does not replace the -launcher icon for your application, rather, it serves as a supplemental icon and should look -the same as your launcher icon. Promotional video, -graphics, and text are optional, although we strongly recommended that you prepare these for your -app. For more information about the graphic assets that accompany your application, see Graphic -Assets for your Application.

    - -

    Configuring options and uploading assets

    - -

    Google Play lets you target your application to a worldwide pool of users and devices. To -reach these users you can use the Developer Console to configure various publishing -options and listing details for your app. For example, you can choose the countries you want to reach, the listing languages you want to use, and the -price you want to charge in each country. You can also configure listing -details such as the application type, category, and content rating. In addition, if you want to sell items within your app using -the in-app billing feature, you can use the Developer Console to create a product list and control which items are available for purchase in your -app.

    - -

    When you are finished setting publishing options and listing details, you can upload your assets -and your application to Google Play. You can also upload your application as a draft -(unpublished) application, which lets you do final testing before you publish it for final -release.

    - -

    To learn more about Google Play publishing settings, see the following resources:

    - - - -

    Publishing your application

    - -

    When you are satisfied that your publishing settings are correctly configured and your uploaded -application is ready to be released to the public, you can simply click Publish in -the Developer Console to make your app available for download -around the world. Keep in mind, it can take several hours for your app to appear on Google -Play after you click Publish in the Developer Console.

    - -

    Controlling Distribution to Devices

    - -

    If your application targets different device configurations, you can control which Android-powered -devices have access to your application on Google Play by -using Google Play filters. Filtering compares device configurations that you declare in your -app's manifest file to the configuration defined by a device. For example, if you declare the camera -filter in your manifest, only those devices that have a camera will see your app on Google -Play. Filters must be configured in your application's manifest file when you are preparing your app for release (that is, before -you upload your app to Google Play). For more information, see Filters on Google Play.

    - -

    You can also use the multiple APK feature to distribute different {@code .apk} files under the same -application listing and the same package name; however, you should use this option only as a last -resort. Android applications usually run on most compatible devices with a single APK, by supplying -alternative resources for different configurations (for example, different layouts for different screen -sizes) and the Android system selects the appropriate resources for the device at runtime. In a -few cases, however, a single APK is unable to support all device configurations, because alternative -resources make the APK file too big (greater than 50MB) or other technical challenges prevent a -single APK from working on all devices. Although we encourage you to develop and publish a single -APK that supports as many device configurations as possible, doing so is sometimes -not possible. To help you publish your application for as many devices as possible, Google Play -allows you to publish multiple APKs under the same application listing. Google Play then supplies -each APK to the appropriate devices based on configuration support you've declared in the manifest -file of each APK. To use this feature, you need to build your separate {@code .apk} files when you are preparing your app for release (that is, before -you upload your app to Google Play). For more information, see Multiple APK Support.

    - -

    Publishing Updates on Google Play

    - -

    At any time after publishing an application on Google Play, you can upload -and publish an update to the same application package. When you publish an -update to an application, users who have already installed the -application may receive a notification that an update is -available for the application. They can then choose to update the application -to the latest version.

    - -

    Before uploading the updated application, be sure that you have incremented -the android:versionCode and android:versionName -attributes in the <manifest> -element of the manifest file. Also, the package name must be the same as the existing version and -the {@code .apk} file must be signed with the same private key. If the package name and signing -certificate do not match those of the existing version, Google Play will -consider it a new application, publish it as such, and will not offer it to existing users as an -update.

    - -

    If you plan to publish your application on Google Play, you must make sure - that it meets the requirements listed below, which are enforced by Google Play - when you upload the application.

    - -

    Using Google Play Licensing Service

    - -

    Google Play offers a licensing service that lets you enforce licensing -policies for paid applications that you publish through Google Play. With -Google Play Licensing, your applications can query Google Play at runtime -to obtain the licensing status for the current user, then allow or disallow -further use of the application as appropriate. Using the service, you can apply a flexible -licensing policy on an application-by-application basis—each -application can enforce its licensing status in the way most appropriate -for it.

    - -

    Any application that you publish through Google Play can use the Google -Play Licensing Service. The service uses no dedicated framework APIs, so you can -add licensing to any application that uses a minimum API Level of 3 or -higher.

    - -

    For complete information about Google Play Licensing Service and how to -use it in your application, read Application Licensing.

    - -

    Using Google Play In-app Billing

    - -

    Google Play In-app Billing -is a Google Play service that lets you sell digital content in your applications. You can use -the service to sell a wide range of content, including downloadable content such as media files or -photos, and virtual content such as game levels or potions.

    - -

    When you use Google Play's in-app billing service to sell an item, Google Play handles all -billing details so your application never has to directly process any financial transactions. -Google Play uses the same checkout service that is used for application purchases, so your users -experience a consistent and familiar purchase flow (see figure 1). Also, the transaction fee for -in-app purchases is the same as the transaction fee for application purchases (30%).

    - -

    Any application that you publish through Google Play can implement in-app billing. No special -account or registration is required other than a Google Play publisher account and a Google -Checkout Merchant account. Also, because the service uses no dedicated framework APIs, you can add -in-app billing to any application that uses a minimum API level of 4 or higher.

    - -

    To help you integrate in-app billing into your application, the Android SDK provides a sample application -that demonstrates a simple implementation of in-app billing. The sample application contains -examples of billing-related classes you can use to implement in-app billing in your application. It -also contains examples of the database, user interface, and business logic you might use to -implement in-app billing. For more information about the in-app billing feature, see the -In-app Billing documentation.

    - -

    Linking to Your Apps on Google Play

    - -

    To help users discover your published applications, you can use two special Google Play URIs -that direct users to your application's details page or perform a search for all of your published -applications on Google Play. You can use these URIs to create a button in your application or a -link on a web page that:

    - -
      -
    • Opens your application's details page in the Google Play application or web site.
    • -
    • Searches for all your published applications in the Google Play application or web -site.
    • -
    - -

    You can launch the Google Play application or web site in the following ways:

    -
      -
    • Initiate an {@link android.content.Intent} from your application that launches the -Google Play application on the user's device.
    • -
    • Provide a link on a web page that opens the Google Play web site (but will also -open the Google Play application if clicked from a device).
    • -
    - -

    In both cases, whether you want to initiate the action from your application or from a web -page, the URIs are quite similar. The only difference is the URI prefix.

    - -

    To open the Google Play application from your application, the prefix for the intent's data -URI is:

    - -

    market://

    - -

    To open Google Play store from your web site, the prefix for the link URI is:

    - -

    http://play.google.com/store/

    - -

    The following sections describe how to create a complete URI for each action.

    - -

    Note: If you create a link to open Google Play from your web -site and the user selects it from an Android-powered device, the device's Google Play application will -resolve the link so the user can use the Google Play application on the device instead of opening the web -site. As such, you should always use {@code http://play.google.com/store/apps/...} URIs when -creating a link on -a web page. When pointing to your apps from within your Android app, use the -{@code market://} URIs in an intent, so that the Google Play application always opens.

    - - -

    Opening an app's details page

    - -

    As described above, you can open the details page for a specific application either on the -Google Play application or the Google Play web site. The details page allows the user to see -the application description, screenshots, reviews and more, and choose to install it.

    - -

    The format for the URI that opens the details page is:

    - -

    <URI_prefix>apps/details?id=<package_name>

    - -

    The <package_name> is a placeholder for the target application's -fully-qualified package name, as declared in the {@code -package} attribute of the {@code -<manifest>} element.

    - -

    For example: http://play.google.com/store/apps/details?id=com.example.myapp

    - - -

    Opening the app details page from your Android app

    - -

    To open the Google Play details page from your application, -create an intent with the {@link android.content.Intent#ACTION_VIEW} action and include a data URI -in this format:

    - -

    market://details?id=<package_name>

    - -

    For example, here's how you can create an intent and open an application's details page in -Google Play:

    - -
    -Intent intent = new Intent(Intent.ACTION_VIEW);
    -intent.setData(Uri.parse("market://details?id=com.example.android"));
    -startActivity(intent);
    -
    - -

    This will open the Google Play application on the device to view the {@code -com.example.android} application.

    - - -

    Opening the app details page from a web site

    - -

    To open the details page from your web site, create a link with a URI in this -format:

    - -

    - http://play.google.com/store/apps/details?id=<package_name> -

    - -

    For example, here's a link that opens an application's details page on Google Play:

    - -
    -<a href="http://play.google.com/store/apps/details?id=com.example.android">App Link</a>
    -
    - -

    When clicked from a desktop web browser, this opens the Google Play web site to view the -{@code com.example.android} application. When clicked from an Android-powered device, users are -given the option to use either their web browser or the Google Play application to view the -application.

    - - - -

    Performing a search

    - -

    To initiate a search on Google Play, the format for the URI is:

    - -

    - <URI_prefix>search?q=<query> -

    - -

    The <query> is a placeholder for the search query to execute in Google -Play. The query can be a raw text string or you can include a parameter that performs a search -based on the publisher name:

    - -
      -
    • To perform a raw text search, append the query string: -

      <URI_prefix>search?q=<search_query>

    • - -
    • To search based on the publisher name, use the {@code pub:} parameter in the query, followed -by the publisher name: -

      <URI_prefix>search?q=pub:<publisher_name>

      -

      You can use this type of search to show all of your published applications.

    • -
    - - -

    Searching from your Android app

    - -

    To initiate a search on Google Play from your application, create an intent with the -{@link android.content.Intent#ACTION_VIEW} action and include a data URI in this format:

    - -

    market://search?q=<query>

    - -

    The query may include the {@code pub:} parameter described above.

    - -

    For example, here's how you can initiate a search in the Google Play application, based on the -publisher name:

    - -
    -Intent intent = new Intent(Intent.ACTION_VIEW);
    -intent.setData(Uri.parse("market://search?q=pub:Your Publisher Name"));
    -startActivity(intent);
    -
    - -

    This opens the Google Play application to perform the search. The search result shows all -applications published by the publisher that are compatible with the current device.

    - - -

    Searching from a web site

    - -

    To initiate a search on Google Play from your web site, create a link with a URI in this -format:

    - -

    - http://play.google.com/store/search?q=<query> -

    - -

    The query may include the {@code pub:} parameter described above.

    - -

    For example, here's a link that initiates a search on Google Play, based on the -publisher name:

    - -
    -<a href="http://play.google.com/store/search?q=pub:Your Publisher Name">Search Link</a>
    -
    - -

    When clicked from a desktop web browser, this opens the Google Play web site and performs the -search. When clicked from an Android-powered device, users are given the option to use either their -web browser or the Google Play application to perform the search.

    - - - -

    Build a Google Play button

    - -

    Use the following form to create a button for your web site that takes users to your application -on Google Play. Input either your application's package name or your publisher name and the button -will take users to Google Play to either view your application's information or view a list of your -published apps. If users click the button while on an Android-powered device, the Google Play -application will respond to show users your application(s).

    - -

    This form offers two styles of the official brand badge each at recommended sizes. You can pick -between either "Get it on Google Play" or "Android app on Google Play." You should not modify the -badge images in any way. For more usage guidelines, -see the Android Brand Guidelines.

    - - - - - -
    - -   - -

     or

    - -   - -

    - -
    - - -      - - -
    - -
    - - -      - - -
    - - -
    -
    - - - - - - - - -

    Summary of URI formats

    - -

    The table below provides a summary of the URIs currently supported by the Google Play (both on -the web and in the Android application), as discussed in the previous sections.

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    For this resultUse this URI in a web page linkOr this URI in an {@link android.content.Intent#ACTION_VIEW} intent
    Display the details screen for a specific applicationhttp://play.google.com/store/apps/details?id=<package_name> -market://details?id=<package_name>
    Search for applications using a general string query.http://play.google.com/store/search?q=<query>market://search?q=<query>
    Search for applications by publisher namehttp://play.google.com/store/search?q=pub:<publisher_name>market://search?q=pub:<publisher_name>
    diff --git a/docs/html/guide/publishing/publishing_overview.jd b/docs/html/guide/publishing/publishing_overview.jd deleted file mode 100755 index 6fb77e18b4a6..000000000000 --- a/docs/html/guide/publishing/publishing_overview.jd +++ /dev/null @@ -1,231 +0,0 @@ -page.title=Publishing Overview -@jd:body - -
    -
    -

    Quickview

    -
      -
    • Learn how to publish Android apps.
    • -
    • Find out how to prepare apps for release.
    • -
    • Learn how to release apps to users.
    • -
    -

    In this document

    -
      -
    1. Preparing Your Application for Release
    2. -
    3. Releasing Your Application to Users -
        -
      1. Releasing on Google Play
      2. -
      3. Releasing on your own website
      4. -
      5. Releasing through email
      6. -
      -
    -

    See also

    -
      -
    1. Preparing for - Release
    2. -
    3. Publishing on Google Play
    4. -
    -
    -
    - -

    Publishing is the process that makes your Android applications available to users. When you -publish an Android application you perform two main tasks:

    - -
      -
    • You prepare the application for release. -

      During the preparation step you build a release version of your application, which users can - download and install on their Android-powered devices.

      -
    • -
    • You release the application to users. -

      During the release step you publicize, sell, and distribute the release version of your - application to users.

      -
    • -
    - -

    Usually, you release your application through an application marketplace, such as Google Play. -However, you can also release applications by sending them directly to users or by letting users -download them from your own website.

    - -

    Figure 1 shows how the publishing process fits into the overall Android application development process. -The publishing process is typically performed after you finish testing your application in a debug -environment. Also, as a best practice, your application should meet all of your release criteria for -functionality, performance, and stability before you begin the publishing process.

    - -Shows where the publishing
-       process fits into the overall development process -

    - Figure 1. Publishing is the last phase of the Android application development process. -

    - -

    Preparing Your Application for Release

    - -

    Preparing your application for release is a multi-step process that involves the following -tasks:

    - -
      - -
    • Configuring your application for release. -

      At a minimum you need to remove {@link android.util.Log} calls and remove the - android:debuggable - attribute from your manifest file. You should also provide values for the - android:versionCode and android:versionName attributes, which are - located in the - <manifest> - element. You may also have to configure several other settings to meet Google Play - requirements or accomodate whatever method you're using to release your application.

      -
    • -
    • Building and signing a release version of your application. -

      The Android Development Tools (ADT) plugin and the Ant build script that are provided - with the Android SDK tools provide everything you need to build and sign a release version of - your application.

      -
    • -
    • Testing the release version of your application. -

      Before you distribute your application, you should thoroughly test the release version on at - least one target handset device and one target tablet device.

      -
    • -
    • Updating application resources for release. -

      You need to be sure that all application resources such as multimedia files and graphics - are updated and included with your application or staged on the proper production servers.

      -
    • -
    • Preparing remote servers and services that your application depends on. -

      If your application depends on external servers or services, you need to be sure they - are secure and production ready.

      -
    • -
    - -

    You may have to perform several other tasks as part of the preparation process. For example, you -will need to get a private key for signing your application, and you may need to get a Maps API -release key if you are using the Google Maps external -library. You will also need to create an icon for your application, and you may want to prepare -an End User License Agreement (EULA) to protect your person, organization, and intellectual -property.

    - -

    When you are finished preparing your application for release you will have a signed -.apk file that you can distribute to users.

    - -

    To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This -topic provides step-by-step instructions for configuring and building a release version of your -application.

    - -

    Releasing Your Application to Users

    - -

    You can release your Android applications several ways. Usually, you release applications -through an application marketplace, such as Google Play, but you can also release applications -on your own website or by sending an application directly to a user. Google Play is the -recommended marketplace for Android applications and is particularly useful if you want to -distribute your applications to a large global audience. The other two release methods—server -distribution and email distribution—are useful if you are releasing an application to a small -group of users (for example, a work group in an enterprise environment), or if you do not want to -make your application available to the general public.

    - -

    Releasing Your Applications on Google Play

    - -

    Google Play is a robust publishing platform that helps you publicize, sell, and distribute -your Android applications to users around the world. When you release your applications through -Google Play you have access to a suite of developer tools that let you analyze your sales, -identify market trends, and control who your applications are being distributed to. You also have -access to several revenue-enhancing features that are not available anywhere else, such as in-app billing and application licensing. This rich array of tools -and features, coupled with numerous end-user community features, makes Google Play the premier -marketplace for selling and buying Android applications.

    - -

    Releasing your application on Google Play is a simple process that involves three basic - steps:

    - -
    - Screenshot showing the graphical user interface element that allows unknown sources
-       to be installed -

    - Figure 2. The Unknown sources setting lets you install - applications that are not published on Google Play . -

    -
    - -
      -
    • Preparing promotional materials. -

      To fully leverage the marketing and publicity capabilities of Google Play, you need to - create promotional materials for your application, such as screenshots, videos, graphics, and - promotional text.

      -
    • -
    • Configuring options and uploading assets. -

      Google Play lets you target your application to a worldwide pool of users and devices. - By configuring various Google Play settings, you can choose the countries you want to - reach, the listing languages you want to use, and the price you want to charge in each - country. You can also configure listing details such as the application type, category, and - content rating. When you are done configuring options you can upload your promotional materials - and your application as a draft (unpublished) application.

      -
    • -
    • Publishing the release version of your application. -

      If you are satisfied that your publishing settings are correctly configured and your - uploaded application is ready to be released to the public, you can simply click - Publish in the developer console and within minutes your application will be - live and available for download around the world.

      -
    • -
    - -

    For information about Google Play, see Publishing on Google Play. This -topic provides an introduction to Google Play features and provides a step-by-step guide for -distributing your applications on Google Play.

    - -

    Releasing your application on your own website

    - -

    If you do not want to release your application on an application marketplace like Google Play, -you can release your application by making it available for download on your own website or server. -To do this, you must first prepare your application for release (that is, you must build it for -release and sign it). Then all you need to do is host the release-ready application on your website -and provide a download link for the application. When users browse to your website with their -Android-powered devices and download your application, the Android system will automatically start -installing the application on the device. However, the installation process will start automatically -only if the user has configured their device to allow the installation of non-Google Play -applications.

    - -
    - Screenshot showing the graphical user interface users see when you send them an app -

    - Figure 3. Users can simply click Install when you send them - an application via email. -

    -
    - -

    By default, Android-powered devices allow users to install applications only if the applications -have been downloaded from Google Play. To allow the installation of applications from other -sources, users need to enable the Unknown sources setting on their devices, and -they need to make this configuration change before they download your application to their -device (see figure 2).

    - -

    Note: Some network providers do not allow users to install -applications from unknown sources.

    - -

    Although it is relatively easy to release your application on your own website, it can be -inefficient and cumbersome. For example, if you want to monetize your application you will -have to process and track all financial transactions yourself and you will not be able to use -Google Play's in-app billing feature to sell in-app products. In addition, you will not be -able to use the licensing feature to help prevent unauthorized installation and use of your -application.

    - -

    Releasing your application through email

    - -

    The easiest and quickest way to release your application is to send it to a user through -email. To do this, you prepare your application for release and then attach it to an email -and send it to a user. When the user opens your email message on their Android-powered device -the Android system will recognize the .apk and display an Install Now -button in the email message (see figure 3). Users can install your application by touching the -button.

    - -

    Note: The Install Now button appears only if a -user has configured their device to allow the installation of non-Google Play applications and -they open your email with the native Gmail application.

    - -

    Releasing applications through email is convenient if you are sending your application to -only a few trusted users, but it provides few protections from piracy and unauthorized -distribution; that is, anyone you send your application to can simply forward it to someone else. -else. diff --git a/docs/html/guide/publishing/versioning.jd b/docs/html/guide/publishing/versioning.jd deleted file mode 100644 index da57e3ebc710..000000000000 --- a/docs/html/guide/publishing/versioning.jd +++ /dev/null @@ -1,174 +0,0 @@ -page.title=Versioning Your Applications -@jd:body - -

    -
    - -

    Quickview

    - -
      -
    • Your application must be versioned
    • -
    • You set the version in the application's manifest file
    • -
    • How you version your applications affects how users upgrade
    • -
    • Determine your versioning strategy early in the development process, including considerations for future releases.
    • -
    - -

    In this document

    - -
      -
    1. Setting Application Version
    2. -
    3. Specifying Your Application's System API Requirements -
    - - -

    See also

    - -
      -
    1. Preparing to Publish Your Application
    2. -
    3. Publishing On Google Play
    4. -
    5. The AndroidManifest.xml File
    6. -
    - -
    -
    - -

    Versioning is a critical component of your application upgrade and maintenance -strategy. Versioning is important because:

    - -
      -
    • Users need to have specific information about the application version that -is installed on their devices and the upgrade versions available for -installation.
    • -
    • Other applications — including other applications that you publish as -a suite — need to query the system for your application's version, to -determine compatibility and identify dependencies.
    • -
    • Services through which you will publish your application(s) may also need to -query your application for its version, so that they can display the version to -users. A publishing service may also need to check the application version to -determine compatibility and establish upgrade/downgrade relationships.
    • -
    - -

    The Android system does not use app version information to enforce -restrictions on upgrades, downgrades, or compatibility of third-party apps. Instead, you (the -developer) are responsible for enforcing version restrictions within your application or by -informing users of the version restrictions and limitations. The Android system does, however, -enforce system version compatibility as expressed by the minSdkVersion attribute in the -manifest. This attribute allows an application to specify the minimum system API with which it is -compatible. For more information see Specifying Minimum System API -Version.

    - -

    Setting Application Version

    -

    To define the version information for your application, you set attributes in -the application's manifest file. Two attributes are available, and you should -always define values for both of them:

    - -
      -
    • android:versionCode — An integer value that represents -the version of the application code, relative to other versions. - -

      The value is an integer so that other applications can programmatically -evaluate it, for example to check an upgrade or downgrade relationship. You can -set the value to any integer you want, however you should make sure that each -successive release of your application uses a greater value. The system does not -enforce this behavior, but increasing the value with successive releases is -normative.

      - -

      Typically, you would release the first version of your application with -versionCode set to 1, then monotonically increase the value with each release, -regardless whether the release constitutes a major or minor release. This means -that the android:versionCode value does not necessarily have a -strong resemblance to the application release version that is visible to the -user (see android:versionName, below). Applications and publishing -services should not display this version value to users.

      -
    • -
    • android:versionName — A string value that represents the -release version of the application code, as it should be shown to users. -

      The value is a string so that you can describe the application version as a -<major>.<minor>.<point> string, or as any other type of -absolute or relative version identifier.

      - -

      As with android:versionCode, the system does not use this value -for any internal purpose, other than to enable applications to display it to -users. Publishing services may also extract the android:versionName -value for display to users.

      -
    • -
    - -

    You define both of these version attributes in the -<manifest> element of the manifest file.

    - -

    Here's an example manifest that shows the android:versionCode -and android:versionName attributes in the -<manifest> element.

    - -
    -<?xml version="1.0" encoding="utf-8"?>
    -<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    -      package="com.example.package.name"
    -      android:versionCode="2"
    -      android:versionName="1.1">
    -    <application android:icon="@drawable/icon" android:label="@string/app_name">
    -        ...
    -    </application>
    -</manifest>
    -
    - -

    In this example, note that android:versionCode value indicates -that the current .apk contains the second release of the application code, which -corresponds to a minor follow-on release, as shown by the -android:versionName string.

    - -

    The Android framework provides an API to let applications query the system -for version information about your application. To obtain version information, -applications use the -{@link android.content.pm.PackageManager#getPackageInfo(java.lang.String, int)} -method of {@link android.content.pm.PackageManager PackageManager}.

    - -

    Specifying Your Application's System API Requirements

    - -

    If your application requires a specific minimum version of the Android -platform, or is designed only to support a certain range of Android platform -versions, you can specify those version requirements as API Level identifiers -in the application's manifest file. Doing so ensures that your -application can only be installed on devices that -are running a compatible version of the Android system.

    - -

    To specify API Level requirements, add a <uses-sdk> -element in the application's manifest, with one or more of these attributes:

    - -
      -
    • android:minSdkVersion — The minimum version -of the Android platform on which the application will run, specified -by the platform's API Level identifier.
    • -
    • android:targetSdkVersion — Specifies the API Level -on which the application is designed to run. In some cases, this allows the -application to use manifest elements or behaviors defined in the target -API Level, rather than being restricted to using only those defined -for the minimum API Level.
    • -
    • android:maxSdkVersion — The maximum version -of the Android platform on which the application is designed to run, -specified by the platform's API Level identifier. Important: Please read the <uses-sdk> -documentation before using this attribute.
    • -
    - -

    When preparing to install your application, the system checks the value of this -attribute and compares it to the system version. If the -android:minSdkVersion value is greater than the system version, the -system aborts the installation of the application. Similarly, the system -installs your application only if its android:maxSdkVersion -is compatible with the platform version.

    - -

    If you do not specify these attributes in your manifest, the system assumes -that your application is compatible with all platform versions, with no -maximum API Level.

    - -

    To specify a minimum platform version for your application, add a -<uses-sdk> element as a child of -<manifest>, then define the -android:minSdkVersion as an attribute.

    - -

    For more information, see the <uses-sdk> -manifest element documentation and the API Levels document.

    diff --git a/docs/html/guide/topics/admin/index.jd b/docs/html/guide/topics/admin/index.jd new file mode 100644 index 000000000000..b2a896f817c5 --- /dev/null +++ b/docs/html/guide/topics/admin/index.jd @@ -0,0 +1,22 @@ +page.title=Administration +page.landing=true +page.landing.intro=If you are an enterprise administrator, you can take advantage of APIs and system capabilities to manage Android devices and control access. +page.landing.image= + +@jd:body + + \ No newline at end of file diff --git a/docs/html/guide/topics/admin/keychain.jd b/docs/html/guide/topics/admin/keychain.jd new file mode 100644 index 000000000000..2ea24084e51b --- /dev/null +++ b/docs/html/guide/topics/admin/keychain.jd @@ -0,0 +1,4 @@ +page.title=Text and Input +@jd:body + +

    Add contnet here

    diff --git a/docs/html/guide/topics/appwidgets/index.jd b/docs/html/guide/topics/appwidgets/index.jd index ba7b67c9770f..a46f9a76f6ee 100644 --- a/docs/html/guide/topics/appwidgets/index.jd +++ b/docs/html/guide/topics/appwidgets/index.jd @@ -295,7 +295,7 @@ Guidelines.

    Creating the App Widget layout is simple if you're familiar with XML Layouts. +href="{@docRoot}guide/topics/ui/declaring-layout.html">Layouts. However, you must be aware that App Widget layouts are based on {@link android.widget.RemoteViews}, which do not support every kind of layout or view widget.

    @@ -516,7 +516,7 @@ consider starting a {@link android.app.Service} in the {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[]) onUpdate()} 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 Application +to an Application Not Responding (ANR) error. See the Wiktionary sample's AppWidgetProvider for an example of an App Widget running a {@link android.app.Service}.

    diff --git a/docs/html/guide/topics/clipboard/copy-paste.jd b/docs/html/guide/topics/clipboard/copy-paste.jd deleted file mode 100644 index 6c86f478cbf6..000000000000 --- a/docs/html/guide/topics/clipboard/copy-paste.jd +++ /dev/null @@ -1,1094 +0,0 @@ -page.title=Copy and Paste -@jd:body -
    -
    -

    Quickview

    -
      -
    • - A clipboard-based framework for copying and pasting data. -
    • -
    • - Supports both simple and complex data, including text strings, complex data - structures, text and binary stream data, and application assets. -
    • -
    • - Copies and pastes simple text directly to and from the clipboard. -
    • -
    • - Copies and pastes complex data using a content provider. -
    • -
    • - Requires API 11. -
    • -
    -

    In this document

    -
      -
    1. - The Clipboard Framework -
    2. -
    3. - Clipboard Classes -
        -
      1. - ClipboardManager -
      2. -
      3. - - ClipData, ClipDescription, and ClipData.Item - -
      4. -
      5. - ClipData convenience methods -
      6. -
      7. - Coercing the clipboard data to text -
      8. -
      -
    4. -
    5. - Copying to the Clipboard -
    6. -
    7. - Pasting from the Clipboard -
        -
      1. - Pasting plain text -
      2. -
      3. - Pasting data from a content URI -
      4. -
      5. - Pasting an Intent -
      6. -
      -
    8. -
    9. - Using Content Providers to Copy Complex Data -
        -
      1. - Encoding an identifier on the URI -
      2. -
      3. - Copying data structures -
      4. -
      5. - Copying data streams -
      6. -
      -
    10. -
    11. - Designing Effective Copy/Paste Functionality -
    12. -
    -

    Key classes

    -
      -
    1. - {@link android.content.ClipboardManager ClipboardManager} -
    2. -
    3. - {@link android.content.ClipData ClipData} -
    4. -
    5. - {@link android.content.ClipData.Item ClipData.Item} -
    6. -
    7. - {@link android.content.ClipDescription ClipDescription} -
    8. -
    9. - {@link android.net.Uri Uri} -
    10. -
    11. - {@link android.content.ContentProvider} -
    12. -
    13. - {@link android.content.Intent Intent} -
    14. -
    -

    Related Samples

    -
      -
    1. - - Note Pad sample application -
    2. -
    -

    See also

    -
      -
    1. - Content Providers -
    2. -
    -
    -
    -

    - Android provides a powerful clipboard-based framework for copying and pasting. It - supports both simple and complex data types, including text strings, complex data - structures, text and binary stream data, and even application assets. Simple text data is stored - directly in the clipboard, while complex data is stored as a reference that the pasting - application resolves with a content provider. Copying and pasting works both within an - application and between applications that implement the framework. -

    - -

    - Since a part of the framework uses content providers, this topic assumes some - familiarity with the Android Content Provider API, which is described in the topic - Content Providers. -

    -

    The Clipboard Framework

    -

    - When you use the clipboard framework, you put data into a clip object, and then - put the clip object on the system-wide clipboard. The clip object can take one of three forms: -

    -
    -
    Text
    -
    - A text string. You put the string directly into the clip object, which you then put onto - the clipboard. To paste the string, you get the clip object from the clipboard and copy - the string to into your application's storage. -
    -
    URI
    -
    - A {@link android.net.Uri} object representing any form of URI. This is primarily for - copying complex data from a content provider. To copy data, you put a - {@link android.net.Uri} object into a clip object and put the clip object onto - the clipboard. To paste the data, you get the clip object, get the - {@link android.net.Uri} object, resolve it to a data source such as a content provider, - and copy the data from the source into your application's storage. -
    -
    Intent
    -
    - An {@link android.content.Intent}. This supports copying application shortcuts. To copy - data, you create an Intent, put it into a clip object, and put the clip object onto the - clipboard. To paste the data, you get the clip object and then copy the Intent object - into your application's memory area. -
    -
    -

    - The clipboard holds only one clip object at a time. When an application puts a clip object on - the clipboard, the previous clip object disappears. -

    -

    - If you want to allow users to paste data into your application, you don't have to handle all - types of data. You can examine the data on the clipboard before you give users the option to - paste it. Besides having a certain data form, the clip object also contains metadata that tells - you what MIME type or types are available. This metadata helps you decide if your application - can do something useful with the clipboard data. For example, if you have an application that - primarily handles text you may want to ignore clip objects that contain a URI or Intent. -

    -

    - You may also want to allow users to paste text regardless of the form of data on the - clipboard. To do this, you can force the clipboard data into a text representation, and then - paste this text. This is described in the section Coercing the - clipboard to text. -

    -

    Clipboard Classes

    -

    - This section describes the classes used by the clipboard framework. -

    -

    ClipboardManager

    -

    - In the Android system, the system clipboard is represented by the global - {@link android.content.ClipboardManager} class. You do not instantiate this - class directly; instead, you get a reference to it by invoking - {@link android.content.Context#getSystemService(String) getSystemService(CLIPBOARD_SERVICE)}. -

    -

    ClipData, ClipData.Item, and ClipDescription

    -

    - To add data to the clipboard, you create a {@link android.content.ClipData} object that - contains both a description of the data and the data itself. The clipboard holds only one - {@link android.content.ClipData} at a time. A {@link android.content.ClipData} contains a - {@link android.content.ClipDescription} object and one or more - {@link android.content.ClipData.Item} objects. -

    -

    - A {@link android.content.ClipDescription} object contains metadata about the clip. In - particular, it contains an array of available MIME types for the clip's data. When you put a - clip on the clipboard, this array is available to pasting applications, which can examine it to - see if they can handle any of available the MIME types. -

    -

    - A {@link android.content.ClipData.Item} object contains the text, URI, or Intent data: -

    -
    -
    Text
    -
    - A {@link java.lang.CharSequence}. -
    -
    URI
    -
    - A {@link android.net.Uri}. This usually contains a content provider URI, although any - URI is allowed. The application that provides the data puts the URI on the clipboard. - Applications that want to paste the data get the URI from the clipboard and use it to - access the content provider (or other data source) and retrieve the data. -
    -
    Intent
    -
    - An {@link android.content.Intent}. This data type allows you to copy an application shortcut - to the clipboard. Users can then paste the shortcut into their applications for later use. -
    -
    -

    - You can add more than one {@link android.content.ClipData.Item} object to a clip. This allows - users to copy and paste multiple selections as a single clip. For example, if you have a list - widget that allows the user to select more than one item at a time, you can copy all the items - to the clipboard at once. To do this, you create a separate - {@link android.content.ClipData.Item} for each list item, and then you add the - {@link android.content.ClipData.Item} objects to the {@link android.content.ClipData} object. -

    -

    ClipData convenience methods

    -

    - The {@link android.content.ClipData} class provides static convenience methods for creating - a {@link android.content.ClipData} object with a single {@link android.content.ClipData.Item} - object and a simple {@link android.content.ClipDescription} object: -

    -
    -
    -{@link android.content.ClipData#newPlainText(CharSequence,CharSequence) newPlainText(label, text)} -
    -
    - Returns a {@link android.content.ClipData} object whose single - {@link android.content.ClipData.Item} object contains a text string. The - {@link android.content.ClipDescription} object's label is set to label. - The single MIME type in {@link android.content.ClipDescription} is - {@link android.content.ClipDescription#MIMETYPE_TEXT_PLAIN}. -

    - Use -{@link android.content.ClipData#newPlainText(CharSequence,CharSequence) newPlainText()} - to create a clip from a text string. -

    -
    -{@link android.content.ClipData#newUri(ContentResolver, CharSequence, Uri) newUri(resolver, label, URI)} -
    -
    - Returns a {@link android.content.ClipData} object whose single - {@link android.content.ClipData.Item} object contains a URI. The - {@link android.content.ClipDescription} object's label is set to label. - If the URI is a content URI ({@link android.net.Uri#getScheme() Uri.getScheme()} returns - content:), the method uses the {@link android.content.ContentResolver} object - provided in resolver to retrieve the available MIME types from the - content provider and store them in {@link android.content.ClipDescription}. For a URI that - is not a content: URI, the method sets the MIME type to - {@link android.content.ClipDescription#MIMETYPE_TEXT_URILIST}. -

    - Use -{@link android.content.ClipData#newUri(ContentResolver, CharSequence, Uri) newUri()} - to create a clip from a URI, particularly a content: URI. -

    -
    -
    - {@link android.content.ClipData#newIntent(CharSequence, Intent) newIntent(label, intent)} -
    -
    - Returns a {@link android.content.ClipData} object whose single - {@link android.content.ClipData.Item} object contains an {@link android.content.Intent}. - The {@link android.content.ClipDescription} object's label is set to label. - The MIME type is set to {@link android.content.ClipDescription#MIMETYPE_TEXT_INTENT}. -

    - Use -{@link android.content.ClipData#newIntent(CharSequence, Intent) newIntent()} - to create a clip from an Intent object. -

    -
    -

    Coercing the clipboard data to text

    -

    - Even if your application only handles text, you can copy non-text data from the - clipboard by converting it with the method - {@link android.content.ClipData.Item#coerceToText(Context) ClipData.Item.coerceToText()}. -

    -

    - This method converts the data in {@link android.content.ClipData.Item} to text and - returns a {@link java.lang.CharSequence}. The value that - {@link android.content.ClipData.Item#coerceToText(Context) ClipData.Item.coerceToText()} - returns is based on the form of data in {@link android.content.ClipData.Item}: -

    -
    -
    Text
    -
    - If {@link android.content.ClipData.Item} is text - ({@link android.content.ClipData.Item#getText()} is not null), - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} returns the - text. -
    -
    URI
    -
    - If {@link android.content.ClipData.Item} is a URI - ({@link android.content.ClipData.Item#getUri()} is not null), - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} tries to use - it as a content URI: -
      -
    • - If the URI is a content URI and the provider can return a text stream, - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} returns - a text stream. -
    • -
    • - If the URI is a content URI but the provider does not offer a text stream, - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} returns - a representation of the URI. The representation is the same as that returned by - {@link android.net.Uri#toString() Uri.toString()}. -
    • -
    • - If the URI is not a content URI, - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} returns - a representation of the URI. The representation is the same as that returned by - {@link android.net.Uri#toString() Uri.toString()}. -
    • -
    -
    -
    Intent
    -
    - If {@link android.content.ClipData.Item} is an Intent - ({@link android.content.ClipData.Item#getIntent()} is not null), - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} converts it to - an Intent URI and returns it. The representation is the same as that returned by - {@link android.content.Intent#toUri(int) Intent.toUri(URI_INTENT_SCHEME)}. -
    -
    -

    - The clipboard framework is summarized in Figure 1. To copy data, an application puts a - {@link android.content.ClipData} object on the {@link android.content.ClipboardManager} global - clipboard. The {@link android.content.ClipData} contains one or more - {@link android.content.ClipData.Item} objects and one - {@link android.content.ClipDescription} object. To paste data, an application gets the - {@link android.content.ClipData}, gets its MIME type from the - {@link android.content.ClipDescription}, and gets the data either from - the {@link android.content.ClipData.Item} or from the content provider referred to by - {@link android.content.ClipData.Item}. -

    - - A block diagram of the copy and paste framework -

    - Figure 1. The Android clipboard framework -

    -

    Copying to the Clipboard

    -

    - As described previously, to copy data to the clipboard you get a handle to the global - {@link android.content.ClipboardManager} object, create a {@link android.content.ClipData} - object, add a {@link android.content.ClipDescription} and one or more - {@link android.content.ClipData.Item} objects to it, and add the finished - {@link android.content.ClipData} object to the {@link android.content.ClipboardManager} object. - This is described in detail in the following procedure: -

    -
      -
    1. - If you are copying data using a content URI, set up a content - provider. -

      - The - Note Pad sample application is an example of using a content provider for - copying and pasting. The - - NotePadProvider class implements the content provider. The - - NotePad class defines a contract between the provider and other applications, - including the supported MIME types. -

      -
    2. -
    3. - Get the system clipboard: -
      -
      -...
      -
      -// if the user selects copy
      -case R.id.menu_copy:
      -
      -// Gets a handle to the clipboard service.
      -ClipboardManager clipboard = (ClipboardManager)
      -        getSystemService(Context.CLIPBOARD_SERVICE);
      -
      -
    4. -
    5. -

      - Copy the data to a new {@link android.content.ClipData} object: -

      -
        -
      • -

        For text

        -
        -// Creates a new text clip to put on the clipboard
        -ClipData clip = ClipData.newPlainText("simple text","Hello, World!");
        -
        -
      • -
      • -

        For a URI

        -

        - This snippet constructs a URI by encoding a record ID onto the content URI - for the provider. This technique is covered in more detail - in the section Encoding an identifier on the URI: -

        -
        -// Creates a Uri based on a base Uri and a record ID based on the contact's last name
        -// Declares the base URI string
        -private static final String CONTACTS = "content://com.example.contacts";
        -
        -// Declares a path string for URIs that you use to copy data
        -private static final String COPY_PATH = "/copy";
        -
        -// Declares the Uri to paste to the clipboard
        -Uri copyUri = Uri.parse(CONTACTS + COPY_PATH + "/" + lastName);
        -
        -...
        -
        -// Creates a new URI clip object. The system uses the anonymous getContentResolver() object to
        -// get MIME types from provider. The clip object's label is "URI", and its data is
        -// the Uri previously created.
        -ClipData clip = ClipData.newUri(getContentResolver(),"URI",copyUri);
        -
        -
      • -
      • -

        For an Intent

        -

        - This snippet constructs an Intent for an application - and then puts it in the clip object: -

        -
        -// Creates the Intent
        -Intent appIntent = new Intent(this, com.example.demo.myapplication.class);
        -
        -...
        -
        -// Creates a clip object with the Intent in it. Its label is "Intent" and its data is
        -// the Intent object created previously
        -ClipData clip = ClipData.newIntent("Intent",appIntent);
        -
        -
      • -
      -
    6. -
    7. - Put the new clip object on the clipboard: -
      -// Set the clipboard's primary clip.
      -clipboard.setPrimaryClip(clip);
      -
      -
    8. -
    -

    Pasting from the Clipboard

    -

    - As described previously, you paste data from the clipboard by getting the global clipboard - object, getting the clip object, looking at its data, and if possible copying the data from - the clip object to your own storage. This section describes in detail how to do this for - the three forms of clipboard data. -

    -

    Pasting plain text

    -

    - To paste plain text, first get the global clipboard and verify that it can return plain text. - Then get the clip object and copy its text to your own storage using - {@link android.content.ClipData.Item#getText()}, as described in the following procedure: -

    -
      -
    1. - Get the global {@link android.content.ClipboardManager} object using - {@link android.content.Context#getSystemService(String) getSystemService(CLIPBOARD_SERVICE)}. Also - declare a global variable to contain the pasted text: -
      -ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
      -
      -String pasteData = "";
      -
      -
      -
    2. -
    3. - Next, determine if you should enable or disable the "paste" option in the - current Activity. You should verify that the clipboard contains a clip and that you - can handle the type of data represented by the clip: -
      -// Gets the ID of the "paste" menu item
      -MenuItem mPasteItem = menu.findItem(R.id.menu_paste);
      -
      -// If the clipboard doesn't contain data, disable the paste menu item.
      -// If it does contain data, decide if you can handle the data.
      -if (!(clipboard.hasPrimaryClip())) {
      -
      -    mPasteItem.setEnabled(false);
      -
      -    } else if (!(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {
      -
      -        // This disables the paste menu item, since the clipboard has data but it is not plain text
      -        mPasteItem.setEnabled(false);
      -    } else {
      -
      -        // This enables the paste menu item, since the clipboard contains plain text.
      -        mPasteItem.setEnabled(true);
      -    }
      -}
      -
      -
    4. -
    5. - Copy the data from the clipboard. This point in the program is only reachable if the - "paste" menu item is enabled, so you can assume that the clipboard contains - plain text. You do not yet know if it contains a text string or a URI that points to plain - text. The following snippet tests this, but it only shows the code for handling plain text: -
      -// Responds to the user selecting "paste"
      -case R.id.menu_paste:
      -
      -// Examines the item on the clipboard. If getText() does not return null, the clip item contains the
      -// text. Assumes that this application can only handle one item at a time.
      - ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
      -
      -// Gets the clipboard as text.
      -pasteData = item.getText();
      -
      -// If the string contains data, then the paste operation is done
      -if (pasteData != null) {
      -    return;
      -
      -// The clipboard does not contain text. If it contains a URI, attempts to get data from it
      -} else {
      -    Uri pasteUri = item.getUri();
      -
      -    // If the URI contains something, try to get text from it
      -    if (pasteUri != null) {
      -
      -        // calls a routine to resolve the URI and get data from it. This routine is not
      -        // presented here.
      -        pasteData = resolveUri(Uri);
      -        return;
      -    } else {
      -
      -    // Something is wrong. The MIME type was plain text, but the clipboard does not contain either
      -    // text or a Uri. Report an error.
      -    Log.e("Clipboard contains an invalid data type");
      -    return;
      -    }
      -}
      -
      -
    6. -
    -

    Pasting data from a content URI

    -

    - If the {@link android.content.ClipData.Item} object contains a content URI and you - have determined that you can handle one of its MIME types, create a - {@link android.content.ContentResolver} and then call the appropriate content provider - method to retrieve the data. -

    -

    - The following procedure describes how to get data from a content provider based on a - content URI on the clipboard. It checks that a MIME type that the application can use - is available from the provider: -

    -
      -
    1. - Declare a global variable to contain the MIME type: -
      -// Declares a MIME type constant to match against the MIME types offered by the provider
      -public static final String MIME_TYPE_CONTACT = "vnd.android.cursor.item/vnd.example.contact"
      -
      -
    2. -
    3. - Get the global clipboard. Also get a content resolver so you can access the content - provider: -
      -// Gets a handle to the Clipboard Manager
      -ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
      -
      -// Gets a content resolver instance
      -ContentResolver cr = getContentResolver();
      -
      -
    4. -
    5. - Get the primary clip from the clipboard, and get its contents as a URI: -
      -// Gets the clipboard data from the clipboard
      -ClipData clip = clipboard.getPrimaryClip();
      -
      -if (clip != null) {
      -
      -    // Gets the first item from the clipboard data
      -    ClipData.Item item = clip.getItemAt(0);
      -
      -    // Tries to get the item's contents as a URI
      -    Uri pasteUri = item.getUri();
      -
      -
    6. -
    7. - Test to see if the URI is a content URI by calling - {@link android.content.ContentResolver#getType(Uri) getType(Uri)}. This method returns - null if Uri does not point to a valid content provider: -
      -    // If the clipboard contains a URI reference
      -    if (pasteUri != null) {
      -
      -        // Is this a content URI?
      -        String uriMimeType = cr.getType(pasteUri);
      -
      -
    8. -
    9. - Test to see if the content provider supports a MIME type that the current application - understands. If it does, call - {@link android.content.ContentResolver#query(Uri, String[], String, String[], String) - ContentResolver.query()} to get the data. The return value is a - {@link android.database.Cursor}: -
      -        // If the return value is not null, the Uri is a content Uri
      -        if (uriMimeType != null) {
      -
      -            // Does the content provider offer a MIME type that the current application can use?
      -            if (uriMimeType.equals(MIME_TYPE_CONTACT)) {
      -
      -                // Get the data from the content provider.
      -                Cursor pasteCursor = cr.query(uri, null, null, null, null);
      -
      -                // If the Cursor contains data, move to the first record
      -                if (pasteCursor != null) {
      -                    if (pasteCursor.moveToFirst()) {
      -
      -                    // get the data from the Cursor here. The code will vary according to the
      -                    // format of the data model.
      -                    }
      -                }
      -
      -                // close the Cursor
      -                pasteCursor.close();
      -             }
      -         }
      -     }
      -}
      -
      -
    10. -
    -

    Pasting an Intent

    -

    - To paste an Intent, first get the global clipboard. Examine the - {@link android.content.ClipData.Item} object to see if it contains an Intent. Then call - {@link android.content.ClipData.Item#getIntent()} to copy the Intent to your own storage. - The following snippet demonstrates this: -

    -
    -// Gets a handle to the Clipboard Manager
    -ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    -
    -// Checks to see if the clip item contains an Intent, by testing to see if getIntent() returns null
    -Intent pasteIntent = clipboard.getPrimaryClip().getItemAt(0).getIntent();
    -
    -if (pasteIntent != null) {
    -
    -    // handle the Intent
    -
    -} else {
    -
    -    // ignore the clipboard, or issue an error if your application was expecting an Intent to be
    -    // on the clipboard
    -}
    -
    -

    Using Content Providers to Copy Complex Data

    -

    - Content providers support copying complex data such as database records or file streams. - To copy the data, you put a content URI on the clipboard. Pasting applications then get this - URI from the clipboard and use it to retrieve database data or file stream descriptors. -

    -

    - Since the pasting application only has the content URI for your data, it needs to know which - piece of data to retrieve. You can provide this information by encoding an identifier for the - data on the URI itself, or you can provide a unique URI that will return the data you want to - copy. Which technique you choose depends on the organization of your data. -

    -

    - The following sections describe how to set up URIs, how to provide complex data, and how to - provide file streams. The descriptions assume that you are familiar with the general principles - of content provider design. -

    -

    Encoding an identifier on the URI

    -

    - A useful technique for copying data to the clipboard with a URI is to encode an identifier for - the data on the URI itself. Your content provider can then get the identifier from the URI and - use it to retrieve the data. The pasting application doesn't have to know that the identifier - exists; all it has to do is get your "reference" (the URI plus the identifier) from - the clipboard, give it your content provider, and get back the data. -

    -

    - You usually encode an identifier onto a content URI by concatenating it to the end of the URI. - For example, suppose you define your provider URI as the following string: -

    -
    -"content://com.example.contacts"
    -
    -

    - If you want to encode a name onto this URI, you would use the following snippet: -

    -
    -String uriString = "content://com.example.contacts" + "/" + "Smith"
    -
    -// uriString now contains content://com.example.contacts/Smith.
    -
    -// Generates a uri object from the string representation
    -Uri copyUri = Uri.parse(uriString);
    -
    -

    - If you are already using a content provider, you may want to add a new URI path that indicates - the URI is for copying. For example, suppose you already have the following URI paths: -

    -
    -"content://com.example.contacts"/people
    -"content://com.example.contacts"/people/detail
    -"content://com.example.contacts"/people/images
    -
    -

    - You could add another path that is specific to copy URIs: -

    -
    -"content://com.example.contacts/copying"
    -
    -

    - You could then detect a "copy" URI by pattern-matching and handle it with code that - is specific for copying and pasting. -

    -

    - You normally use the encoding technique if you're already using a content provider, internal - database, or internal table to organize your data. In these cases, you have multiple pieces of - data you want to copy, and presumably a unique identifier for each piece. In response to a - query from the pasting application, you can look up the data by its identifier and return it. -

    -

    - If you don't have multiple pieces of data, then you probably don't need to encode an identifier. - You can simply use a URI that is unique to your provider. In response to a query, your provider - would return the data it currently contains. -

    -

    - Getting a single record by ID is used in the - Note Pad sample application to - open a note from the notes list. The sample uses the _id field from an SQL - database, but you can have any numeric or character identifier you want. -

    -

    Copying data structures

    -

    - You set up a content provider for copying and pasting complex data as a subclass of the - {@link android.content.ContentProvider} component. You should also encode the URI you put on - the clipboard so that it points to the exact record you want to provide. In addition, you - have to consider the existing state of your application: -

    -
      -
    • - If you already have a content provider, you can add to its functionality. You may only - need to modify its -{@link android.content.ContentResolver#query(Uri, String[], String, String[], String) query()} - method to handle URIs coming from applications that want to paste data. You will - probably want to modify the method to handle a "copy" URI pattern. -
    • -
    • - If your application maintains an internal database, you may - want to move this database into a content provider to facilitate copying from it. -
    • -
    • - If you are not currently using a database, you can implement a simple content provider - whose sole purpose is to offer data to applications that are pasting from the - clipboard. -
    • -
    -

    -In the content provider, you will want to override at least the following methods: -

    -
    -
    -{@link android.content.ContentResolver#query(Uri, String[], String, String[], String) query()} -
    -
    - Pasting applications will assume that they can get your data by using this method with - the URI you put on the clipboard. To support copying, you should have this method - detect URIs that contain a special "copy" path. Your application can then - create a "copy" URI to put on the clipboard, containing the copy path and - a pointer to the exact record you want to copy. -
    -
    - {@link android.content.ContentProvider#getType(Uri) getType()} -
    -
    - This method should return the MIME type or types for the data you intend to copy. The method - {@link android.content.ClipData#newUri(ContentResolver, CharSequence, Uri) newUri()} calls - {@link android.content.ContentProvider#getType(Uri) getType()} in order to put the MIME - types into the new {@link android.content.ClipData} object. -

    - MIME types for complex data are described in the topic - Content Providers. -

    -
    -
    -

    - Notice that you don't have to have any of the other content provider methods such as - {@link android.content.ContentProvider#insert(Uri, ContentValues) insert()} or - {@link android.content.ContentProvider#update(Uri, ContentValues, String, String[]) update()}. - A pasting application only needs to get your supported MIME types and copy data from your - provider. If you already have these methods, they won't interfere with copy operations. -

    -

    - The following snippets demonsrate how to set up your application to copy complex data: -

    -
      -
    1. -

      - In the global constants for your application, - declare a base URI string and a path that identifies URI strings you are - using to copy data. Also declare a MIME type for the copied data: -

      -
      -// Declares the base URI string
      -private static final String CONTACTS = "content://com.example.contacts";
      -
      -// Declares a path string for URIs that you use to copy data
      -private static final String COPY_PATH = "/copy";
      -
      -// Declares a MIME type for the copied data
      -public static final String MIME_TYPE_CONTACT = "vnd.android.cursor.item/vnd.example.contact"
      -
      -
    2. -
    3. - In the Activity from which users copy data, - set up the code to copy data to the clipboard. In response to a copy request, put - the URI on the clipboard: -
      -public class MyCopyActivity extends Activity {
      -
      -    ...
      -
      -// The user has selected a name and is requesting a copy.
      -case R.id.menu_copy:
      -
      -    // Appends the last name to the base URI
      -    // The name is stored in "lastName"
      -    uriString = CONTACTS + COPY_PATH + "/" + lastName;
      -
      -    // Parses the string into a URI
      -    Uri copyUri = Uri.parse(uriString);
      -
      -    // Gets a handle to the clipboard service.
      -    ClipboardManager clipboard = (ClipboardManager)
      -        getSystemService(Context.CLIPBOARD_SERVICE);
      -
      -    ClipData clip = ClipData.newUri(getContentResolver(), "URI", copyUri);
      -
      -    // Set the clipboard's primary clip.
      -    clipboard.setPrimaryClip(clip);
      -
      -
    4. - -
    5. -

      - In the global scope of your content provider, create a URI matcher and add a URI - pattern that will match URIs you put on the clipboard: -

      -
      -public class MyCopyProvider extends ContentProvider {
      -
      -    ...
      -
      -// A Uri Match object that simplifies matching content URIs to patterns.
      -private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
      -
      -// An integer to use in switching based on the incoming URI pattern
      -private static final int GET_SINGLE_CONTACT = 0;
      -
      -...
      -
      -// Adds a matcher for the content URI. It matches
      -// "content://com.example.contacts/copy/*"
      -sUriMatcher.addURI(CONTACTS, "names/*", GET_SINGLE_CONTACT);
      -
      -
    6. -
    7. -

      - Set up the - {@link android.content.ContentProvider#query(Uri, String[], String, String[], String) query()} - method. This method can handle different URI patterns, depending on how you code it, but - only the pattern for the clipboard copying operation is shown: -

      -
      -// Sets up your provider's query() method.
      -public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
      -    String sortOrder) {
      -
      -    ...
      -
      -    // Switch based on the incoming content URI
      -    switch (sUriMatcher.match(uri)) {
      -
      -    case GET_SINGLE_CONTACT:
      -
      -        // query and return the contact for the requested name. Here you would decode
      -        // the incoming URI, query the data model based on the last name, and return the result
      -        // as a Cursor.
      -
      -    ...
      -
      -}
      -
      -
    8. -
    9. -

      - Set up the {@link android.content.ContentProvider#getType(Uri) getType()} method to - return an appropriate MIME type for copied data: -

      -
      -// Sets up your provider's getType() method.
      -public String getType(Uri uri) {
      -
      -    ...
      -
      -    switch (sUriMatcher.match(uri)) {
      -
      -    case GET_SINGLE_CONTACT:
      -
      -            return (MIME_TYPE_CONTACT);
      -
      -
    10. -
    -

    - The section Pasting data from a content URI - describes how to get a content URI from the clipboard and use it to get and paste data. -

    -

    Copying data streams

    -

    - You can copy and paste large amounts of text and binary data as streams. The data can have - forms such as the following: -

    -
      -
    • - Files stored on the actual device. -
    • -
    • - Streams from sockets. -
    • -
    • - Large amounts of data stored in a provider's underlying database system. -
    • -
    -

    - A content provider for data streams provides access to its data with a file descriptor object - such as {@link android.content.res.AssetFileDescriptor} instead of a - {@link android.database.Cursor} object. The pasting application reads the data stream using - this file descriptor. -

    -

    - To set up your application to copy a data stream with a provider, follow these steps: -

    -
      -
    1. - Set up a content URI for the data stream you are putting on the clipboard. Options - for doing this include the following: -
        -
      • - Encode an identifier for the data stream onto the URI, - as described in the section - Encoding an identifier on the URI, and then maintain a - table in your provider that contains identifiers and the corresponding stream name. -
      • -
      • - Encode the stream name directly on the URI. -
      • -
      • - Use a unique URI that always returns the current stream from the provider. If you - use this option, you have to remember to update your provider to point to a - different stream whenever you copy the stream to the clipboard via the URI. -
      • -
      -
    2. -
    3. - Provide a MIME type for each type of data stream you plan to offer. Pasting applications - need this information to determine if they can paste the data on the clipboard. -
    4. -
    5. - Implement one of the {@link android.content.ContentProvider} methods that returns - a file descriptor for a stream. If you encode identifiers on the content URI, use this - method to determine which stream to open. -
    6. -
    7. - To copy the data stream to the clipboard, construct the content URI and place it - on the clipboard. -
    8. -
    -

    - To paste a data stream, an application gets the clip from the clipboard, gets the URI, and - uses it in a call to a {@link android.content.ContentResolver} file descriptor method that - opens the stream. The {@link android.content.ContentResolver} method calls the corresponding - {@link android.content.ContentProvider} method, passing it the content URI. Your provider - returns the file descriptor to {@link android.content.ContentResolver} method. The pasting - application then has the responsibility to read the data from the stream. -

    -

    - The following list shows the most important file descriptor methods for a content provider. - Each of these has a corresponding {@link android.content.ContentResolver} method with the - string "Descriptor" appended to the method name; for example, the - {@link android.content.ContentResolver} analog of - {@link android.content.ContentProvider#openAssetFile(Uri, String) openAssetFile()} is -{@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String) openAssetFileDescriptor()}: -

    -
    -
    -{@link android.content.ContentProvider#openTypedAssetFile(Uri,String,Bundle) openTypedAssetFile()} -
    -
    - This method should return an asset file descriptor, but only if the provided MIME type is - supported by the provider. The caller (the application doing the pasting) provides a MIME - type pattern. The content provider (of the application that has copied a URI to the - clipboard) returns an {@link android.content.res.AssetFileDescriptor} file handle if it - can provide that MIME type, or throws an exception if it can not. -

    - This method handles subsections of files. You can use it to read assets that the - content provider has copied to the clipboard. -

    -
    -
    - {@link android.content.ContentProvider#openAssetFile(Uri, String) openAssetFile()} -
    -
    - This method is a more general form of -{@link android.content.ContentProvider#openTypedAssetFile(Uri,String,Bundle) openTypedAssetFile()}. - It does not filter for allowed MIME types, but it can read subsections of files. -
    -
    - {@link android.content.ContentProvider#openFile(Uri, String) openFile()} -
    -
    - This is a more general form of - {@link android.content.ContentProvider#openAssetFile(Uri, String) openAssetFile()}. It can't - read subsections of files. -
    -
    -

    - You can optionally use the -{@link android.content.ContentProvider#openPipeHelper(Uri, String, Bundle, T, ContentProvider.PipeDataWriter) openPipeHelper()} - method with your file descriptor method. This allows the pasting application to read the - stream data in a background thread using a pipe. To use this method, you need to implement the - {@link android.content.ContentProvider.PipeDataWriter} interface. An example of doing this is - given in the Note Pad sample - application, in the openTypedAssetFile() method of - NotePadProvider.java. -

    -

    Designing Effective Copy/Paste Functionality

    -

    - To design effective copy and paste functionality for your application, remember these - points: -

    -
      -
    • - At any time, there is only one clip on the clipboard. A new copy operation by - any application in the system overwrites the previous clip. Since the user may - navigate away from your application and do a copy before returning, you can't assume - that the clipboard contains the clip that the user previously copied in your - application. -
    • -
    • - The intended purpose of multiple {@link android.content.ClipData.Item} - objects per clip is to support copying and pasting of multiple selections rather than - different forms of reference to a single selection. You usually want all of the - {@link android.content.ClipData.Item} objects in a clip to have the same form, that is, - they should all be simple text, content URI, or {@link android.content.Intent}, but not - a mixture. -
    • -
    • - When you provide data, you can offer different MIME representations. Add the MIME types - you support to the {@link android.content.ClipDescription}, and then - implement the MIME types in your content provider. -
    • -
    • - When you get data from the clipboard, your application is responsible for checking the - available MIME types and then deciding which one, if any, to use. Even if there is a - clip on the clipboard and the user requests a paste, your application is not required - to do the paste. You should do the paste if the MIME type is compatible. You - may choose to coerce the data on the clipboard to text using - {@link android.content.ClipData.Item#coerceToText(Context) coerceToText()} if you - choose. If your application supports more than one of the available MIME types, you can - allow the user to choose which one to use. -
    • -
    diff --git a/docs/html/guide/topics/connectivity/bluetooth.jd b/docs/html/guide/topics/connectivity/bluetooth.jd new file mode 100644 index 000000000000..832b8506466c --- /dev/null +++ b/docs/html/guide/topics/connectivity/bluetooth.jd @@ -0,0 +1,1086 @@ +page.title=Bluetooth +@jd:body + +
    +
    + +

    Quickview

    +
      +
    • Android's bluetooth APIs allow your application to perform wireless data transactions with +other devices
    • +
    + +

    In this document

    +
      +
    1. The Basics
    2. +
    3. Bluetooth Permissions
    4. +
    5. Setting Up Bluetooth
    6. +
    7. Finding Devices +
        +
      1. Querying paired devices
      2. +
      3. Discovering devices
      4. +
    8. +
    9. Connecting Devices +
        +
      1. Connecting as a server
      2. +
      3. Connecting as a client
      4. +
    10. +
    11. Managing a Connection
    12. +
    13. Working with Profiles +
        +
      1. Vendor-specific AT commands +
      2. Health Device Profile +
    14. +
    + +

    Key classes

    +
      +
    1. {@link android.bluetooth.BluetoothAdapter}
    2. +
    3. {@link android.bluetooth.BluetoothDevice}
    4. +
    5. {@link android.bluetooth.BluetoothSocket}
    6. +
    7. {@link android.bluetooth.BluetoothServerSocket}
    8. +
    + +

    Related samples

    +
      +
    1. Bluetooth Chat
    2. +
    3. Bluetooth HDP (Health Device Profile)
    4. +
    + +
    +
    + + +

    The Android platform includes support for the Bluetooth network stack, +which allows a device to wirelessly exchange data with other Bluetooth devices. +The application framework provides access to the Bluetooth functionality through +the Android Bluetooth APIs. These APIs let applications wirelessly +connect to other Bluetooth devices, enabling point-to-point and multipoint +wireless features.

    + +

    Using the Bluetooth APIs, an Android application can perform the +following:

    +
      +
    • Scan for other Bluetooth devices
    • +
    • Query the local Bluetooth adapter for paired Bluetooth devices
    • +
    • Establish RFCOMM channels
    • +
    • Connect to other devices through service discovery
    • +
    • Transfer data to and from other devices
    • +
    • Manage multiple connections
    • +
    + + +

    The Basics

    + +

    This document describes how to use the Android Bluetooth APIs to accomplish +the four major tasks necessary to communicate using Bluetooth: setting up +Bluetooth, finding devices that are either paired or available in the local +area, connecting devices, and transferring data between devices.

    + +

    All of the Bluetooth APIs are available in the {@link android.bluetooth} +package. Here's a summary of the classes and interfaces you will need to create Bluetooth +connections:

    + +
    +
    {@link android.bluetooth.BluetoothAdapter}
    +
    Represents the local Bluetooth adapter (Bluetooth radio). The +{@link android.bluetooth.BluetoothAdapter} is the entry-point for all Bluetooth +interaction. Using this, +you can discover other Bluetooth devices, query a list of bonded (paired) +devices, instantiate a {@link android.bluetooth.BluetoothDevice} using a known +MAC address, and create a {@link android.bluetooth.BluetoothServerSocket} to +listen for communications +from other devices.
    + +
    {@link android.bluetooth.BluetoothDevice}
    +
    Represents a remote Bluetooth device. Use this to request a connection +with a remote device through a {@link android.bluetooth.BluetoothSocket} or +query information about the +device such as its name, address, class, and bonding state.
    + +
    {@link android.bluetooth.BluetoothSocket}
    +
    Represents the interface for a Bluetooth socket (similar to a TCP +{@link java.net.Socket}). This is the connection point that allows +an application to exchange data with another Bluetooth device via InputStream +and OutputStream.
    + +
    {@link android.bluetooth.BluetoothServerSocket}
    +
    Represents an open server socket that listens for incoming requests +(similar to a TCP {@link java.net.ServerSocket}). In order to connect two +Android devices, one device must open a server socket with this class. When a +remote Bluetooth device makes a connection request to the this device, the +{@link android.bluetooth.BluetoothServerSocket} will return a connected {@link +android.bluetooth.BluetoothSocket} when the +connection is accepted.
    + +
    {@link android.bluetooth.BluetoothClass}
    +
    Describes the general characteristics and capabilities of a Bluetooth +device. This is a read-only set of properties that define the device's major and +minor device classes and its services. However, this does not reliably describe +all Bluetooth profiles and services supported by the device, but is useful as a +hint to the device type.
    + +
    {@link android.bluetooth.BluetoothProfile}
    An interface that +represents a Bluetooth profile. A Bluetooth profile is a wireless +interface specification for Bluetooth-based communication between devices. An +example is the Hands-Free profile. For more discussion of profiles, see Working with Profiles
    + +
    {@link android.bluetooth.BluetoothHeadset}
    Provides support for +Bluetooth headsets to be used with mobile phones. This includes both Bluetooth +Headset and Hands-Free (v1.5) profiles.
    + +
    {@link android.bluetooth.BluetoothA2dp}
    Defines how high quality +audio can be streamed from one device to another over a Bluetooth connection. +"A2DP" stands for Advanced Audio Distribution Profile.
    + +
    {@link android.bluetooth.BluetoothHealth}
    +
    Represents a Health Device Profile proxy that controls the Bluetooth service.
    + +
    {@link android.bluetooth.BluetoothHealthCallback}
    + +
    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.
    + +
    {@link android.bluetooth.BluetoothHealthAppConfiguration}
    + +
    Represents an application configuration that the Bluetooth Health third-party +application registers to communicate with a remote Bluetooth health +device.
    + +
    {@link android.bluetooth.BluetoothProfile.ServiceListener}
    + +
    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).
    + +
    + + + + +

    Bluetooth Permissions

    + +

    In order to use Bluetooth features in your application, you need to declare +at least one of two Bluetooth permissions: {@link +android.Manifest.permission#BLUETOOTH} and {@link +android.Manifest.permission#BLUETOOTH_ADMIN}.

    + +

    You must request the {@link android.Manifest.permission#BLUETOOTH} permission +in order to perform any Bluetooth communication, such as requesting a +connection, accepting a connection, and transferring data.

    + +

    You must request the {@link android.Manifest.permission#BLUETOOTH_ADMIN} +permission in order to initiate device discovery or manipulate Bluetooth +settings. Most applications need this permission solely for the +ability to discover local Bluetooth devices. The other abilities granted by this +permission should not be used, unless the application is a "power manager" that +will modify Bluetooth settings upon user request. Note: If you +use {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission, then must +also have the {@link android.Manifest.permission#BLUETOOTH} permission.

    + +

    Declare the Bluetooth permission(s) in your application manifest file. For +example:

    + +
     
    +<manifest ... >
    +  <uses-permission android:name="android.permission.BLUETOOTH" />
    +  ...
    +</manifest>
    +
    + +

    See the <uses-permission> +reference for more information about declaring application permissions.

    + + +

    Setting Up Bluetooth

    + +
    + +Figure 1: The enabling Bluetooth dialog. +
    + +

    Before your application can communicate over Bluetooth, you need to verify +that Bluetooth is supported on the device, and if so, ensure that it is enabled.

    + +

    If Bluetooth is not supported, then you should gracefully disable any +Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the +user enable Bluetooth without leaving your application. This setup is +accomplished in two steps, using the {@link android.bluetooth.BluetoothAdapter}.

    + + +
      +
    1. Get the {@link android.bluetooth.BluetoothAdapter} +

      The {@link android.bluetooth.BluetoothAdapter} is required for any and all Bluetooth +activity. To get the {@link android.bluetooth.BluetoothAdapter}, call the static {@link +android.bluetooth.BluetoothAdapter#getDefaultAdapter()} method. This returns a +{@link android.bluetooth.BluetoothAdapter} that represents the device's own +Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the +entire system, and your application can interact with it using this object. If +{@link android.bluetooth.BluetoothAdapter#getDefaultAdapter()} returns null, +then the device does not support Bluetooth and your story ends here. For example:

      +
       
      +BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      +if (mBluetoothAdapter == null) {
      +    // Device does not support Bluetooth
      +}
      +
      +
    2. + +
    3. Enable Bluetooth +

      Next, you need to ensure that Bluetooth is enabled. Call {@link +android.bluetooth.BluetoothAdapter#isEnabled()} to check whether Bluetooth is +currently enable. If this method returns false, then Bluetooth is disabled. To +request that Bluetooth be enabled, call {@link +android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} +with the {@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} action Intent. +This will issue a request to enable Bluetooth through the system settings (without +stopping your application). For example:

      +
       
      +if (!mBluetoothAdapter.isEnabled()) {
      +    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      +    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      +}
      +
      + +

      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).

      + +

      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 +requestCode parameter.

      + +

      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 is {@link +android.app.Activity#RESULT_CANCELED}.

      +
    4. +
    + +

    Optionally, your application can also listen for the +{@link android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED} broadcast Intent, which +the system will broadcast whenever the Bluetooth state has changed. This broadcast contains +the extra fields {@link android.bluetooth.BluetoothAdapter#EXTRA_STATE} and {@link +android.bluetooth.BluetoothAdapter#EXTRA_PREVIOUS_STATE}, containing the new and old +Bluetooth states, respectively. Possible values for these extra fields are +{@link android.bluetooth.BluetoothAdapter#STATE_TURNING_ON}, {@link +android.bluetooth.BluetoothAdapter#STATE_ON}, {@link +android.bluetooth.BluetoothAdapter#STATE_TURNING_OFF}, and {@link +android.bluetooth.BluetoothAdapter#STATE_OFF}. Listening for this +broadcast can be useful to detect changes made to the Bluetooth state while your +app is running.

    + +

    Tip: Enabling discoverability will automatically +enable Bluetooth. If you plan to consistently enable device discoverability before +performing Bluetooth activity, you can skip +step 2 above. Read about enabling discoverability, +below.

    + + +

    Finding Devices

    + +

    Using the {@link android.bluetooth.BluetoothAdapter}, you can find remote Bluetooth +devices either through device discovery or by querying the list of paired (bonded) +devices.

    + +

    Device discovery is a scanning procedure that searches the local area for +Bluetooth enabled devices and then requesting some information about each one +(this is sometimes referred to as "discovering," "inquiring" or "scanning"). +However, a Bluetooth device within the local area will respond to a discovery +request only if it is currently enabled to be discoverable. If a device is +discoverable, it will respond to the discovery request by sharing some +information, such as the device name, class, and its unique MAC address. Using +this information, the device performing discovery can then choose to initiate a +connection to the discovered device.

    + +

    Once a connection is made with a remote device for the first time, a pairing +request is automatically presented to the user. When a device is +paired, the basic information about that device (such as the device name, class, +and MAC address) is saved and can be read using the Bluetooth APIs. Using the +known MAC address for a remote device, a connection can be initiated with it at +any time without performing discovery (assuming the device is within range).

    + +

    Remember there is a difference between being paired and being connected. To +be paired means that two devices are aware of each other's existence, have a +shared link-key that can be used for authentication, and are capable of +establishing an encrypted connection with each other. To be connected means that +the devices currently share an RFCOMM channel and are able to transmit data with +each other. The current Android Bluetooth API's require devices to be paired +before an RFCOMM connection can be established. (Pairing is automatically performed +when you initiate an encrypted connection with the Bluetooth APIs.)

    + +

    The following sections describe how to find devices that have been paired, or +discover new devices using device discovery.

    + +

    Note: Android-powered devices are not +discoverable by default. A user can make +the device discoverable for a limited time through the system settings, or an +application can request that the user enable discoverability without leaving the +application. How to enable discoverability +is discussed below.

    + + +

    Querying paired devices

    + +

    Before performing device discovery, its worth querying the set +of paired devices to see if the desired device is already known. To do so, +call {@link android.bluetooth.BluetoothAdapter#getBondedDevices()}. This +will return a Set of {@link android.bluetooth.BluetoothDevice}s representing +paired devices. For example, you can query all paired devices and then +show the name of each device to the user, using an ArrayAdapter:

    +
     
    +Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    +// If there are paired devices
    +if (pairedDevices.size() > 0) {
    +    // Loop through paired devices
    +    for (BluetoothDevice device : pairedDevices) {
    +        // Add the name and address to an array adapter to show in a ListView
    +        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    +    }
    +}
    +
    + +

    All that's needed from the {@link android.bluetooth.BluetoothDevice} object +in order to initiate a connection is the MAC address. In this example, it's saved +as a part of an ArrayAdapter that's shown to the user. The MAC address can later +be extracted in order to initiate the connection. You can learn more about creating +a connection in the section about Connecting Devices.

    + + +

    Discovering devices

    + +

    To start discovering devices, simply call {@link +android.bluetooth.BluetoothAdapter#startDiscovery()}. The +process is asynchronous and the method will immediately return with a boolean +indicating whether discovery has successfully started. The discovery process +usually involves an inquiry scan of about 12 seconds, followed by a page scan of +each found device to retrieve its Bluetooth name.

    + +

    Your application must register a BroadcastReceiver for the +{@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent in +order to receive information about each +device discovered. For each device, the system will broadcast the +{@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent. This +Intent carries the extra fields +{@link android.bluetooth.BluetoothDevice#EXTRA_DEVICE} and +{@link android.bluetooth.BluetoothDevice#EXTRA_CLASS}, containing a +{@link android.bluetooth.BluetoothDevice} and a {@link +android.bluetooth.BluetoothClass}, respectively. For example, here's how you can +register to handle the broadcast when devices are discovered:

    +
     
    +// Create a BroadcastReceiver for ACTION_FOUND
    +private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    +    public void onReceive(Context context, Intent intent) {
    +        String action = intent.getAction();
    +        // When discovery finds a device
    +        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    +            // Get the BluetoothDevice object from the Intent
    +            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    +            // Add the name and address to an array adapter to show in a ListView
    +            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    +        }
    +    }
    +};
    +// Register the BroadcastReceiver
    +IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    +registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
    +
    + +

    All that's needed from the {@link android.bluetooth.BluetoothDevice} object +in order to initiate a +connection is the MAC address. In this example, it's saved as a part of an +ArrayAdapter that's shown to the user. The MAC address can later be extracted in +order to initiate the connection. You can learn more about creating a connection +in the section about Connecting Devices.

    + +

    Caution: Performing device discovery is +a heavy procedure for the Bluetooth +adapter and will consume a lot of its resources. Once you have found a device to +connect, be certain that you always stop discovery with +{@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} before +attempting a connection. Also, if you +already hold a connection with a device, then performing discovery can +significantly reduce the bandwidth available for the connection, so you should +not perform discovery while connected.

    + +

    Enabling discoverability

    + +

    If you would like to make the local device discoverable to other devices, +call {@link android.app.Activity#startActivityForResult(Intent,int)} with the +{@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE} action +Intent. This will issue a request to enable discoverable mode through the system +settings (without stopping your application). By default, the device will become +discoverable for 120 seconds. You can define a different duration by adding the +{@link android.bluetooth.BluetoothAdapter#EXTRA_DISCOVERABLE_DURATION} Intent +extra. The maximum duration an app can set is 3600 seconds, and a value of 0 +means the device is always discoverable. Any value below 0 or above 3600 is +automatically set to 120 secs). For example, this snippet sets the duration to +300:

    + +
    Intent discoverableIntent = new
    +Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    +discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    +startActivity(discoverableIntent);
    +
    + +
    + +Figure 2: The enabling discoverability dialog. +
    + +

    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 +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 {@link android.app.Activity#RESULT_CANCELED}.

    + +

    Note: If Bluetooth has not been enabled on the device, +then enabling device discoverability will automatically enable Bluetooth.

    + +

    The device will silently remain in discoverable mode for the allotted time. +If you would like to be notified when the discoverable mode has changed, you can +register a BroadcastReceiver for the {@link +android.bluetooth.BluetoothAdapter#ACTION_SCAN_MODE_CHANGED} +Intent. This will contain the extra fields {@link +android.bluetooth.BluetoothAdapter#EXTRA_SCAN_MODE} and +{@link android.bluetooth.BluetoothAdapter#EXTRA_PREVIOUS_SCAN_MODE}, which tell you the +new and old scan mode, respectively. Possible values for each are +{@link android.bluetooth.BluetoothAdapter#SCAN_MODE_CONNECTABLE_DISCOVERABLE}, +{@link android.bluetooth.BluetoothAdapter#SCAN_MODE_CONNECTABLE}, or {@link +android.bluetooth.BluetoothAdapter#SCAN_MODE_NONE}, +which indicate that the device is either in discoverable mode, not in +discoverable mode but still able to receive connections, or not in discoverable +mode and unable to receive connections, respectively.

    + +

    You do not need to enable device discoverability if you will be initiating +the connection to a remote device. Enabling discoverability is only necessary when +you want your application to host a server socket that will accept incoming +connections, because the remote devices must be able to discover the device +before it can initiate the connection.

    + + + +

    Connecting Devices

    + +

    In order to create a connection between your application on two devices, you +must implement both the server-side and client-side mechanisms, because one +device must open a server socket and the other one must initiate the connection +(using the server device's MAC address to initiate a connection). The server and +client are considered connected to each other when they each have a connected +{@link android.bluetooth.BluetoothSocket} on the same RFCOMM channel. At this +point, each device can obtain input and output streams and data transfer can +begin, which is discussed in the section about Managing a Connection. This section describes how +to initiate the connection between two devices.

    + +

    The server device and the client device each obtain the required {@link +android.bluetooth.BluetoothSocket} in different ways. The server will receive it +when an incoming connection is accepted. The client will receive it when it +opens an RFCOMM channel to the server.

    + +
    + +Figure 3: The Bluetooth pairing dialog. +
    + +

    One implementation technique is to automatically prepare each device as a +server, so that each one has a server socket open and listening for connections. +Then either device can initiate a connection with the other and become the +client. Alternatively, one device can explicitly "host" the connection and open +a server socket on demand and the other device can simply initiate the +connection.

    + +

    Note: If the two devices have not been previously paired, +then the Android framework will automatically show a pairing request notification or +dialog to the user during the connection procedure, as shown in Figure 3. So +when attempting to connect devices, +your application does not need to be concerned about whether or not the devices are +paired. Your RFCOMM connection attempt will block until the user has successfully paired, +or will fail if the user rejects pairing, or if pairing fails or times out.

    + + +

    Connecting as a server

    + +

    When you want to connect two devices, one must act as a server by holding an +open {@link android.bluetooth.BluetoothServerSocket}. The purpose of the server +socket is to listen for incoming connection requests and when one is accepted, +provide a connected {@link android.bluetooth.BluetoothSocket}. When the {@link +android.bluetooth.BluetoothSocket} is acquired from the {@link +android.bluetooth.BluetoothServerSocket}, +the {@link android.bluetooth.BluetoothServerSocket} can (and should) be +discarded, unless you want to accept more connections.

    + + + +

    Here's the basic procedure to set up a server socket and accept a +connection:

    + +
      +
    1. Get a {@link android.bluetooth.BluetoothServerSocket} by calling the +{@link +android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, +UUID)}. +

      The string is an identifiable name of your service, which the system will +automatically write to a new Service Discovery Protocol (SDP) database entry on +the device (the name is arbitrary and can simply be your application name). The +UUID is also included in the SDP entry and will be the basis for the connection +agreement with the client device. That is, when the client attempts to connect +with this device, it will carry a UUID that uniquely identifies the service with +which it wants to connect. These UUIDs must match in order for the connection to +be accepted (in the next step).

      +
    2. + +
    3. Start listening for connection requests by calling +{@link android.bluetooth.BluetoothServerSocket#accept()}. +

      This is a blocking call. It will return when either a connection has been +accepted or an exception has occurred. A connection is accepted only when a +remote device has sent a connection request with a UUID matching the one +registered with this listening server socket. When successful, {@link +android.bluetooth.BluetoothServerSocket#accept()} will +return a connected {@link android.bluetooth.BluetoothSocket}.

      +
    4. + +
    5. Unless you want to accept additional connections, call +{@link android.bluetooth.BluetoothServerSocket#close()}. +

      This releases the server socket and all its resources, but does not close the +connected {@link android.bluetooth.BluetoothSocket} that's been returned by {@link +android.bluetooth.BluetoothServerSocket#accept()}. Unlike TCP/IP, RFCOMM only allows one +connected client per channel at a time, so in most cases it makes sense to call {@link +android.bluetooth.BluetoothServerSocket#close()} on the {@link +android.bluetooth.BluetoothServerSocket} immediately after accepting a connected +socket.

      +
    6. +
    + +

    The {@link android.bluetooth.BluetoothServerSocket#accept()} call should not +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 +thread managed by your application. To abort a blocked call such as {@link +android.bluetooth.BluetoothServerSocket#accept()}, call {@link +android.bluetooth.BluetoothServerSocket#close()} on the {@link +android.bluetooth.BluetoothServerSocket} (or {@link +android.bluetooth.BluetoothSocket}) from another thread and the blocked call will +immediately return. Note that all methods on a {@link +android.bluetooth.BluetoothServerSocket} or {@link android.bluetooth.BluetoothSocket} +are thread-safe.

    + +

    Example

    + +

    Here's a simplified thread for the server component that accepts incoming +connections:

    +
     
    +private class AcceptThread extends Thread {
    +    private final BluetoothServerSocket mmServerSocket;
    + 
    +    public AcceptThread() {
    +        // Use a temporary object that is later assigned to mmServerSocket,
    +        // because mmServerSocket is final
    +        BluetoothServerSocket tmp = null;
    +        try {
    +            // MY_UUID is the app's UUID string, also used by the client code
    +            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
    +        } catch (IOException e) { }
    +        mmServerSocket = tmp;
    +    }
    + 
    +    public void run() {
    +        BluetoothSocket socket = null;
    +        // Keep listening until exception occurs or a socket is returned
    +        while (true) {
    +            try {
    +                socket = mmServerSocket.accept();
    +            } catch (IOException e) {
    +                break;
    +            }
    +            // If a connection was accepted
    +            if (socket != null) {
    +                // Do work to manage the connection (in a separate thread)
    +                manageConnectedSocket(socket);
    +                mmServerSocket.close();
    +                break;
    +            }
    +        }
    +    }
    + 
    +    /** Will cancel the listening socket, and cause the thread to finish */
    +    public void cancel() {
    +        try {
    +            mmServerSocket.close();
    +        } catch (IOException e) { }
    +    }
    +}
    +
    + +

    In this example, only one incoming connection is desired, so as soon as a +connection is accepted and the {@link android.bluetooth.BluetoothSocket} is +acquired, the application +sends the acquired {@link android.bluetooth.BluetoothSocket} to a separate +thread, closes the +{@link android.bluetooth.BluetoothServerSocket} and breaks the loop.

    + +

    Note that when {@link android.bluetooth.BluetoothServerSocket#accept()} +returns the {@link android.bluetooth.BluetoothSocket}, the socket is already +connected, so you should not call {@link +android.bluetooth.BluetoothSocket#connect()} (as you do from the +client-side).

    + +

    manageConnectedSocket() is a fictional method in the application +that will +initiate the thread for transferring data, which is discussed in the section +about Managing a Connection.

    + +

    You should usually close your {@link android.bluetooth.BluetoothServerSocket} +as soon as you are done listening for incoming connections. In this example, {@link +android.bluetooth.BluetoothServerSocket#close()} is called as soon +as the {@link android.bluetooth.BluetoothSocket} is acquired. You may also want +to provide a public method in your thread that can close the private {@link +android.bluetooth.BluetoothSocket} in the event that you need to stop listening on the +server socket.

    + + +

    Connecting as a client

    + +

    In order to initiate a connection with a remote device (a device holding an +open +server socket), you must first obtain a {@link +android.bluetooth.BluetoothDevice} object that represents the remote device. +(Getting a {@link android.bluetooth.BluetoothDevice} is covered in the above +section about Finding Devices.) You must then use the +{@link android.bluetooth.BluetoothDevice} to acquire a {@link +android.bluetooth.BluetoothSocket} and initiate the connection.

    + +

    Here's the basic procedure:

    + +
      +
    1. Using the {@link android.bluetooth.BluetoothDevice}, get a {@link +android.bluetooth.BluetoothSocket} by calling {@link +android.bluetooth.BluetoothDevice#createRfcommSocketToServiceRecord(UUID)}. +

      This initializes a {@link android.bluetooth.BluetoothSocket} that will +connect to the {@link android.bluetooth.BluetoothDevice}. The UUID passed here +must match the UUID used by the server device when it opened its +{@link android.bluetooth.BluetoothServerSocket} (with {@link +android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, +UUID)}). Using the same UUID is simply a matter of hard-coding the UUID string +into your application and then referencing it from both the server and client +code.

      +
    2. + +
    3. Initiate the connection by calling {@link +android.bluetooth.BluetoothSocket#connect()}. +

      Upon this call, the system will perform an SDP lookup on the remote device in +order to match the UUID. If the lookup is successful and the remote device +accepts the connection, it will share the RFCOMM channel to use during the +connection and {@link +android.bluetooth.BluetoothSocket#connect()} will return. This method is a +blocking call. If, for +any reason, the connection fails or the {@link +android.bluetooth.BluetoothSocket#connect()} method times out (after about +12 seconds), then it will throw an exception.

      +

      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 +thread.

      +

      Note: You should always ensure that the device is not performing +device discovery when you call {@link +android.bluetooth.BluetoothSocket#connect()}. If discovery is in progress, then +the +connection attempt will be significantly slowed and is more likely to fail.

      +
    4. +
    + +

    Example

    + +

    Here is a basic example of a thread that initiates a Bluetooth +connection:

    +
     
    +private class ConnectThread extends Thread {
    +    private final BluetoothSocket mmSocket;
    +    private final BluetoothDevice mmDevice;
    + 
    +    public ConnectThread(BluetoothDevice device) {
    +        // Use a temporary object that is later assigned to mmSocket,
    +        // because mmSocket is final
    +        BluetoothSocket tmp = null;
    +        mmDevice = device;
    + 
    +        // Get a BluetoothSocket to connect with the given BluetoothDevice
    +        try {
    +            // MY_UUID is the app's UUID string, also used by the server code
    +            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    +        } catch (IOException e) { }
    +        mmSocket = tmp;
    +    }
    + 
    +    public void run() {
    +        // Cancel discovery because it will slow down the connection
    +        mBluetoothAdapter.cancelDiscovery();
    + 
    +        try {
    +            // Connect the device through the socket. This will block
    +            // until it succeeds or throws an exception
    +            mmSocket.connect();
    +        } catch (IOException connectException) {
    +            // Unable to connect; close the socket and get out
    +            try {
    +                mmSocket.close();
    +            } catch (IOException closeException) { }
    +            return;
    +        }
    + 
    +        // Do work to manage the connection (in a separate thread)
    +        manageConnectedSocket(mmSocket);
    +    }
    + 
    +    /** Will cancel an in-progress connection, and close the socket */
    +    public void cancel() {
    +        try {
    +            mmSocket.close();
    +        } catch (IOException e) { }
    +    }
    +}
    +
    + +

    Notice that {@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} is called +before the connection is made. You should always do this before connecting and it is safe +to call without actually checking whether it is running or not (but if you do want to +check, call {@link android.bluetooth.BluetoothAdapter#isDiscovering()}).

    + +

    manageConnectedSocket() is a fictional method in the application +that will initiate the thread for transferring data, which is discussed in the section +about Managing a Connection.

    + +

    When you're done with your {@link android.bluetooth.BluetoothSocket}, always +call {@link android.bluetooth.BluetoothSocket#close()} to clean up. +Doing so will immediately close the connected socket and clean up all internal +resources.

    + + +

    Managing a Connection

    + +

    When you have successfully connected two (or more) devices, each one will +have a connected {@link android.bluetooth.BluetoothSocket}. This is where the fun +begins because you can share data between devices. Using the {@link +android.bluetooth.BluetoothSocket}, the general procedure to transfer arbitrary data is +simple:

    +
      +
    1. Get the {@link java.io.InputStream} and {@link java.io.OutputStream} that +handle transmissions through the socket, via {@link +android.bluetooth.BluetoothSocket#getInputStream()} and +{@link android.bluetooth.BluetoothSocket#getOutputStream}, respectively.
    2. + +
    3. Read and write data to the streams with {@link +java.io.InputStream#read(byte[])} and {@link java.io.OutputStream#write(byte[])}.
    4. +
    + +

    That's it.

    + +

    There are, of course, implementation details to consider. First and foremost, +you should use a dedicated thread for all stream reading and writing. This is +important because both {@link java.io.InputStream#read(byte[])} and {@link +java.io.OutputStream#write(byte[])} methods are blocking calls. {@link +java.io.InputStream#read(byte[])} will block until there is something to read +from the stream. {@link java.io.OutputStream#write(byte[])} does not usually +block, but can block for flow control if the remote device is not calling {@link +java.io.InputStream#read(byte[])} quickly enough and the intermediate buffers are full. +So, your main loop in the thread should be dedicated to reading from the {@link +java.io.InputStream}. A separate public method in the thread can be used to initiate +writes to the {@link java.io.OutputStream}.

    + +

    Example

    + +

    Here's an example of how this might look:

    +
     
    +private class ConnectedThread extends Thread {
    +    private final BluetoothSocket mmSocket;
    +    private final InputStream mmInStream;
    +    private final OutputStream mmOutStream;
    + 
    +    public ConnectedThread(BluetoothSocket socket) {
    +        mmSocket = socket;
    +        InputStream tmpIn = null;
    +        OutputStream tmpOut = null;
    + 
    +        // Get the input and output streams, using temp objects because
    +        // member streams are final
    +        try {
    +            tmpIn = socket.getInputStream();
    +            tmpOut = socket.getOutputStream();
    +        } catch (IOException e) { }
    + 
    +        mmInStream = tmpIn;
    +        mmOutStream = tmpOut;
    +    }
    + 
    +    public void run() {
    +        byte[] buffer = new byte[1024];  // buffer store for the stream
    +        int bytes; // bytes returned from read()
    + 
    +        // Keep listening to the InputStream until an exception occurs
    +        while (true) {
    +            try {
    +                // Read from the InputStream
    +                bytes = mmInStream.read(buffer);
    +                // Send the obtained bytes to the UI activity
    +                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
    +                        .sendToTarget();
    +            } catch (IOException e) {
    +                break;
    +            }
    +        }
    +    }
    + 
    +    /* 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 */
    +    public void cancel() {
    +        try {
    +            mmSocket.close();
    +        } catch (IOException e) { }
    +    }
    +}
    +
    + +

    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 +Handler from the parent class. Then it goes back and waits for more bytes from +the stream.

    + +

    Sending outgoing data is as simple as calling the thread's +write() 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.

    + +

    The thread's cancel() method is important so that the connection +can be +terminated at any time by closing the {@link android.bluetooth.BluetoothSocket}. +This should always be called when you're done using the Bluetooth +connection.

    + +
    +

    For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

    +
    + +

    Working with Profiles

    + +

    Starting in Android 3.0, the Bluetooth API includes support for working with +Bluetooth profiles. A Bluetooth profile is a wireless interface +specification for Bluetooth-based communication between devices. An example +is the Hands-Free profile. For a mobile phone to connect to a wireless headset, +both devices must support the Hands-Free profile.

    + +

    You can implement the interface {@link android.bluetooth.BluetoothProfile} to write +your own classes to support a particular Bluetooth profile. The Android +Bluetooth API provides implementations for the following Bluetooth +profiles:

    +
      + +
    • Headset. The Headset profile provides support for +Bluetooth headsets to be used with mobile phones. Android provides the {@link +android.bluetooth.BluetoothHeadset} class, which is a proxy for controlling the +Bluetooth Headset Service via interprocess communication (IPC). 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 Vendor-specific AT commands
    • + +
    • A2DP. The Advanced Audio Distribution Profile (A2DP) +profile defines how high quality audio can be streamed from one device to +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.
    • + +
    • Health Device. 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 Bluetooth Assigned Numbers at www.bluetooth.org. 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 Health Device Profile.
    • + +
    + +

    Here are the basic steps for working with a profile:

    +
      + +
    1. Get the default adapter, as described in + Setting Up + Bluetooth.
    2. + +
    3. Use {@link +android.bluetooth.BluetoothAdapter#getProfileProxy(android.content.Context, +android.bluetooth.BluetoothProfile.ServiceListener, int) getProfileProxy()} to +establish a connection to the profile proxy object associated with the profile. +In the example below, the profile proxy object is an instance of {@link +android.bluetooth.BluetoothHeadset}.
    4. + +
    5. Set up a {@link android.bluetooth.BluetoothProfile.ServiceListener}. This +listener notifies {@link android.bluetooth.BluetoothProfile} IPC clients when +they have been connected to or disconnected from the service.
    6. + +
    7. In {@link +android.bluetooth.BluetoothProfile.ServiceListener#onServiceConnected(int, +android.bluetooth.BluetoothProfile) onServiceConnected()}, get a handle +to the profile proxy object.
    8. + +
    9. Once you have the profile proxy object, you can use it to monitor the +state of the connection and perform other operations that are relevant to that +profile.
    10. +
    + +

    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:

    + +
    BluetoothHeadset mBluetoothHeadset;
    + 
    +// Get the default adapter
    +BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    + 
    +// Establish connection to the proxy.
    +mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
    + 
    +private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
    +    public void onServiceConnected(int profile, BluetoothProfile proxy) {
    +        if (profile == BluetoothProfile.HEADSET) {
    +            mBluetoothHeadset = (BluetoothHeadset) proxy;
    +        }
    +    }
    +    public void onServiceDisconnected(int profile) {
    +        if (profile == BluetoothProfile.HEADSET) {
    +            mBluetoothHeadset = null;
    +        }
    +    }
    +};
    + 
    +// ... call functions on mBluetoothHeadset
    + 
    +// Close proxy connection after use.
    +mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);
    +
    + + + +

    Vendor-specific AT commands

    + +

    Starting in Android 3.0, applications can register to receive system +broadcasts of pre-defined vendor-specific AT commands sent by headsets (such as +a Plantronics +XEVENT command). For example, an application could receive +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.

    + +

    Health Device Profile

    + +

    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 The Basics.

    + +

    In using the Bluetooth Health API, it's helpful to understand these key HDP concepts:

    + + + + + + + + + + + + + + + + + + + + + + + + +
    ConceptDescription
    SourceA role defined in HDP. A source 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.
    SinkA role defined in HDP. In HDP, a sink 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.
    RegistrationRefers to registering a sink for a particular health device.
    ConnectionRefers to opening a channel between a health device and a smart device +such as an Android phone or tablet.
    + +

    Creating an HDP Application

    + +

    Here are the basic steps involved in creating an Android HDP application:

    +
      + +
    1. Get a reference to the {@link android.bluetooth.BluetoothHealth} proxy +object.

      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.

    2. + +
    3. Create a {@link android.bluetooth.BluetoothHealthCallback} and register an +application configuration +({@link android.bluetooth.BluetoothHealthAppConfiguration}) +that acts as a health +sink.
    4. + +
    5. Establish a connection to a health device. Some devices will initiate the +connection. It is unnecessary to carry out this step for those devices.
    6. + +
    7. When connected successfully to a health device, read/write to the health +device using the file descriptor.

      The received data needs to be interpreted +using a health manager which implements the IEEE 11073-xxxxx +specifications.

    8. + +
    9. When done, close the health channel and unregister the application. The +channel also closes when there is extended inactivity.
    10. +
    + +

    For a complete code sample that illustrates these steps, see Bluetooth HDP (Health +Device Profile).

    diff --git a/docs/html/guide/topics/connectivity/index.jd b/docs/html/guide/topics/connectivity/index.jd new file mode 100644 index 000000000000..322518e67929 --- /dev/null +++ b/docs/html/guide/topics/connectivity/index.jd @@ -0,0 +1,42 @@ +page.title=Connectivity +page.landing=true +page.landing.intro=Android provides rich APIs to let your app connect and interact with other devices over Bluetooth, NFC, Wi-Fi Direct, USB, and SIP, in addition to standard network connections. +page.landing.image=images/develop/connectivity.png + +@jd:body + + \ No newline at end of file diff --git a/docs/html/guide/topics/connectivity/nfc/advanced-nfc.jd b/docs/html/guide/topics/connectivity/nfc/advanced-nfc.jd new file mode 100644 index 000000000000..9d6cda51ab34 --- /dev/null +++ b/docs/html/guide/topics/connectivity/nfc/advanced-nfc.jd @@ -0,0 +1,300 @@ +page.title=Advanced NFC +@jd:body + + + +

    This document describes advanced NFC topics, such as working with various tag technologies, +writing to NFC tags, and foreground dispatching, which allows an application in the foreground to +handle intents even when other applications filter for the same ones.

    + +

    Working with Supported Tag Technologies

    +

    When working with NFC tags and Android-powered devices, the main format you use to read +and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support +in parsing the message and delivering it in an {@link android.nfc.NdefMessage} when +possible. There are cases, however, when you scan a tag that does not contain +NDEF data or when the NDEF data could not be mapped to a MIME type or URI. +In these cases, you need to open communication directly with the tag and read and write to it with +your own protocol (in raw bytes). Android provides generic support for these use cases with the +{@link android.nfc.tech} package, which is described in Table 1. You can +use the {@link android.nfc.Tag#getTechList getTechList()} method to determine the technologies +supported by the tag and create the corresponding {@link android.nfc.tech.TagTechnology} +object with one of classes provided by {@link android.nfc.tech}

    + +

    +Table 1. Supported tag technologies

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ClassDescription
    {@link android.nfc.tech.TagTechnology}The interface that all tag technology classes must implement.
    {@link android.nfc.tech.NfcA}Provides access to NFC-A (ISO 14443-3A) properties and I/O operations.
    {@link android.nfc.tech.NfcB}Provides access to NFC-B (ISO 14443-3B) properties and I/O operations.
    {@link android.nfc.tech.NfcF}Provides access to NFC-F (JIS 6319-4) properties and I/O operations.
    {@link android.nfc.tech.NfcV}Provides access to NFC-V (ISO 15693) properties and I/O operations.
    {@link android.nfc.tech.IsoDep}Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations.
    {@link android.nfc.tech.Ndef}Provides access to NDEF data and operations on NFC tags that have been formatted as + NDEF.
    {@link android.nfc.tech.NdefFormatable}Provides a format operations for tags that may be NDEF formattable.
    +

    The following tag technlogies are not required to be supported by Android-powered devices.

    +

    +Table 2. Optional supported tag technologies

    + + + + + + + + + + + + + + + + + +
    ClassDescription
    {@link android.nfc.tech.MifareClassic}Provides access to MIFARE Classic properties and I/O operations, if this Android device + supports MIFARE.
    {@link android.nfc.tech.MifareUltralight}Provides access to MIFARE Ultralight properties and I/O operations, if this Android + device supports MIFARE.
    + +

    Working with tag technologies and the ACTION_TECH_DISCOVERED intent

    +

    When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, +the tag dispatch system tries to start an activity with the {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} +intent. The {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} is also used when a tag +with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag +directly if the tag dispatch system could not parse it for you. The basic steps when working with +tag technologies are as follows:

    + +
      +
    1. Filter for an {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent specifying the +tag technologies that you want to handle. See Filtering for NFC +intents for more information. In general, the tag dispatch system tries to start a {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent when an NDEF message +cannot be mapped to a MIME type or URI, or if the tag scanned did not contain NDEF data. For +more information on how this is determined, see The Tag Dispatch System.
    2. +
    3. When your application receives the intent, obtain the {@link android.nfc.Tag} object from +the intent: +
      Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    4. +
    5. Obtain an instance of a {@link android.nfc.tech.TagTechnology}, by calling one of the +get factory methods of the classes in the {@link android.nfc.tech} package. You can +enumerate the supported technologies of the tag by calling {@link android.nfc.Tag#getTechList +getTechList()} before calling a get factory method. For example, to obtain an instance +of {@link android.nfc.tech.MifareUltralight} from a {@link android.nfc.Tag}, do the following: + +
      +MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
      +
      +
    6. +
    + + + +

    Reading and writing to tags

    + +

    Reading and writing to an NFC tag involves obtaining the tag from the intent and +opening communication with the tag. You must define your own protocol stack to read and write data +to the tag. Keep in mind, however, that you can still read and write NDEF data when working +directly with a tag. It is up to you how you want to structure things. The +following example shows how to work with a MIFARE Ultralight tag.

    + +
    +package com.example.android.nfc;
    +
    +import android.nfc.Tag;
    +import android.nfc.tech.MifareUltralight;
    +import android.util.Log;
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +
    +public class MifareUltralightTagTester {
    +
    +    private static final String TAG = MifareUltralightTagTester.class.getSimpleName();
    +
    +    public void writeTag(Tag tag, String tagText) {
    +        MifareUltralight ultralight = MifareUltralight.get(tag);
    +        try {
    +            ultralight.connect();
    +            ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
    +            ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
    +            ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
    +            ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
    +        } catch (IOException e) {
    +            Log.e(TAG, "IOException while closing MifareUltralight...", e);
    +        } finally {
    +            try {
    +                ultralight.close();
    +            } catch (IOException e) {
    +                Log.e(TAG, "IOException while closing MifareUltralight...", e);
    +            }
    +        }
    +    }
    +
    +    public String readTag(Tag tag) {
    +        MifareUltralight mifare = MifareUltralight.get(tag);
    +        try {
    +            mifare.connect();
    +            byte[] payload = mifare.readPages(4);
    +            return new String(payload, Charset.forName("US-ASCII"));
    +        } catch (IOException e) {
    +            Log.e(TAG, "IOException while writing MifareUltralight
    +            message...", e);
    +        } finally {
    +            if (mifare != null) {
    +               try {
    +                   mifare.close();
    +               }
    +               catch (IOException e) {
    +                   Log.e(TAG, "Error closing tag...", e);
    +               }
    +            }
    +        }
    +        return null;
    +    }
    +}
    +
    + + + +

    Using the Foreground Dispatch System

    + +

    The foreground dispatch system allows an activity to intercept an intent and claim +priority over other activities that handle the same intent. Using this system involves + constructing a few data structures for the Android system to be able to send the appropriate + intents to your application. To enable the foreground dispatch system:

    + +
      +
    1. Add the following code in the onCreate() method of your activity: + +
        +
      1. Create a {@link android.app.PendingIntent} object so the Android system can populate it + with the details of the tag when it is scanned. +
        +PendingIntent pendingIntent = PendingIntent.getActivity(
        +    this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        +
        +
      2. + +
      3. Declare intent filters to handle the intents that you want to intercept. The foreground + dispatch system checks the specified intent filters with the intent that is received when + the device scans a tag. If it matches, then your application handles the intent. If it does + not match, the foreground dispatch system falls back to the intent dispatch system. + Specifying a null array of intent filters and technology filters, specifies + that you want to filter for all tags that fallback to the TAG_DISCOVERED + intent. The code snippet below handles all MIME types for NDEF_DISCOVERED. You + should only handle the ones that you need. +
        +IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        +    try {
        +        ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
        +                                       You should specify only the ones that you need. */
        +    }
        +    catch (MalformedMimeTypeException e) {
        +        throw new RuntimeException("fail", e);
        +    }
        +   intentFiltersArray = new IntentFilter[] {ndef, };
        +
        +
      4. + +
      5. Set up an array of tag technologies that your application wants to handle. Call the + Object.class.getName() method to obtain the class of the technology that you + want to support. +
        +techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
        +
        +
      6. +
      +
    2. + +
    3. Override the following activity lifecycle callbacks and add logic to enable and disable the + foreground dispatch when the activity loses ({@link android.app.Activity#onPause onPause()}) + and regains ({@link android.app.Activity#onResume onResume()}) focus. {@link + android.nfc.NfcAdapter#enableForegroundDispatch enableForegroundDispatch()} must be called from +the main thread and only when the activity is in the foreground (calling in {@link +android.app.Activity#onResume onResume()} guarantees this). You also need to implement the {@link + android.app.Activity#onNewIntent onNewIntent} callback to process the data from the scanned NFC + tag.
    4. + +
      +public void onPause() {
      +    super.onPause();
      +    mAdapter.disableForegroundDispatch(this);
      +}
      +
      +public void onResume() {
      +    super.onResume();
      +    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
      +}
      +
      +public void onNewIntent(Intent intent) {
      +    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      +    //do something with tagFromIntent
      +}
      +
      + +
    + +

    See the +ForegroundDispatch sample from API Demos for the complete sample.

    \ No newline at end of file diff --git a/docs/html/guide/topics/connectivity/nfc/index.jd b/docs/html/guide/topics/connectivity/nfc/index.jd new file mode 100644 index 000000000000..88c206f4958a --- /dev/null +++ b/docs/html/guide/topics/connectivity/nfc/index.jd @@ -0,0 +1,33 @@ +page.title=Near Field Communication +@jd:body + +

    Near Field Communication (NFC) is a set of short-range wireless technologies, typically + requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small + payloads of data between an NFC tag and an Android-powered device, or between two Android-powered + devices. + +

    Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with + one-time-programmable areas to make the card read-only. More complex tags offer math operations, + and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags + contain operating environments, allowing complex interactions with code executing on the tag. + The data stored in the tag can also be written in a variety of formats, but many of the Android + framework APIs are based around a NFC Forum standard + called NDEF (NFC Data Exchange Format).

    + +
    +
    NFC Basics
    +
    This document describes how Android handles discovered NFC tags and how it notifies +applications of data that is relevant to the application. It also goes over how to work with the +NDEF data in your applications and gives an overview of the framework APIs that support the basic +NFC feature set of Android.
    + +
    Advanced + NFC
    +
    This document goes over the APIs that enable use of the various tag technologies that + Android supports. When you are not working with NDEF data, or when you are working with NDEF + data that Android cannot fully understand, you have to manually read or write to the tag in raw + bytes using your own protocol stack. In these cases, Android provides support to detect + certain tag technologies and to open communication with the tag using your own protocol + stack.
    +
    +

    \ No newline at end of file diff --git a/docs/html/guide/topics/connectivity/nfc/nfc.jd b/docs/html/guide/topics/connectivity/nfc/nfc.jd new file mode 100644 index 000000000000..51c7bee04f26 --- /dev/null +++ b/docs/html/guide/topics/connectivity/nfc/nfc.jd @@ -0,0 +1,923 @@ +page.title=NFC Basics +@jd:body + + + + +

    This document describes the basic NFC tasks you perform in Android. It explains how to send and +receive NFC data in the form of NDEF messages and describes the Android framework APIs that support +these features. For more advanced topics, including a discussion of working with non-NDEF data, +see Advanced NFC.

    + + +

    There are two major uses cases when working with NDEF data and Android:

    + +
      +
    • Reading NDEF data from an NFC tag
    • +
    • Beaming NDEF messages from one device to another with Android +Beam™
    • +
    + + +

    Reading NDEF data from an NFC tag is handled with the tag dispatch +system, which analyzes discovered NFC tags, appropriately categorizes the data, and starts +an application that is interested in the categorized data. An application that wants to handle the +scanned NFC tag can declare an intent filter and +request to handle the data.

    + +

    The Android Beam™ feature allows a device to push an NDEF message onto +another device by physically tapping the devices together. This interaction provides an easier way +to send data than other wireless technologies like Bluetooth, because with NFC, no manual device +discovery or pairing is required. The connection is automatically started when two devices come +into range. Android Beam is available through a set of NFC APIs, so any application can transmit +information between devices. For example, the Contacts, Browser, and YouTube applications use +Android Beam to share contacts, web pages, and videos with other devices. +

    + + +

    The Tag Dispatch System

    + +

    Android-powered devices are usually looking for NFC tags when the screen +is unlocked, unless NFC is disabled in the device's Settings menu. +When an Android-powered device discovers an NFC tag, the desired behavior +is to have the most appropriate activity handle the intent without asking the user what application +to use. Because devices scan NFC tags at a very short range, it is likely that making users manually +select an activity would force them to move the device away from the tag and break the connection. +You should develop your activity to only handle the NFC tags that your activity cares about to +prevent the Activity Chooser from appearing.

    + +

    To help you with this goal, Android provides a special tag dispatch system that analyzes scanned +NFC tags, parses them, and tries to locate applications that are interested in the scanned data. It +does this by:

    + +
      +
    1. Parsing the NFC tag and figuring out the MIME type or a URI that identifies the data payload + in the tag.
    2. +
    3. Encapsulating the MIME type or URI and the payload into an intent. These first two + steps are described in How NFC tags are mapped to MIME types and URIs.
    4. +
    5. Starts an activity based on the intent. This is described in + How NFC Tags are Dispatched to Applications.
    6. +
    + +

    How NFC tags are mapped to MIME types and URIs

    +

    Before you begin writing your NFC applications, it is important to understand the different +types of NFC tags, how the tag dispatch system parses NFC tags, and the special work that the tag +dispatch system does when it detects an NDEF message. NFC tags come in a +wide array of technologies and can also have data written to them in many different ways. +Android has the most support for the NDEF standard, which is defined by the NFC Forum. +

    + +

    NDEF data is encapsulated inside a message ({@link android.nfc.NdefMessage}) that contains one +or more records ({@link android.nfc.NdefRecord}). Each NDEF record must be well-formed according to +the specification of the type of record that you want to create. Android +also supports other types of tags that do not contain NDEF data, which you can work with by using +the classes in the {@link android.nfc.tech} package. To learn more +about these technologies, see the Advanced +NFC topic. Working with these other types of tags involves +writing your own protocol stack to communicate with the tags, so we recommend using NDEF when +possible for ease of development and maximum support for Android-powered devices. +

    + +

    Note: +To download complete NDEF specifications, go to the NFC Forum Specification Download site and see +Creating common types of NDEF records for examples of how to +construct NDEF records.

    + +

    Now that you have some background in NFC tags, the following sections describe in more detail how +Android handles NDEF formatted tags. When an Android-powered device scans an NFC tag containing NDEF +formatted data, it parses the message and tries to figure out the data's MIME type or identifying +URI. To do this, the system reads the first {@link android.nfc.NdefRecord} inside the {@link +android.nfc.NdefMessage} to determine how to interpret the entire NDEF message (an NDEF message can +have multiple NDEF records). In a well-formed NDEF message, the first {@link android.nfc.NdefRecord} +contains the following fields: +

    +
    3-bit TNF (Type Name Format)
    +
    Indicates how to interpret the variable length type field. Valid values are described in +described in Table 1.
    + +
    Variable length type
    +
    Describes the type of the record. If using {@link android.nfc.NdefRecord#TNF_WELL_KNOWN}, use +this field to specify the Record Type Definition (RTD). Valid RTD values are described in Table 2.
    + +
    Variable length ID
    +
    A unique identifier for the record. This field is not used often, but +if you need to uniquely identify a tag, you can create an ID for it.
    + +
    Variable length payload
    +
    The actual data payload that you want to read or write. An NDEF +message can contain multiple NDEF records, so don't assume the full payload is in the first NDEF +record of the NDEF message.
    + +
    + +

    The tag dispatch system uses the TNF and type fields to try to map a MIME type or URI to the +NDEF message. If successful, it encapsulates that information inside of a {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with the actual payload. However, there +are cases when the tag dispatch system cannot determine the type of data based on the first NDEF +record. This happens when the NDEF data cannot be mapped to a MIME type or URI, or when the +NFC tag does not contain NDEF data to begin with. In such cases, a {@link +android.nfc.Tag} object that has information about the tag's technologies and the payload are +encapsulated inside of a {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent instead.

    + +

    +Table 1. describes how the tag dispatch system maps TNF and type +fields to MIME types or URIs. It also describes which TNFs cannot be mapped to a MIME type or URI. +In these cases, the tag dispatch system falls back to +{@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. + +

    For example, if the tag dispatch system encounters a record of type {@link +android.nfc.NdefRecord#TNF_ABSOLUTE_URI}, it maps the variable length type field of that record +into a URI. The tag dispatch system encapsulates that URI in the data field of an {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with other information about the tag, +such as the payload. On the other hand, if it encounters a record of type {@link +android.nfc.NdefRecord#TNF_UNKNOWN}, it creates an intent that encapsulates the tag's technologies +instead.

    + + +

    + Table 1. Supported TNFs and their mappings

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Type Name Format (TNF)Mapping
    {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI}URI based on the type field.
    {@link android.nfc.NdefRecord#TNF_EMPTY}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE}URI based on the URN in the type field. The URN is encoded into the NDEF type field in + a shortened form: <domain_name>:<service_name>. + Android maps this to a URI in the form: + vnd.android.nfc://ext/<domain_name>:<service_name>.
    {@link android.nfc.NdefRecord#TNF_MIME_MEDIA}MIME type based on the type field.
    {@link android.nfc.NdefRecord#TNF_UNCHANGED}Invalid in the first record, so falls back to + {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#TNF_UNKNOWN}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#TNF_WELL_KNOWN}MIME type or URI depending on the Record Type Definition (RTD), which you set in the +type field. See Table 2. for more information on +available RTDs and their mappings.
    + +

    + Table 2. Supported RTDs for TNF_WELL_KNOWN and their +mappings

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Record Type Definition (RTD)Mapping
    {@link android.nfc.NdefRecord#RTD_ALTERNATIVE_CARRIER}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_HANDOVER_CARRIER}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_HANDOVER_REQUEST}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_HANDOVER_SELECT}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_SMART_POSTER}URI based on parsing the payload.
    {@link android.nfc.NdefRecord#RTD_TEXT}MIME type of text/plain.
    {@link android.nfc.NdefRecord#RTD_URI}URI based on payload.
    + +

    How NFC Tags are Dispatched to Applications

    + +

    When the tag dispatch system is done creating an intent that encapsulates the NFC tag and its +identifying information, it sends the intent to an interested application that +filters for the intent. If more than one application can handle the intent, the Activity Chooser +is presented so the user can select the Activity. The tag dispatch system defines three intents, +which are listed in order of highest to lowest priority:

    + +
      +
    1. + {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}: This intent is used to start an +Activity when a tag that contains an NDEF payload is scanned and is of a recognized type. This is +the highest priority intent, and the tag dispatch system tries to start an Activity with this +intent before any other intent, whenever possible. +
    2. + +
    3. {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}: If no activities register to +handle the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} +intent, the tag dispatch system tries to start an application with this intent. This +intent is also directly started (without starting {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} first) if the tag that is scanned +contains NDEF data that cannot be mapped to a MIME type or URI, or if the tag does not contain NDEF +data but is of a known tag technology. +
    4. + +
    5. {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}: This intent is started + if no activities handle the {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} + intents.
    6. +
    + +

    The basic way the tag dispatch system works is as follows:

    + +
      +
    1. Try to start an Activity with the intent that was created by the tag dispatch system +when parsing the NFC tag (either +{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}).
    2. +
    3. If no activities filter for that intent, try to start an Activity with the next + lowest priority intent (either {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} or {@link +android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}) until an application filters for the + intent or until the tag dispatch system tries all possible intents.
    4. +
    5. If no applications filter for any of the intents, do nothing.
    6. +
    + + + +

    Figure 1. Tag Dispatch System

    + + +

    Whenever possible, work with NDEF messages and the {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent, because it is the most specific out of +the three. This intent allows you to start your application at a more appropriate time than the +other two intents, giving the user a better experience.

    + +

    Requesting NFC Access in the Android Manifest

    + +

    Before you can access a device's NFC hardware and properly handle NFC intents, declare these + items in your AndroidManifest.xml file:

    + +
      +
    • The NFC <uses-permission> element to access the NFC hardware: +
      +<uses-permission android:name="android.permission.NFC" />
      +
      +
    • + +
    • The minimum SDK version that your application can support. API level 9 only supports + limited tag dispatch via {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, and only gives + access to NDEF messages via the {@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES} extra. No + other tag properties or I/O operations are accessible. API level 10 + includes comprehensive reader/writer support as well as foreground NDEF pushing, and API level + 14 provides an easier way to push NDEF messages to other devices with Android Beam and extra + convenience methods to create NDEF records. +
      +<uses-sdk android:minSdkVersion="10"/>
      +
      +
    • + +
    • The uses-feature element so that your application shows up in Google +Play only for devices that have NFC hardware: +
      +<uses-feature android:name="android.hardware.nfc" android:required="true" />
      +
      +

      If your application uses NFC functionality, but that functionality is not crucial to your +application, you can omit the uses-feature element and check for NFC avalailbility at +runtime by checking to see if {@link android.nfc.NfcAdapter#getDefaultAdapter getDefaultAdapter()} +is null.

      +
    • +
    + +

    Filtering for NFC Intents

    + +

    To start your application when an NFC tag that you want to handle is scanned, your application +can filter for one, two, or all three of the NFC intents in the Android manifest. However, you +usually want to filter for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent for the +most control of when your application starts. The {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent is a fallback for {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} when no applications filter for + {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or for when the payload is not +NDEF. Filtering for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is usually too general of a +category to filter on. Many applications will filter for {@link +android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} before {@link +android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, so your application has a low probability of +starting. {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is only available as a last resort +for applications to filter for in the cases where no other applications are installed to handle the +{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}intent.

    + +

    Because NFC tag deployments vary and are many times not under your control, this is not always +possible, which is why you can fallback to the other two intents when necessary. When you have +control over the types of tags and data written, it is recommended that you use NDEF to format your +tags. The following sections describe how to filter for each type of intent.

    + + +

    ACTION_NDEF_DISCOVERED

    +

    +To filter for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intents, declare the +intent filter along with the type of data that you want to filter for. The +following example filters for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} +intents with a MIME type of text/plain: +

    +
    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    +    <category android:name="android.intent.category.DEFAULT"/>
    +    <data android:mimeType="text/plain" />
    +</intent-filter>
    +
    +

    The following example filters for a URI in the form of +http://developer.android.com/index.html. +

    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    +    <category android:name="android.intent.category.DEFAULT"/>
    +   <data android:scheme="http"
    +              android:host="developer.android.com"
    +              android:pathPrefix="/index.html" />
    +</intent-filter>
    +
    + + +

    ACTION_TECH_DISCOVERED

    + +

    If your activity filters for the {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent, +you must create an XML resource file that specifies the technologies that your activity supports +within a tech-list set. Your activity is + considered a match if a tech-list set is a subset of the technologies that are + supported by the tag, which you can obtain by calling {@link android.nfc.Tag#getTechList + getTechList()}.

    + +

    For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your + tech-list set must specify all three, two, or one of the technologies (and nothing + else) in order for your activity to be matched.

    + +

    The following sample defines all of the technologies. You can remove the ones that you do not + need. Save this file (you can name it anything you wish) in the + <project-root>/res/xml folder.

    +
    +<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    +    <tech-list>
    +        <tech>android.nfc.tech.IsoDep</tech>
    +        <tech>android.nfc.tech.NfcA</tech>
    +        <tech>android.nfc.tech.NfcB</tech>
    +        <tech>android.nfc.tech.NfcF</tech>
    +        <tech>android.nfc.tech.NfcV</tech>
    +        <tech>android.nfc.tech.Ndef</tech>
    +        <tech>android.nfc.tech.NdefFormatable</tech>
    +        <tech>android.nfc.tech.MifareClassic</tech>
    +        <tech>android.nfc.tech.MifareUltralight</tech>
    +    </tech-list>
    +</resources>
    +
    + +

    You can also specify multiple tech-list sets. Each of the tech-list + sets is considered independently, and your activity is considered a match if any single + tech-list set is a subset of the technologies that are returned by {@link + android.nfc.Tag#getTechList getTechList()}. This provides AND and OR + semantics for matching technologies. The following example matches tags that can support the + NfcA and Ndef technologies or can support the NfcB and Ndef technologies:

    +
    +<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    +    <tech-list>
    +        <tech>android.nfc.tech.NfcA</tech>
    +        <tech>android.nfc.tech.Ndef</tech>
    +    </tech-list>
    +</resources>
    +
    +<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    +    <tech-list>
    +        <tech>android.nfc.tech.NfcB</tech>
    +        <tech>android.nfc.tech.Ndef</tech>
    +    </tech-list>
    +</resources>
    +
    + +

    In your AndroidManifest.xml file, specify the resource file that you just created + in the <meta-data> element inside the <activity> + element like in the following example:

    +
    +<activity>
    +...
    +<intent-filter>
    +    <action android:name="android.nfc.action.TECH_DISCOVERED"/>
    +</intent-filter>
    +
    +<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
    +    android:resource="@xml/nfc_tech_filter" />
    +...
    +</activity>
    +
    + +

    For more information about working with tag technologies and the {@link +android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent, see Working with Supported Tag +Technologies in the Advanced NFC document.

    +

    ACTION_TAG_DISCOVERED

    +

    To filter for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} use the following intent +filter:

    + + +
    <intent-filter>
    +    <action android:name="android.nfc.action.TAG_DISCOVERED"/>
    +</intent-filter>
    +
    + + + +

    Obtaining information from intents

    + +

    If an activity starts because of an NFC intent, you can obtain information about the scanned NFC +tag from the intent. Intents can contain the following extras depending on the tag that was scanned: + +

      +
    • {@link android.nfc.NfcAdapter#EXTRA_TAG} (required): A {@link android.nfc.Tag} object +representing the scanned tag.
    • +
    • {@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES} (optional): An array of NDEF messages +parsed from the tag. This extra is mandatory on {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED +intents.
    • +
    • {@link android.nfc.NfcAdapter#EXTRA_ID} (optional): The low-level ID of the tag.
    + +

    To obtain these extras, check to see if your activity was launched with one of +the NFC intents to ensure that a tag was scanned, and then obtain the extras out of the +intent. The following example checks for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} +intent and gets the NDEF messages from an intent extra.

    + +
    +public void onResume() {
    +    super.onResume();
    +    ...
    +    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
    +        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    +        if (rawMsgs != null) {
    +            msgs = new NdefMessage[rawMsgs.length];
    +            for (int i = 0; i < rawMsgs.length; i++) {
    +                msgs[i] = (NdefMessage) rawMsgs[i];
    +            }
    +        }
    +    }
    +    //process the msgs array
    +}
    +
    + +

    Alternatively, you can obtain a {@link android.nfc.Tag} object from the intent, which will +contain the payload and allow you to enumerate the tag's technologies:

    + +
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    + + +

    Creating Common Types of NDEF Records

    +

    This section describes how to create common types of NDEF records to help you when writing to +NFC tags or sending data with Android Beam. It also describes how to create the corresponding +intent filter for the record. All of these NDEF record examples should be in the first NDEF +record of the NDEF message that you are writing to a tag or beaming.

    + +

    TNF_ABSOLUTE_URI

    +

    Given the following {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI} NDEF record, which is +stored as the first record inside of an {@link android.nfc.NdefMessage}:

    + +
    +NdefRecord uriRecord = new NdefRecord(
    +    NdefRecord.TNF_ABSOLUTE_URI ,
    +    "http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),
    +    new byte[0], new byte[0]);
    +
    + +

    the intent filter would look like this:

    +
    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <data android:scheme="http"
    +        android:host="developer.android.com"
    +        android:pathPrefix="/index.html" />
    +</intent-filter>
    +
    + + +

    TNF_MIME_MEDIA

    +

    Given the following {@link android.nfc.NdefRecord#TNF_MIME_MEDIA} NDEF record, which is stored as +the first record inside +of an {@link android.nfc.NdefMessage}:

    +
    +NdefRecord mimeRecord = new NdefRecord(
    +    NdefRecord.TNF_MIME_MEDIA ,
    +    "application/com.example.android.beam".getBytes(Charset.forName("US-ASCII")),
    +    new byte[0], "Beam me up, Android!".getBytes(Charset.forName("US-ASCII")));
    +
    + +

    the intent filter would look like this:

    +
    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <data android:mimeType="application/com.example.android.beam" />
    +</intent-filter>
    +
    + + +

    TNF_WELL_KNOWN with RTD_TEXT

    + +

    Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as +the first record inside of an {@link android.nfc.NdefMessage}:

    +
    +public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    +    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    +    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    +    byte[] textBytes = payload.getBytes(utfEncoding);
    +    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    +    char status = (char) (utfBit + langBytes.length);
    +    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    +    data[0] = (byte) status;
    +    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    +    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    +    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    +    NdefRecord.RTD_TEXT, new byte[0], data);
    +    return record;
    +}
    +
    + +

    the intent filter would look like this:

    +
    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <data android:mimeType="text/plain" />
    +</intent-filter>
    +
    + + +

    TNF_WELL_KNOWN with RTD_URI

    + +

    Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as +the first record inside of an {@link android.nfc.NdefMessage}:

    + +
    +byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII"));
    +byte[] payload = new byte[uriField.length + 1];              //add 1 for the URI Prefix
    +byte payload[0] = 0x01;                                      //prefixes http://www. to the URI
    +System.arraycopy(uriField, 0, payload, 1, uriField.length);  //appends URI to payload
    +NdefRecord rtdUriRecord = new NdefRecord(
    +    NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);
    +
    + +

    the intent filter would look like this:

    + +
    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <data android:scheme="http"
    +        android:host="example.com"
    +        android:pathPrefix="" />
    +</intent-filter>
    +
    + +

    TNF_EXTERNAL_TYPE

    +

    Given the following {@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} NDEF record, which is stored +as the first record inside of an {@link android.nfc.NdefMessage}:

    + +
    +byte[] payload;
    +...
    +NdefRecord mimeRecord = new NdefRecord(
    +    NdefRecord.TNF_EXTERNAL_TYPE, "example.com:externalType", new byte[0], payload);
    +
    + +

    the intent filter would look like this:

    +
    +<intent-filter>
    +    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    +    <category android:name="android.intent.category.DEFAULT" />
    +    <data android:scheme="vnd.android.nfc"
    +        android:host="ext"
    +        android:pathPrefix="/example.com:externalType"/>
    +</intent-filter>
    +
    + + +

    Use TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better support both +Android-powered and non-Android-powered devices.

    + +

    Note: URNs for {@link +android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} have a canonical format of: +urn:nfc:ext:example.com:externalType, however the NFC Forum RTD specification +declares that the urn:nfc:ext: portion of the URN must be ommitted from the +NDEF record. So all you need to provide is the domain (example.com in the example) +and type (externalType in the example) separated by a colon. +When dispatching TNF_EXTERNAL_TYPE, Android converts the urn:nfc:ext:example.com:externalType URN to a +vnd.android.nfc://ext/example.com:externalType URI, which is what the intent filter in the example +declares.

    + +

    Android Application Records

    + +

    +Introduced in Android 4.0 (API level 14), an Android Application Record (AAR) provides a stronger +certainty that your application is started when an NFC tag is scanned. An AAR has the package name +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, +Google Play is launched to download the application.

    + +

    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, use intent filters. +

    + + + +

    If a tag contains an AAR, the tag dispatch system dispatches in the following manner:

    +
      +
    1. Try to start an Activity using an intent filter as normal. If the Activity that matches +the intent also matches the AAR, start the Activity.
    2. +
    3. 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.
    4. +
    5. If no application can start with the AAR, go to Google Play to download the +application based on the AAR.
    6. +
    + +

    + +

    Note: You can override AARs and the intent dispatch system with the foreground dispatch +system, which allows a foreground activity to have priority when an NFC tag is discovered. +With this method, the activity must be in the foreground to +override AARs and the intent dispatch system.

    + +

    If you still want to filter for scanned tags that do not contain an AAR, you can declare +intent filters as normal. This is useful if your application is interested in other tags +that do not contain an AAR. For example, maybe you want to guarantee that your application handles +proprietary tags that you deploy as well as general tags deployed by third parties. Keep in mind +that AARs are specific to Android 4.0 devices or later, so when deploying tags, you most likely want +to use a combination of AARs and MIME types/URIs to support the widest range of devices. In +addition, when you deploy NFC tags, think about how you want to write your NFC tags to enable +support for the most devices (Android-powered and other devices). You can do this by +defining a relatively unique MIME type or URI to make it easier for applications to distinguish. +

    + +

    Android provides a simple API to create an AAR, +{@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}. All you need to +do is embed the AAR anywhere in your {@link android.nfc.NdefMessage}. You do not want +to use the first record of your {@link android.nfc.NdefMessage}, unless the AAR is the only +record in the {@link android.nfc.NdefMessage}. This is because the Android +system checks the first record of an {@link android.nfc.NdefMessage} to determine the MIME type or +URI of the tag, which is used to create an intent for applications to filter. The following code +shows you how to create an AAR:

    + +
    +NdefMessage msg = new NdefMessage(
    +        new NdefRecord[] {
    +            ...,
    +            NdefRecord.createApplicationRecord("com.example.android.beam")}
    +
    + + +

    Beaming NDEF Messages to Other Devices

    + +

    Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The +application that wants to beam data to another device must be in the foreground and the device +receiving the data must not be locked. When the beaming device comes in close enough contact with a +receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose +whether or not to beam the message to the receiving device.

    + +

    Note: Foreground NDEF pushing was available at API level 10, +which provides similar functionality to Android Beam. These APIs have since been deprecated, but +are available to support older devices. See {@link android.nfc.NfcAdapter#enableForegroundNdefPush +enableForegroundNdefPush()} for more information.

    + +

    You can enable Android Beam for your application by calling one of the two methods:

    +
      +
    • {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()}: Accepts an +{@link android.nfc.NdefMessage} to set as the message to beam. Automatically beams the message +when two devices are in close enough proximity.
    • +
    • {@link android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}: +Accepts a callback that contains a +{@link android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} +which is called when a device is in range to beam data to. The callback lets you create +the NDEF message only when necessary.
    • +
    + +

    An activity can only push one NDEF message at a time, so {@link +android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()} takes precedence +over {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if both are set. To use +Android Beam, the following general guidelines must be met: +

    + +
      +
    • The activity that is beaming the data must be in the foreground. Both devices must have +their screens unlocked.
    • + +
    • You must encapsulate the data that you are beaming in an {@link android.nfc.NdefMessage} + object.
    • + +
    • The NFC device that is receiving the beamed data must support the + com.android.npp NDEF push protocol or NFC Forum's SNEP (Simple NDEF Exchange +Protocol). The com.android.npp protocol is required for devices on API level 9 (Android +2.3) to API level 13 (Android 3.2). com.android.npp and SNEP are both required on +API level 14 (Android 4.0) and later.
    • + +
    + +

    Note: If your activity enables Android Beam and is +in the foreground, the standard intent dispatch system is disabled. However, if your activity also +enables foreground +dispatching, then it can still scan tags that match the intent filters set in the foreground +dispatching.

    + +

    To enable Android Beam:

    + +
      +
    1. Create an {@link android.nfc.NdefMessage} that contains the {@link android.nfc.NdefRecord}s +that you want to push onto the other device.
    2. + +
    3. Call {@link +android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} with a {@link +android.nfc.NdefMessage} or call {@link +android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} passing in a {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback} object in the onCreate() method of +your activity. These methods require at least one activity that you want to enable with Android +Beam, along with an optional list of other activities to activate. + +

      In general, you normally use {@link +android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if your Activity only needs to +push the same NDEF message at all times, when two devices are in range to communicate. You use +{@link android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} when your +application cares about the current context of the application and wants to push an NDEF message +depending on what the user is doing in your application.

      +
    4. +
    + +

    The following sample shows how a simple activity calls {@link +android.nfc.NfcAdapter.CreateNdefMessageCallback} in the onCreate() method of an +activity (see AndroidBeamDemo +for the complete sample). This example also has methods to help you create a MIME record:

    + +
    +package com.example.android.beam;
    +
    +import android.app.Activity;
    +import android.content.Intent;
    +import android.nfc.NdefMessage;
    +import android.nfc.NdefRecord;
    +import android.nfc.NfcAdapter;
    +import android.nfc.NfcAdapter.CreateNdefMessageCallback;
    +import android.nfc.NfcEvent;
    +import android.os.Bundle;
    +import android.os.Parcelable;
    +import android.widget.TextView;
    +import android.widget.Toast;
    +import java.nio.charset.Charset;
    +
    +
    +public class Beam extends Activity implements CreateNdefMessageCallback {
    +    NfcAdapter mNfcAdapter;
    +    TextView textView;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main);
    +        TextView textView = (TextView) findViewById(R.id.textView);
    +        // Check for available NFC Adapter
    +        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    +        if (mNfcAdapter == null) {
    +            Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
    +            finish();
    +            return;
    +        }
    +        // Register callback
    +        mNfcAdapter.setNdefPushMessageCallback(this, this);
    +    }
    +
    +    @Override
    +    public NdefMessage createNdefMessage(NfcEvent event) {
    +        String text = ("Beam me up, Android!\n\n" +
    +                "Beam Time: " + System.currentTimeMillis());
    +        NdefMessage msg = new NdefMessage(
    +                new NdefRecord[] { createMimeRecord(
    +                        "application/com.example.android.beam", text.getBytes())
    +         /**
    +          * The Android Application Record (AAR) is commented out. When a device
    +          * receives a push with an AAR in it, the application specified in the AAR
    +          * is guaranteed to run. The AAR overrides the tag dispatch system.
    +          * You can add it back in to guarantee that this
    +          * activity starts when receiving a beamed message. For now, this code
    +          * uses the tag dispatch system.
    +          */
    +          //,NdefRecord.createApplicationRecord("com.example.android.beam")
    +        });
    +        return msg;
    +    }
    +
    +    @Override
    +    public void onResume() {
    +        super.onResume();
    +        // Check to see that the Activity started due to an Android Beam
    +        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
    +            processIntent(getIntent());
    +        }
    +    }
    +
    +    @Override
    +    public void onNewIntent(Intent intent) {
    +        // onResume gets called after this to handle the intent
    +        setIntent(intent);
    +    }
    +
    +    /**
    +     * Parses the NDEF Message from the intent and prints to the TextView
    +     */
    +    void processIntent(Intent intent) {
    +        textView = (TextView) findViewById(R.id.textView);
    +        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
    +                NfcAdapter.EXTRA_NDEF_MESSAGES);
    +        // only one message sent during the beam
    +        NdefMessage msg = (NdefMessage) rawMsgs[0];
    +        // record 0 contains the MIME type, record 1 is the AAR, if present
    +        textView.setText(new String(msg.getRecords()[0].getPayload()));
    +    }
    +
    +    /**
    +     * Creates a custom MIME type encapsulated in an NDEF record
    +     */
    +    public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
    +        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
    +        NdefRecord mimeRecord = new NdefRecord(
    +                NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
    +        return mimeRecord;
    +    }
    +}
    +
    + +

    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, 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: +

    + +
    +<intent-filter>
    +  <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    +  <category android:name="android.intent.category.DEFAULT"/>
    +  <data android:mimeType="application/com.example.android.beam"/>
    +</intent-filter>
    +
    +

    With this intent filter, the com.example.android.beam application now can be started +when it scans an NFC tag or receives an Android Beam with an AAR of +type com.example.android.beam, or when an NDEF formatted message contains a MIME record +of type application/com.example.android.beam.

    + +

    Even though AARs guarantee an application is started or downloaded, intent filters are +recommended, because they let you start an Activity of your choice in your +application instead of always starting the main Activity within the package specified by an AAR. +AARs do not have Activity level granularity. Also, because some Android-powered devices do not +support AARs, you should also embed identifying information in the first NDEF record of your NDEF +messages and filter for that as well, just in case. See Creating Common +Types of NDEF records for more information on how to create records. +

    diff --git a/docs/html/guide/topics/connectivity/sip.jd b/docs/html/guide/topics/connectivity/sip.jd new file mode 100644 index 000000000000..a5f0e2e49a26 --- /dev/null +++ b/docs/html/guide/topics/connectivity/sip.jd @@ -0,0 +1,490 @@ +page.title=Session Initiation Protocol +@jd:body +
    +
    +

    In this document

    +
      + +
    1. Requirements and Limitations
    2. +
    3. Classes and Interfaces
    4. +
    5. Creating the Manifest
    6. +
    7. Creating a SIP Manager
    8. +
    9. Registering with a SIP Server
    10. +
    11. Making an Audio Call
    12. +
    13. Receiving Calls
    14. +
    15. Testing SIP Applications
    16. +
    + +

    Key classes

    +
      +
    1. {@link android.net.sip.SipManager}
    2. +
    3. {@link android.net.sip.SipProfile}
    4. +
    5. {@link android.net.sip.SipAudioCall}
    6. + +
    + +

    Related samples

    +
      +
    1. SipDemo
    2. +
    +
    +
    + +

    Android provides an API that supports the Session Initiation Protocol (SIP). +This lets you add SIP-based internet telephony features to your applications. +Android includes a full SIP protocol stack and integrated call management +services that let applications easily set up outgoing and incoming voice calls, +without having to manage sessions, transport-level communication, or audio +record or playback directly.

    + +

    Here are examples of the types of applications that might use the SIP API:

    +
      +
    • Video conferencing.
    • +
    • Instant messaging.
    • +
    +

    Requirements and Limitations

    +

    Here are the requirements for developing a SIP application:

    +
      + +
    • You must have a mobile device that is running Android 2.3 or higher.
    • + +
    • SIP runs over a wireless data connection, so your device must have a data +connection (with a mobile data service or Wi-Fi). This means that you +can't test on AVD—you can only test on a physical device. For details, see +Testing SIP Applications.
    • + +
    • Each participant in the application's communication session must have a +SIP account. There are many different SIP providers that offer SIP accounts.
    • +
    + + +

    SIP API Classes and Interfaces

    + +

    Here is a summary of the classes and one interface +(SipRegistrationListener) that are included in the Android SIP +API:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Class/InterfaceDescription
    {@link android.net.sip.SipAudioCall}Handles an Internet audio call over SIP.
    {@link android.net.sip.SipAudioCall.Listener}Listener for events relating to a SIP call, such as when a call is being +received ("on ringing") or a call is outgoing ("on calling").
    {@link android.net.sip.SipErrorCode}Defines error codes returned during SIP actions.
    {@link android.net.sip.SipManager}Provides APIs for SIP tasks, such as initiating SIP connections, and provides access +to related SIP services.
    {@link android.net.sip.SipProfile}Defines a SIP profile, including a SIP account, domain and server information. +
    {@link android.net.sip.SipProfile.Builder}Helper class for creating a SipProfile.
    {@link android.net.sip.SipSession}Represents a SIP session that is associated with a SIP dialog or a standalone transaction +not within a dialog.
    {@link android.net.sip.SipSession.Listener}Listener for events relating to a SIP session, such as when a session is being registered +("on registering") or a call is outgoing ("on calling").
    {@link android.net.sip.SipSession.State}Defines SIP session states, such as "registering", "outgoing call", and "in call".
    {@link android.net.sip.SipRegistrationListener}An interface that is a listener for SIP registration events.
    + +

    Creating the Manifest

    + +

    If you are developing an application that uses the SIP API, remember that the +feature is supported only on Android 2.3 (API level 9) and higher versions of +the platform. Also, among devices running Android 2.3 (API level 9) or higher, +not all devices will offer SIP support.

    + +

    To use SIP, add the following permissions to your application's manifest:

    +
      +
    • android.permission.USE_SIP
    • +
    • android.permission.INTERNET
    • +
    + +

    To ensure that your application can only be installed on devices that are +capable of supporting SIP, add the following to your application's +manifest:

    + +
      +
    • <uses-sdk android:minSdkVersion="9" />. This + indicates that your application requires Android 2.3 or higher. For more +information, see API +Levels and the documentation for the <uses-sdk> element.
    • +
    + +

    To control how your application is filtered from devices that do not support +SIP (for example, on Google Play), add the following to your application's +manifest:

    + +
      + +
    • <uses-feature android:name="android.hardware.sip.voip" +/>. This states that your application uses the SIP API. The +declaration should include an android:required attribute that +indicates whether you want the application to be filtered from devices that do +not offer SIP support. Other <uses-feature> declarations +may also be needed, depending on your implementation. For more information, +see the documentation for the <uses- +feature> element.
    • + +
    +

    If your application is designed to receive calls, you must also define a receiver ({@link android.content.BroadcastReceiver} subclass) in the application's manifest:

    + +
      +
    • <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>
    • +
    +

    Here are excerpts from the SipDemo manifest:

    + + + +
    <?xml version="1.0" encoding="utf-8"?>
    +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +          package="com.example.android.sip">
    +  ...
    +     <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>
    +  ...
    +  <uses-sdk android:minSdkVersion="9" />
    +  <uses-permission android:name="android.permission.USE_SIP" />
    +  <uses-permission android:name="android.permission.INTERNET" />
    +  ...
    +  <uses-feature android:name="android.hardware.sip.voip" android:required="true" />
    +  <uses-feature android:name="android.hardware.wifi" android:required="true" />
    +  <uses-feature android:name="android.hardware.microphone" android:required="true" />
    +</manifest>
    +
    + + +

    Creating a SipManager

    + +

    To use the SIP API, your application must create a {@link +android.net.sip.SipManager} object. The {@link android.net.sip.SipManager} takes +care of the following in your application:

    + +
      +
    • Initiating SIP sessions.
    • +
    • Initiating and receiving calls.
    • +
    • Registering and unregistering with a SIP provider.
    • +
    • Verifying session connectivity.
    • +
    +

    You instantiate a new {@link android.net.sip.SipManager} as follows:

    +
    public SipManager mSipManager = null;
    +...
    +if(mSipManager == null) {
    +    mSipManager = SipManager.newInstance(this);
    +}
    +

    Registering with a SIP Server

    + +

    A typical Android SIP application involves one or more users, each of whom +has a SIP account. In an Android SIP application, each SIP account is +represented by a {@link android.net.sip.SipProfile} object.

    + +

    A {@link android.net.sip.SipProfile} defines a SIP profile, including a SIP +account, and domain and server information. The profile associated with the SIP +account on the device running the application is called the local +profile. The profile that the session is connected to is called the +peer profile. When your SIP application logs into the SIP server with +the local {@link android.net.sip.SipProfile}, this effectively registers the +device as the location to send SIP calls to for your SIP address.

    + +

    This section shows how to create a {@link android.net.sip.SipProfile}, +register it with a SIP server, and track registration events.

    + +

    You create a {@link android.net.sip.SipProfile} object as follows:

    +
    +public SipProfile mSipProfile = null;
    +...
    +
    +SipProfile.Builder builder = new SipProfile.Builder(username, domain);
    +builder.setPassword(password);
    +mSipProfile = builder.build();
    + +

    The following code excerpt opens the local profile for making calls and/or +receiving generic SIP calls. The caller can make subsequent calls through +mSipManager.makeAudioCall. This excerpt also sets the action +android.SipDemo.INCOMING_CALL, which will be used by an intent +filter when the device receives a call (see Setting up +an intent filter to receive calls). This is the registration step:

    + +
    Intent intent = new Intent();
    +intent.setAction("android.SipDemo.INCOMING_CALL");
    +PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
    +mSipManager.open(mSipProfile, pendingIntent, null);
    + +

    Finally, this code sets a SipRegistrationListener on the {@link +android.net.sip.SipManager}. This tracks whether the {@link +android.net.sip.SipProfile} was successfully registered with your SIP service +provider:
    +

    + +
    mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
    +
    +public void onRegistering(String localProfileUri) {
    +    updateStatus("Registering with SIP Server...");
    +}
    +
    +public void onRegistrationDone(String localProfileUri, long expiryTime) {
    +    updateStatus("Ready");
    +}
    +   
    +public void onRegistrationFailed(String localProfileUri, int errorCode,
    +    String errorMessage) {
    +    updateStatus("Registration failed.  Please check settings.");
    +}
    + + +

    When your application is done using a profile, it should close it to free +associated objects into memory and unregister the device from the server. For +example:

    + +
    public void closeLocalProfile() {
    +    if (mSipManager == null) {
    +       return;
    +    }
    +    try {
    +       if (mSipProfile != null) {
    +          mSipManager.close(mSipProfile.getUriString());
    +       }
    +     } catch (Exception ee) {
    +       Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
    +     }
    +}
    + +

    Making an Audio Call

    +

    To make an audio call, you must have the following in place:

    +
      + +
    • A {@link android.net.sip.SipProfile} that is making the call (the +"local profile"), and a valid SIP address to receive the call (the +"peer profile"). + +
    • A {@link android.net.sip.SipManager} object.
    • +
    + +

    To make an audio call, you should set up a {@link +android.net.sip.SipAudioCall.Listener}. Much of the client's interaction with +the SIP stack happens through listeners. In this snippet, you see how the {@link +android.net.sip.SipAudioCall.Listener} sets things up after the call is +established:

    + +
    +SipAudioCall.Listener listener = new SipAudioCall.Listener() {
    +  
    +   @Override
    +   public void onCallEstablished(SipAudioCall call) {
    +      call.startAudio();
    +      call.setSpeakerMode(true);
    +      call.toggleMute();
    +         ...
    +   }
    +   
    +   @Override
    +   public void onCallEnded(SipAudioCall call) {
    +      // Do something.
    +   }
    +};
    + +

    Once you've set up the {@link android.net.sip.SipAudioCall.Listener}, you can +make the call. The {@link android.net.sip.SipManager} method +makeAudioCall takes the following parameters:

    + +
      +
    • A local SIP profile (the caller).
    • +
    • A peer SIP profile (the user being called).
    • + +
    • A {@link android.net.sip.SipAudioCall.Listener} to listen to the call +events from {@link android.net.sip.SipAudioCall}. This can be null, +but as shown above, the listener is used to set things up once the call is +established.
    • + +
    • The timeout value, in seconds.
    • +
    +

    For example:

    +
     call = mSipManager.makeAudioCall(mSipProfile.getUriString(), sipAddress, listener, 30);
    + +

    Receiving Calls

    + +

    To receive calls, a SIP application must include a subclass of {@link +android.content.BroadcastReceiver} that has the ability to respond to an intent +indicating that there is an incoming call. Thus, you must do the following in +your application:

    + +
      +
    • In AndroidManifest.xml, declare a +<receiver>. In SipDemo, this is +<receiver android:name=".IncomingCallReceiver" +android:label="Call Receiver"/>.
    • + +
    • Implement the receiver, which is a subclass of {@link +android.content.BroadcastReceiver}. In SipDemo, this is +IncomingCallReceiver.
    • + +
    • Initialize the local profile ({@link android.net.sip.SipProfile}) with a +pending intent that fires your receiver when someone calls the local profile. +
    • + +
    • Set up an intent filter that filters by the action that represents an +incoming call. In SipDemo, this action is +android.SipDemo.INCOMING_CALL.
    • +
    +

    Subclassing BroadcastReceiver

    + +

    To receive calls, your SIP application must subclass {@link +android.content.BroadcastReceiver}. The +Android system handles incoming SIP calls and broadcasts an "incoming +call" intent (as defined by the application) when it receives +a call. Here is the subclassed {@link android.content.BroadcastReceiver} +code from SipDemo. To see the full example, go to SipDemo sample, which +is included in the SDK samples. For information on downloading and installing +the SDK samples, see +Getting the Samples.

    + +
    /*** Listens for incoming SIP calls, intercepts and hands them off to WalkieTalkieActivity.
    + */
    +public class IncomingCallReceiver extends BroadcastReceiver {
    +    /**
    +     * Processes the incoming call, answers it, and hands it over to the
    +     * WalkieTalkieActivity.
    +     * @param context The context under which the receiver is running.
    +     * @param intent The intent being received.
    +     */
    +    @Override
    +    public void onReceive(Context context, Intent intent) {
    +        SipAudioCall incomingCall = null;
    +        try {
    +            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
    +                @Override
    +                public void onRinging(SipAudioCall call, SipProfile caller) {
    +                    try {
    +                        call.answerCall(30);
    +                    } catch (Exception e) {
    +                        e.printStackTrace();
    +                    }
    +                }
    +            };
    +            WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
    +            incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);
    +            incomingCall.answerCall(30);
    +            incomingCall.startAudio();
    +            incomingCall.setSpeakerMode(true);
    +            if(incomingCall.isMuted()) {
    +                incomingCall.toggleMute();
    +            }
    +            wtActivity.call = incomingCall;
    +            wtActivity.updateStatus(incomingCall);
    +        } catch (Exception e) {
    +            if (incomingCall != null) {
    +                incomingCall.close();
    +            }
    +        }
    +    }
    +}
    +
    + +

    Setting up an intent filter to receive calls

    + +

    When the SIP service receives a new call, it sends out an intent with the +action string provided by the application. In SipDemo, this action string is +android.SipDemo.INCOMING_CALL.

    +

    This code excerpt from SipDemo shows how the {@link +android.net.sip.SipProfile} object gets created with a pending intent based on +the action string android.SipDemo.INCOMING_CALL. The +PendingIntent object will perform a broadcast when the {@link +android.net.sip.SipProfile} receives a call:

    + +
    +public SipManager mSipManager = null;
    +public SipProfile mSipProfile = null;
    +...
    +
    +Intent intent = new Intent(); 
    +intent.setAction("android.SipDemo.INCOMING_CALL"); 
    +PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA); 
    +mSipManager.open(mSipProfile, pendingIntent, null);
    + +

    The broadcast will be intercepted by the intent filter, which will then fire +the receiver (IncomingCallReceiver). You can specify an intent +filter in your application's manifest file, or do it in code as in the SipDemo +sample application's onCreate() method +of the application's Activity:

    + +
    +public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
    +...
    +    public IncomingCallReceiver callReceiver;
    +    ...
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +
    +       IntentFilter filter = new IntentFilter();
    +       filter.addAction("android.SipDemo.INCOMING_CALL");
    +       callReceiver = new IncomingCallReceiver();
    +       this.registerReceiver(callReceiver, filter);
    +       ...
    +    }
    +    ...
    +}
    +
    + + +

    Testing SIP Applications

    + +

    To test SIP applications, you need the following:

    +
      +
    • A mobile device that is running Android 2.3 or higher. SIP runs over +wireless, so you must test on an actual device. Testing on AVD won't work.
    • +
    • A SIP account. There are many different SIP providers that offer SIP accounts.
    • +
    • If you are placing a call, it must also be to a valid SIP account.
    • +
    +

    To test a SIP application:

    +
      + +
    1. On your device, connect to wireless (Settings > Wireless & networks +> Wi-Fi > Wi-Fi settings)
    2. +
    3. Set up your mobile device for testing, as described in Developing on a Device.
    4. +
    5. Run your application on your mobile device, as described in Developing on a Device.
    6. + +
    7. If you are using Eclipse, you can view the application log output in Eclipse +using LogCat (Window > Show View > Other > Android > +LogCat).
    8. +
    + diff --git a/docs/html/guide/topics/connectivity/usb/accessory.jd b/docs/html/guide/topics/connectivity/usb/accessory.jd new file mode 100644 index 000000000000..a2177678fc56 --- /dev/null +++ b/docs/html/guide/topics/connectivity/usb/accessory.jd @@ -0,0 +1,462 @@ +page.title=USB Accessory +@jd:body + + + +

    USB accessory mode allows users to connect + USB host hardware specifically designed for Android-powered devices. The accessories must adhere + to the Android accessory protocol outlined in the Android Accessory Development Kit documentation. + This allows Android-powered devices that cannot act as a USB host to still interact with USB + hardware. When an Android-powered device is in USB accessory mode, the attached Android USB + accessory acts as the host, provides power to the USB bus, and enumerates connected devices. + Android 3.1 (API level 12) supports USB accessory mode and the feature is also backported to + Android 2.3.4 (API level 10) to enable support for a broader range of devices.

    + +

    Choosing the Right USB Accessory APIs

    + +

    Although the USB accessory APIs were introduced to the platform in Android 3.1, they are also + available in Android 2.3.4 using the Google APIs add-on library. Because these APIs were + backported using an external library, there are two packages that you can import to support USB + accessory mode. Depending on what Android-powered devices you want to support, you might have to + use one over the other:

    + +
      +
    • com.android.future.usb: To support USB accessory mode in Android 2.3.4, the + Google APIs add-on + library includes the backported USB accessory APIs and they are contained in this + namespace. Android 3.1 also supports importing and calling the classes within this namespace to + support applications written with the add-on library. This add-on library is a thin wrapper + around the {@link android.hardware.usb} accessory APIs and does not support USB host mode. If + you want to support the widest range of devices that support USB accessory mode, use the add-on + library and import this package. It is important to note that not all Android 2.3.4 devices are + required to support the USB accessory feature. Each individual device manufacturer decides + whether or not to support this capability, which is why you must declare it in your manifest + file.
    • + +
    • {@link android.hardware.usb}: This namespace contains the classes that support USB + accessory mode in Android 3.1. This package is included as part of the framework APIs, so + Android 3.1 supports USB accessory mode without the use of an add-on library. Use this package + if you only care about Android 3.1 or newer devices that have hardware support for USB + accessory mode, which you can declare in your manifest file.
    • +
    + +

    Installing the Google APIs add-on library

    + +

    If you want to install the add-on, you can do so by installing the Google APIs Android API 10 + package with the SDK Manager. See Installing the Google APIs + Add-on for more information on installing the add-on library.

    + +

    API Overview

    + +

    Because the add-on library is a wrapper for the framework APIs, the classes that support the + USB accessory feature are similar. You can use the reference documentation for the {@link + android.hardware.usb} even if you are using the add-on library.

    + +

    Note: There is, however, a minor usage + difference between the add-on library and framework APIs that you should be aware of.

    + +

    The following table describes the classes that support the USB accessory APIs:

    + + + + + + + + + + + + + + + + + + + +
    ClassDescription
    {@link android.hardware.usb.UsbManager}Allows you to enumerate and communicate with connected USB accessories.
    {@link android.hardware.usb.UsbAccessory}Represents a USB accessory and contains methods to access its identifying + information.
    + +

    Usage differences between the add-on library and platform APIs

    + +

    There are two usage differences between using the Google APIs add-on library and the platform + APIs.

    + +

    If you are using the add-on library, you must obtain the {@link + android.hardware.usb.UsbManager} object in the following manner:

    +
    +UsbManager manager = UsbManager.getInstance(this);
    +
    + +

    If you are not using the add-on library, you must obtain the {@link + android.hardware.usb.UsbManager} object in the following manner:

    +
    +UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    +
    + +

    When you filter for a connected accessory with an intent filter, the {@link + android.hardware.usb.UsbAccessory} object is contained inside the intent that is passed to your + application. If you are using the add-on library, you must obtain the {@link + android.hardware.usb.UsbAccessory} object in the following manner:

    +
    +UsbAccessory accessory = UsbManager.getAccessory(intent);
    +
    + +

    If you are not using the add-on library, you must obtain the {@link + android.hardware.usb.UsbAccessory} object in the following manner:

    +
    +UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
    +
    + +

    Android Manifest requirements

    + +

    The following list describes what you need to add to your application's manifest file before + working with the USB accesory APIs. The manifest and resource file + examples show how to declare these items:

    + +
      +
    • Because not all Android-powered devices are guaranteed to support the USB accessory APIs, + include a <uses-feature> element that declares that your application uses + the android.hardware.usb.accessory feature.
    • + +
    • If you are using the + add-on library, + add the <uses-library> element specifying + com.android.future.usb.accessory for the library.
    • + +
    • Set the minimum SDK of the application to API Level 10 if you are using the add-on library + or 12 if you are using the {@link android.hardware.usb} package.
    • + +
    • +

      If you want your application to be notified of an attached USB accessory, specify an + <intent-filter> and <meta-data> element pair for the + android.hardware.usb.action.USB_ACCESSORY_ATTACHED intent in your main activity. + The <meta-data> element points to an external XML resource file that + declares identifying information about the accessory that you want to detect.

      + +

      In the XML resource file, declare <usb-accessory> elements for the + accessories that you want to filter. Each <usb-accessory> can have the + following attributes:

      + +
        +
      • manufacturer
      • + +
      • model
      • + +
      • version
      • +
      + +

      Save the resource file in the res/xml/ directory. The resource file name + (without the .xml extension) must be the same as the one you specified in the + <meta-data> element. The format for the XML resource file is also shown in + the example below.

      +
    • +
    + +

    Manifest and resource file examples

    + +

    The following example shows a sample manifest and its corresponding resource file:

    +
    +<manifest ...>
    +    <uses-feature android:name="android.hardware.usb.accessory" />
    +    
    +    <uses-sdk android:minSdkVersion="<version>" />
    +    ...
    +    <application>
    +      <uses-library android:name="com.android.future.usb.accessory" />
    +        <activity ...>
    +            ...
    +            <intent-filter>
    +                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
    +            </intent-filter>
    +
    +            <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
    +                android:resource="@xml/accessory_filter" />
    +        </activity>
    +    </application>
    +</manifest>
    +
    + +

    In this case, the following resource file should be saved in + res/xml/accessory_filter.xml and specifies that any accessory that has the + corresponding model, manufacturer, and version should be filtered. The accessory sends these + attributes the Android-powered device:

    +
    +<?xml version="1.0" encoding="utf-8"?>
    +
    +<resources>
    +    <usb-accessory model="DemoKit" manufacturer="Google" version="1.0"/>
    +</resources>
    +
    + +

    Working with Accessories

    + +

    When users connect USB accessories to an Android-powered device, the Android system can + determine whether your application is interested in the connected accessory. If so, you can set + up communication with the accessory if desired. To do this, your application has to:

    + +
      +
    1. Discover connected accessories by using an intent filter that filters for accessory + attached events or by enumerating connected accessories and finding the appropriate one.
    2. + +
    3. Ask the user for permission to communicate with the accessory, if not already + obtained.
    4. + +
    5. Communicate with the accessory by reading and writing data on the appropriate interface + endpoints.
    6. +
    + +

    Discovering an accessory

    + +

    Your application can discover accessories by either using an intent filter to be notified when + the user connects an accessory or by enumerating accessories that are already connected. Using an + intent filter is useful if you want to be able to have your application automatically detect a + desired accessory. Enumerating connected accessories is useful if you want to get a list of all + connected accessories or if your application did not filter for an intent.

    + +

    Using an intent filter

    + +

    To have your application discover a particular USB accessory, you can specify an intent filter + to filter for the android.hardware.usb.action.USB_ACCESSORY_ATTACHED intent. Along + with this intent filter, you need to specify a resource file that specifies properties of the USB + accessory, such as manufacturer, model, and version. When users connect an accessory that matches + your accessory filter,

    + +

    The following example shows how to declare the intent filter:

    +
    +<activity ...>
    +    ...
    +    <intent-filter>
    +        <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
    +    </intent-filter>
    +
    +    <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
    +        android:resource="@xml/accessory_filter" />
    +</activity>
    +
    + +

    The following example shows how to declare the corresponding resource file that specifies the + USB accessories that you're interested in:

    +
    +<?xml version="1.0" encoding="utf-8"?>
    +
    +<resources>
    +    <usb-accessory manufacturer="Google, Inc." model="DemoKit" version="1.0" />
    +</resources>
    +
    + +

    In your activity, you can obtain the {@link android.hardware.usb.UsbAccessory} that represents + the attached accessory from the intent like this (with the add-on library):

    +
    +UsbAccessory accessory = UsbManager.getAccessory(intent);
    +
    + +

    or like this (with the platform APIs):

    +
    +UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
    +
    + +

    Enumerating accessories

    + +

    You can have your application enumerate accesories that have identified themselves while your + application is running.

    + +

    Use the {@link android.hardware.usb.UsbManager#getAccessoryList() getAccessoryList()} method + to get an array all the USB accessories that are connected:

    +
    +UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    +UsbAccessory[] accessoryList = manager.getAcccessoryList();
    +
    + +

    Note: Currently, only one connected accessory is supported at + one time, but the API is designed to support multiple accessories in the future.

    + +

    Obtaining permission to communicate with an accessory

    + +

    Before communicating with the USB accessory, your applicaton must have permission from your + users.

    + +

    Note: If your application uses an + intent filter to discover accessories as they're connected, it automatically receives + permission if the user allows your application to handle the intent. If not, you must request + permission explicitly in your application before connecting to the accessory.

    + +

    Explicitly asking for permission might be neccessary in some situations such as when your + application enumerates accessories that are already connected and then wants to communicate with + one. You must check for permission to access an accessory before trying to communicate with it. + If not, you will receive a runtime error if the user denied permission to access the + accessory.

    + +

    To explicitly obtain permission, first create a broadcast receiver. This receiver listens for + the intent that gets broadcast when you call {@link + android.hardware.usb.UsbManager#requestPermission requestPermission()}. The call to {@link + android.hardware.usb.UsbManager#requestPermission requestPermission()} displays a dialog to the + user asking for permission to connect to the accessory. The following sample code shows how to + create the broadcast receiver:

    +
    +private static final String ACTION_USB_PERMISSION =
    +    "com.android.example.USB_PERMISSION";
    +private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    + 
    +    public void onReceive(Context context, Intent intent) {
    +        String action = intent.getAction();
    +        if (ACTION_USB_PERMISSION.equals(action)) {
    +            synchronized (this) {
    +                UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
    +
    +                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
    +                    if(accessory != null){
    +                        //call method to set up accessory communication
    +                    }
    +                }
    +                else {
    +                    Log.d(TAG, "permission denied for accessory " + accessory);
    +                }
    +            }
    +        }
    +    }
    +};
    +
    + +

    To register the broadcast receiver, put this in your onCreate() method in your + activity:

    +
    +UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    +private static final String ACTION_USB_PERMISSION =
    +    "com.android.example.USB_PERMISSION";
    +...
    +mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    +IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    +registerReceiver(mUsbReceiver, filter);
    +
    + +

    To display the dialog that asks users for permission to connect to the accessory, call the + {@link android.hardware.usb.UsbManager#requestPermission requestPermission()} method:

    +
    +UsbAccessory accessory;
    +...
    +mUsbManager.requestPermission(accessory, mPermissionIntent);
    +
    + +

    When users reply to the dialog, your broadcast receiver receives the intent that contains the + {@link android.hardware.usb.UsbManager#EXTRA_PERMISSION_GRANTED} extra, which is a boolean + representing the answer. Check this extra for a value of true before connecting to the + accessory.

    + +

    Communicating with an accessory

    + +

    You can communicate with the accessory by using the {@link android.hardware.usb.UsbManager} to + obtain a file descriptor that you can set up input and output streams to read and write data to + descriptor. The streams represent the accessory's input and output bulk endpoints. You should set + up the communication between the device and accessory in another thread, so you don't lock the + main UI thread. The following example shows how to open an accessory to communicate with:

    +
    +UsbAccessory mAccessory;
    +ParcelFileDescriptor mFileDescriptor;
    +FileInputStream mInputStream;
    +FileOutputStream mOutputStream;
    +
    +...
    +
    +private void openAccessory() {
    +    Log.d(TAG, "openAccessory: " + accessory);
    +    mFileDescriptor = mUsbManager.openAccessory(mAccessory);
    +    if (mFileDescriptor != null) {
    +        FileDescriptor fd = mFileDescriptor.getFileDescriptor();
    +        mInputStream = new FileInputStream(fd);
    +        mOutputStream = new FileOutputStream(fd);
    +        Thread thread = new Thread(null, this, "AccessoryThread");
    +        thread.start();
    +    }
    +}
    +
    + +

    In the thread's run() method, you can read and write to the accessory by using + the {@link java.io.FileInputStream} or {@link java.io.FileOutputStream} objects. When reading + data from an accessory with a {@link java.io.FileInputStream} object, ensure that the buffer that + you use is big enough to store the USB packet data. The Android accessory protocol supports + packet buffers up to 16384 bytes, so you can choose to always declare your buffer to be of this + size for simplicity.

    + +

    Note: At a lower level, the packets are 64 bytes for USB + full-speed accessories and 512 bytes for USB high-speed accessories. The Android accessory + protocol bundles the packets together for both speeds into one logical packet for simplicity.

    + +

    For more information about using threads in Android, see Processes and + Threads.

    + +

    Terminating communication with an accessory

    + +

    When you are done communicating with an accessory or if the accessory was detached, close the + file descriptor that you opened by calling {@link android.os.ParcelFileDescriptor#close close()}. + To listen for detached events, create a broadcast receiver like below:

    +
    +BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    +    public void onReceive(Context context, Intent intent) {
    +        String action = intent.getAction(); 
    +
    +        if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
    +            UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
    +            if (accessory != null) {
    +                // call your method that cleans up and closes communication with the accessory
    +            }
    +        }
    +    }
    +};
    +
    + +

    Creating the broadcast receiver within the application, and not the manifest, allows your + application to only handle detached events while it is running. This way, detached events are + only sent to the application that is currently running and not broadcast to all applications.

    + diff --git a/docs/html/guide/topics/connectivity/usb/adk.jd b/docs/html/guide/topics/connectivity/usb/adk.jd new file mode 100644 index 000000000000..034728cf9e2c --- /dev/null +++ b/docs/html/guide/topics/connectivity/usb/adk.jd @@ -0,0 +1,909 @@ +page.title=Android Open Accessory Development Kit +@jd:body + + + +

    The Android 3.1 platform (also backported to Android 2.3.4) introduces Android Open Accessory + support, which allows external USB hardware (an Android USB accessory) to interact with an + Android-powered device in a special "accessory" mode. When an Android-powered powered device is + in accessory mode, the connected accessory acts as the USB host (powers the bus and enumerates + devices) and the Android-powered device acts as the USB device. Android USB accessories are + specifically designed to attach to Android-powered devices and adhere to a simple protocol + (Android accessory protocol) that allows them to detect Android-powered devices that support + accessory mode. Accessories must also provide 500mA at 5V for charging power. Many previously + released Android-powered devices are only capable of acting as a USB device and cannot initiate + connections with external USB devices. Android Open Accessory support overcomes this limitation + and allows you to build accessories that can interact with an assortment of Android-powered + devices by allowing the accessory to initiate the connection.

    + +

    Note: Accessory mode is ultimately dependent on the device's + hardware and not all devices will support accessory mode. Devices that support accessory mode can + be filtered using a <uses-feature> element in your corresponding application's + Android manifest. For more information, see the USB Accessory Developer Guide.

    + +

    The following list of distributers are currently producing Android Open Accessory compatible + development boards:

    + +
      + +
    • The Arduino Store provides the Arduino Mega ADK + (in EU nations + or non-EU nations) + that is based on the ATmega2560 and supports the ADK firmware.
    • + +
    • DIY + Drones provides an Arduino-compatible board geared towards RC (radio controlled) and UAV + (unmanned aerial vehicle) enthusiasts.
    • + +
    • mbed provides a microcontroller and a library + to develop accessories that support the Android accessory protocol. For more information, see + mbed with the Android ADK. +
    • + +
    • Microchip provides a PIC based USB + microcontroller board.
    • + +
    • Modern + Device provides an Arduino-compatible board that supports the ADK firmware.
    • + +
    • + RT Corp provides an Arduino-compatible board based on the Android ADK board design.
    • + +
    • + Seeed Studio provides an Arduino-compatible board that supports the ADK firmware.
    • + +
    • + SparkFun's IOIO board now has beta support for the ADK firmware.
    • + +
    + +

    We expect more hardware distributers to create a variety of kits, so please stay tuned for + further developments.

    + +

    ADK Components

    +

    The Android Open Accessory Development Kit (ADK) provides an implementation of an Android USB + accessory that is based on the Arduino open source electronics + prototyping platform, the accessory's hardware design files, code that implements the + accessory's firmware, and the Android application that interacts with the accessory. The hardware + design files and firmware code are contained in the ADK package download.

    +

    The main hardware and software components of the ADK include:

    + +
      +
    • A USB micro-controller board that is based on the Arduino Mega2560 and Circuits@Home USB + Host Shield designs (now referred to as the ADK board), which you will later implement as an + Android USB accessory. The ADK board provides input and output pins that you can implement + through the use of attachments called "shields." Custom firmware, written in C++, is installed + on the board to define the board's functionality and interaction with the attached shield and + Android-powered device. The hardware design files for the board are located in + hardware/ directory.
    • + +
    • An Android Demo Shield (ADK shield) that affixes atop the ADK board implements the input + and output points on the board. These implementations include a joystick, LED outputs, and + temperature and light sensors. You can create or buy your own shields or wire your own features + to the ADK board to implement custom functionality. The hardware design files for the shield + are located in hardware/.
    • + +
    • A library based on the Arduino USB Host Shield + library provides the logic for the USB micro-controller board to act as a USB Host. This allows + the board to initiate transactions with USB devices. Describing how to use this entire library + is beyond the scope of this document. Where needed, this document points out important + interactions with the library. For more information, see the source code for the Arduino USB + Host Shield library in the arduino_libs/USB_Host_Shield directory.
    • + +
    • An Arduino sketch, arduino_libs/AndroidAccessory/examples/demokit/demokit.pde, + defines the firmware that + runs on the ADK board and is written in C++. The sketch calls the Android accessory protocol + library to interact with the Android-powered device. It also sends data from the ADK board and + shield to the Android application and receives data from the Android application and outputs it + to the ADK board and shield.
    • + +
    • The Android accessory protocol library, which is located in the + arduino_libs/AndroidAccessory directory. This library defines how to + enumerate the bus, find a connected Android-powered device that supports accessory mode, and + how to setup communication with the device.
    • + +
    • Other third party libraries to support the ADK board's functionality: + +
    • + +
    + +

    Getting Started with the ADK

    + +

    The following sections describe how to install the Arduino software on your computer, use the + Arduino IDE to install the ADK board's firmware, and install and run the accompanying + Android application for the ADK board. Before you begin, download the following items to set up + your development environment:

    + +
      +
    • Arduino 1.0 or higher: contains + libraries and an IDE for coding and installing firmware to the ADK board.
    • + +
    • CapSense library v.04: + contains the libraries to sense human capacitance. This library is needed for the capacitive + button that is located on the ADK shield.
    • + +
    • ADK software + package: contains the firmware for the ADK board and hardware design files for the ADK + board and shield.
    • +
    + +

    Installing the Arduino software and necessary libraries

    + +

    To install the Arduino software:

    + +
      +
    1. + Download and install the Arduino 1.0 or + higher as described on the Arduino website. + +

      Note: If you are on a Mac, install the FTDI USB Serial + Driver that is included in the Arduino package, even though the installation instructions say + otherwise.

      +
    2. + +
    3. Download and + extract the ADK package to a directory of your choice. You should have an app, + arduino_libs, and hardware directories.
    4. + +
    5. Download and extract + the CapSense package to a directory of your choice.
    6. + +
    7. Install the necessary libraries: + +

      On Windows:

      + +
        +
      1. Copy the arduino_libs/AndroidAccessory and + arduino_libs/USB_Host_Shield directories (the complete directories, + not just the files within) to the <arduino_installation_root>/libraries/ + directory.
      2. + +
      3. Copy the extracted CapSense/ library directory and its contents to the + <arduino_installation_root>/libraries/ directory.
      4. +
      + +

      On Mac:

      + +
        +
      1. Create, if it does not already exist, an Arduino + directory inside your user account's Documents directory, and within + that, a libraries directory.
      2. + +
      3. Copy the arduino_libs/AndroidAccessory and + arduino_libs/USB_Host_Shield directories (the + complete directories, not just the files within) to your + Documents/Arduino/libraries/ directory.
      4. + +
      5. Copy the extracted CapSense/ library directory and its contents to the + Documents/Arduino/libraries/ directory. +
      + +

      On Linux (Ubuntu):

      + +
        +
      1. Copy the firmware/arduino_libs/AndroidAccessory and + firmware/arduino_libs/USB_Host_Shield directories (the complete directories, + not just the files within) to the <arduino_installation_root>/libraries/ + directory.
      2. + +
      3. Copy the extracted CapSense/ library directory and its contents to the + <arduino_installation_root>/libraries/ directory.
      4. + +
      5. Install the avr-libc library by entering sudo apt-get install avr-libc + from a shell prompt.
      6. +
      +
    8. +
    + +

    You should now have three new directories in the Arduino libraries/ directory: + AndroidAccessory, USB_Host_Shield, and CapSense.

    + +

    Installing the firmware to the ADK board

    + +

    To install the firmware to the ADK board:

    + +
      +
    1. Connect the ADK board to your computer using the micro-USB port, which allows two-way + communication and provides power to the ADK board.
    2. + +
    3. Launch the Arduino IDE.
    4. + +
    5. Click Tools > Board > Arduino Mega 2560 to specify the ADK board's + type.
    6. + +
    7. Select the appropriate USB port: + +
        +
      • On Windows: click Tools > Serial Port > COM# to specify the port + of communication. The COM port number varies depending on your computer. COM1 is usually + reserved for serial port connections. You most likely want COM2 or COM3.
      • + +
      • On Mac: Click Tools > Serial Port > dev/tty.usbserial-### to + specify the port of communication.
      • + +
      • On Linux (Ubuntu): Click Tools > Serial Port > dev/ttyUSB# to + specify the port of communication.
      • +
      +
    8. + +
    9. To open the Demokit sketch (firmware code), click File > Examples > + AndroidAccessory > demokit.
    10. + +
    11. Click Sketch > Verify/Compile to ensure that the sketch has no + errors.
    12. + +
    13. Select File > Upload. When Arduino outputs Done + uploading., the board is ready to communicate with your Android-powered device.
    14. +
    + +

    Running the DemoKit Android application

    + +

    The DemoKit Android application runs on your Android-powered device and communicates with the + ADK board. The ADK board receives commands such as lighting up the board's LEDs or sends data + from the board such as joystick movement and temperature readings.

    + +

    To install and run the application in Eclipse:

    + +
      +
    1. Install the + Google APIs API Level 10 add-on library, which includes the Open Accessory library for + 2.3.4 devices that support accessory mode. This library is also forward compatible with Android + 3.1 or newer devices that support accessory mode. If you only care about Android 3.1 or newer + devices, all you need is API Level 12. For more information on deciding which API level to use, + see the USB Accessory + documentation.
    2. + +
    3. Click File > New > Project..., then select Android > + Android Project
    4. + +
    5. In the Project name: field, type DemoKit.
    6. + +
    7. Choose Create project from existing source, click Browse, + select the app directory, click Open to close that dialog and then + click Finish.
    8. + +
    9. For Build Target, select Google APIs (Platform 2.3.3, API Level 10). + +

      Note: Even though the add-on is labeled as + 2.3.3, the newest Google API add-on library for API level 10 adds USB Open + Accessory API support for 2.3.4 devices.

      +
    10. + +
    11. Click Finish.
    12. + +
    13. Install the application to your device.
    14. + +
    15. Connect the ADK board (USB-A) to your Android-powered device (micro-USB). Ensure that the + power cable to the accessory is plugged in or that the micro-USB port on the accesory is + connected to your computer for power (this also allows you to monitor the + ADK board). When connected, accept the prompt that asks for whether or not to open the + DemoKit application to connect to the accessory. If the prompt does not show up, connect and + reconnect the accessory.
    16. +
    + +

    You can now interact with the ADK board by moving the color LED or servo sliders (make sure + the servos are connected) or by pressing the relay buttons in the application. On the ADK shield, + you can press the buttons and move the joystick to see their outputs displayed in the + application.

    + +

    Monitoring the ADK Board

    + +

    The ADK firmware consists of a few files that you should be looking at if you want to build + your own accessory. The files in the arduino_libs/AndroidAccessory + directory are the most important files and have the logic to detect and connect to + Android-powered devices that support accessory mode. Feel free to add debug statements (Arduino + Serial.println() statements) to the code located in the + <arduino_installation_root>/libraries/AndroidAccessory directory and + demokit.pde sketch and re-upload the sketch to the ADK board to + discover more about how the firmware works.

    + +

    You can view the debug statements in the Arduino Serial Monitor by clicking Tools > + Serial Monitor and setting the baud to 115200. The following sections about how + accessories communicate with Android-powered devices describe much of what you should be doing in + your own accessory.

    + +

    Implementing the Android Accessory Protocol

    + +

    An Android USB accessory must adhere to Android Accessory Protocol, which defines how + an accessory detects and sets up communication with an Android-powered device. In general, an + accessory should carry out the following steps:

    + +
      +
    1. Wait for and detect connected devices
    2. + +
    3. Determine the device's accessory mode support
    4. + +
    5. Attempt to start the device in accessory mode if needed
    6. + +
    7. Establish communication with the device if it supports the Android accessory protocol
    8. +
    + +

    The following sections go into depth about how to implement these steps.

    + +

    Wait for and detect connected devices

    + +

    Your accessory should have logic to continuously check + for connected Android-powered devices. When a device is connected, your accessory should + determine if the device supports accessory mode.

    + +

    Determine the device's accessory mode support

    + + +

    When an Android-powered device is connected, it can be in one of three states:

    + +
      +
    1. The attached device supports Android accessory mode and is already in accessory mode.
    2. + +
    3. The attached device supports Android accessory mode, but it is not in accessory mode.
    4. + +
    5. The attached device does not support Android accessory mode.
    6. +
    + +

    During the initial connection, the accessory should check the vendor and product IDs of the + connected device's USB device descriptor. The vendor ID should match Google's ID (0x18D1) and the + product ID should be 0x2D00 or 0x2D01 if the device is already in accessory mode (case A). If so, + the accessory can now establish communication with the device through + bulk transfer endpoints with its own communication protocol. There is no need to start the device + in accessory mode.

    + +

    Note: 0x2D00 is reserved for Android-powered devices that + support accessory mode. 0x2D01 is reserved for devices that support accessory mode as well as the + ADB (Android Debug Bridge) protocol, which exposes a second interface with two bulk endpoints for + ADB. You can use these endpoints for debugging the accessory application if you are simulating + the accessory on a computer. In general, do not use this interface unless your accessory is + implementing a passthrough to ADB on the device.

    + +

    If the vendor and product ID do not match, there is no way to distinguish between states b and + c, so the accessory attempts to start the device in accessory mode to figure + out if the device is supported.

    + +

    Attempt to start the device in accessory mode

    + +

    If the vendor and product IDs do not correspond to an Android-powered device in accessory + mode, the accessory cannot discern whether the device supports accessory mode and is not in that + state, or if the device does not support accessory mode at all. This is because devices that + support accessory mode but aren't in it initially report the device's manufacturer vendor ID and + product ID, and not the special Android Open Accessory ones. In either case, the accessory should try to start + the device into accessory mode to figure out if the device supports it. The following steps + explain how to do this:

    + +
      +
    1. Send a 51 control request ("Get Protocol") to figure out if the device supports the Android + accessory protocol. A non-zero number is returned if the protocol is supported, which + represents the version of the protocol that the device supports (currently, only version 1 + exists). This request is a control request on endpoint 0 with the following characteristics: +
      +requestType:    USB_DIR_IN | USB_TYPE_VENDOR
      +request:        51
      +value:          0
      +index:          0
      +data:           protocol version number (16 bits little endian sent from the device to the accessory)
      +
      +
    2. + +
    3. If the device returns a proper protocol version, send identifying string information to the + device. This information allows the device to figure out an appropriate application for this + accessory and also present the user with a URL if an appropriate application does not exist. + These requests are control requests on endpoint 0 (for each string ID) with the following + characteristics: +
      +requestType:    USB_DIR_OUT | USB_TYPE_VENDOR
      +request:        52
      +value:          0
      +index:          string ID
      +data            zero terminated UTF8 string sent from accessory to device
      +
      + +

      The following string IDs are supported, with a maximum size of 256 bytes for each string + (must be zero terminated with \0).

      +
      +manufacturer name:  0
      +model name:         1
      +description:        2
      +version:            3
      +URI:                4
      +serial number:      5
      +
      +
    4. + +
    5. When the identifying strings are sent, request the device start up in accessory mode. This + request is a control request on endpoint 0 with the following characteristics: +
      +requestType:    USB_DIR_OUT | USB_TYPE_VENDOR
      +request:        53
      +value:          0
      +index:          0
      +data:           none
      +
      +
    6. +
    + +

    After sending the final control request, the connected USB device should re-introduce itself + on the bus in accessory mode and the accessory can re-enumerate the connected devices. The + algorithm jumps back to determining the device's accessory mode support + to check for the vendor and product ID. The vendor ID and product ID of the device will be + different if the device successfully switched to accessory mode and will now correspond to + Google's vendor and product IDs instead of the device manufacturer's IDs. The accessory can now + establish communication with the device.

    + +

    If at any point these steps fail, the device does not support Android accessory mode and the + accessory should wait for the next device to be connected.

    + +

    Establish communication with the device

    + +

    If an Android-powered device in accessory mode is detected, the accessory can query the + device's interface and endpoint descriptors to obtain the bulk endpoints to communicate with the + device. An Android-powered device that has a product ID of 0x2D00 has one interface with two bulk + endpoints for input and output communication. A device with product ID of 0x2D01 has two + interfaces with two bulk endpoints each for input and output communication. The first interface + is for standard communication while the second interface is for ADB communication. To communicate + on an interface, all you need to do is find the first bulk input and output endpoints, set the + device's configuration to a value of 1 with a SET_CONFIGURATION (0x09) device request, then + communicate using the endpoints.

    + +

    How the ADK board implements the Android Accessory protocol

    + +

    If you have access to the ADK board and shield, the following sections describe the firmware + code that you installed onto the ADK board. The firmware demonstrates a practical example of how + to implement the Android Accessory protocol. Even if you do not have the ADK board and shield, + reading through how the hardware detects and interacts with devices in accessory mode is still + useful if you want to port the code over for your own accessories.

    + +

    The important pieces of the firmware are the + arduino_libs/AndroidAccessory/examples/demokit/demokit/demokit.pde sketch, which is + the code that receives and sends data to the DemoKit application running on the Android-powered + device. The code to detect and set up communication with the Android-powered device is contained + in the arduino_libs/AndroidAccessory/AndroidAccessory.h and + arduino_libs/AndroidAccessory/AndroidAccessory.cpp files. This code + includes most of the logic that will help you implement your own accessory's firmware. It might + be useful to have all three of these files open in a text editor as you read through these next + sections.

    + +

    The following sections describe the firmware code in the context of the algorithm described in + Implementing the Android Accessory Protocol.

    + +

    Wait for and detect connected devices

    + +

    In the firmware code (demokit.pde), the loop() function runs + repeatedly and calls AndroidAccessory::isConnected() to check for any connected + devices. If there is a connected device, it continuously updates the input and output streams + going to and from the board and application. If nothing is connected, it continuously checks for + a device to be connected:

    +
    +...
    +
    +AndroidAccessory acc("Google, Inc.",
    +                     "DemoKit",
    +                     "DemoKit Arduino Board",
    +                     "1.0",
    +                     "http://www.android.com",
    +                     "0000000012345678");
    +
    +...
    +void loop()
    +{
    +...
    +    if (acc.isConnected()) {
    +        //communicate with Android application
    +    }
    +    else{
    +        //set the accessory to its default state
    +    }
    +...
    +}
    +
    + +

    Determine the connected device's accessory mode support

    + +

    When a device is connected to the ADK board, it can already be in accessory mode, support + accessory mode and is not in that mode, or does not support accessory mode. The + AndroidAccessory::isConnected() method checks for these cases and responds + accordingly when the loop() function calls it. This function first checks to see if + the device that is connected hasn't already been handled. If not, it gets the connected device's + device descriptor to figure out if the device is already in accessory mode by calling + AndroidAccessory::isAccessoryDevice(). This method checks the vendor and product ID + of the device descriptor. A device in accessory mode has a vendor ID of 0x18D1 and a product ID + of 0x2D00 or 0x2D01. If the device is in accessory mode, then the ADK board can establish communication with the device. If not, the board attempts to start the device in accessory mode.

    +
    +bool AndroidAccessory::isConnected(void)
    +{
    +    USB_DEVICE_DESCRIPTOR *devDesc = (USB_DEVICE_DESCRIPTOR *) descBuff;
    +    byte err;
    +
    +    max.Task();
    +    usb.Task();
    +
    +    if (!connected &&
    +        usb.getUsbTaskState() >= USB_STATE_CONFIGURING &&
    +        usb.getUsbTaskState() != USB_STATE_RUNNING) {
    +        Serial.print("\nDevice addressed... ");
    +        Serial.print("Requesting device descriptor.");
    +
    +        err = usb.getDevDescr(1, 0, 0x12, (char *) devDesc);
    +        if (err) {
    +            Serial.print("\nDevice descriptor cannot be retrieved. Program Halted\n");
    +            while(1);
    +        }
    +
    +        if (isAccessoryDevice(devDesc)) {
    +            Serial.print("found android accessory device\n");
    +
    +            connected = configureAndroid();
    +        } else {
    +            Serial.print("found possible device. switching to serial mode\n");
    +            switchDevice(1);
    +        }
    +    } else if (usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
    +        connected = false;
    +    }
    +
    +    return connected;
    +}
    +
    + +

    Attempt to start the device in accessory mode

    + +

    If the device is not already in accessory mode, then the ADK board must determine whether or + not it supports it by sending control request 51 to check the version of the USB accessory + protocol that the device supports (see AndroidAccessory::getProtocol()). Protocol + version 1 is the only version for now, but this can be an integer greater than zero in the + future. If the appropriate protocol version is returned, the board sends control request 52 (one + for each string with AndroidAcessory:sendString()) to send it's identifying + information, and tries to start the device in accessory mode with control request 53. The + AndroidAccessory::switchDevice() method takes care of this:

    +
    +bool AndroidAccessory::switchDevice(byte addr)
    +{
    +    int protocol = getProtocol(addr);
    +    if (protocol == 1) {
    +        Serial.print("device supports protocol 1\n");
    +    } else {
    +        Serial.print("could not read device protocol version\n");
    +        return false;
    +    }
    +
    +    sendString(addr, ACCESSORY_STRING_MANUFACTURER, manufacturer);
    +    sendString(addr, ACCESSORY_STRING_MODEL, model);
    +    sendString(addr, ACCESSORY_STRING_DESCRIPTION, description);
    +    sendString(addr, ACCESSORY_STRING_VERSION, version);
    +    sendString(addr, ACCESSORY_STRING_URI, uri);
    +    sendString(addr, ACCESSORY_STRING_SERIAL, serial);
    +
    +    usb.ctrlReq(addr, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE,
    +                ACCESSORY_START, 0, 0, 0, 0, NULL);
    +    return true;
    +}
    +
    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 establishes communication with the device. + +

    Establish communication with the device

    + +

    If a device is detected as being in accessory mode, the accessory must find the proper bulk + endpoints and set up communication with the device. When the ADK board detects an Android-powered + device in accessory mode, it calls the AndroidAccessory::configureAndroid() + function:

    +
    +...
    +if (isAccessoryDevice(devDesc)) {
    +            Serial.print("found android acessory device\n");
    +
    +            connected = configureAndroid();
    +        }
    +...
    +
    + +

    which in turn calls the findEndpoints() function:

    +
    +...
    +bool AndroidAccessory::configureAndroid(void)
    +{
    +    byte err;
    +    EP_RECORD inEp, outEp;
    +
    +    if (!findEndpoints(1, &inEp, &outEp))
    +        return false;
    +...
    +
    + +

    The AndroidAccessory::findEndpoints() function queries the Android-powered + device's configuration descriptor and finds the bulk data endpoints in which to communicate with + the USB device. To do this, it first gets the device's first four bytes of the configuration + descriptor (only need descBuff[2] and descBuff[3]), which contains the information about the + total length of data returned by getting the descriptor. This data is used to determine whether + or not the descriptor can fit in the descriptor buffer. This descriptor also contains information + about all the interfaces and endpoint descriptors. If the descriptor is of appropriate size, the + method reads the entire configuration descriptor and fills the entire descriptor buffer with this + device's configuration descriptor. If for some reason the descriptor is no longer attainable, an + error is returned.

    +
    +...
    +
    +bool AndroidAccessory::findEndpoints(byte addr, EP_RECORD *inEp, EP_RECORD *outEp)
    +{
    +    int len;
    +    byte err;
    +    uint8_t *p;
    +
    +    err = usb.getConfDescr(addr, 0, 4, 0, (char *)descBuff);
    +    if (err) {
    +        Serial.print("Can't get config descriptor length\n");
    +        return false;
    +    }
    +
    +
    +    len = descBuff[2] | ((int)descBuff[3] << 8);
    +    if (len > sizeof(descBuff)) {
    +        Serial.print("config descriptor too large\n");
    +            /* might want to truncate here */
    +        return false;
    +    }
    +
    +    err = usb.getConfDescr(addr, 0, len, 0, (char *)descBuff);
    +    if (err) {
    +        Serial.print("Can't get config descriptor\n");
    +        return false;
    +    }
    +
    +...
    +
    + +

    Once the descriptor is in memory, a pointer is assigned to the first position of the buffer + and is used to index the buffer for reading. There are two endpoint pointers (input and output) + that are passed into AndroidAccessory::findEndpoints() and their addresses are set + to 0, because the code hasn't found any suitable bulk endpoints yet. A loop reads the buffer, + parsing each configuration, interface, or endpoint descriptor. For each descriptor, Position 0 + always contains the size of the descriptor in bytes and position 1 always contains the descriptor + type. Using these two values, the loop skips any configuration and interface descriptors and + increments the buffer with the descLen variable to get to the next descriptor.

    + +

    Note: An Android-powered device in accessory mode can + potentially have two interfaces, one for the default communication to the device and the other + for ADB communication. The default communication interface is always indexed first, so finding + the first input and output bulk endpoints will return the default communication endpoints, which + is what the demokit.pde sketch does. If you are writing your own firmware, the logic + to find the appropriate endpoints for your accessory might be different.

    + +

    When it finds the first input and output endpoint descriptors, it sets the endpoint pointers + to those addresses. If the findEndpoints() function finds both an input and output endpoint, it + returns true. It ignores any other endpoints that it finds (the endpoints for the ADB interface, + if present).

    +
    +...
    +    p = descBuff;
    +    inEp->epAddr = 0;
    +    outEp->epAddr = 0;
    +    while (p < (descBuff + len)){
    +        uint8_t descLen = p[0];
    +        uint8_t descType = p[1];
    +        USB_ENDPOINT_DESCRIPTOR *epDesc;
    +        EP_RECORD *ep;
    +
    +        switch (descType) {
    +        case USB_DESCRIPTOR_CONFIGURATION:
    +            Serial.print("config desc\n");
    +            break;
    +
    +        case USB_DESCRIPTOR_INTERFACE:
    +            Serial.print("interface desc\n");
    +            break;
    +
    +        case USB_DESCRIPTOR_ENDPOINT:
    +            epDesc = (USB_ENDPOINT_DESCRIPTOR *)p;
    +            if (!inEp->epAddr && (epDesc->bEndpointAddress & 0x80))
    +                ep = inEp;
    +            else if (!outEp->epAddr)
    +                ep = outEp;
    +            else
    +                ep = NULL;
    +
    +            if (ep) {
    +                ep->epAddr = epDesc->bEndpointAddress & 0x7f;
    +                ep->Attr = epDesc->bmAttributes;
    +                ep->MaxPktSize = epDesc->wMaxPacketSize;
    +                ep->sndToggle = bmSNDTOG0;
    +                ep->rcvToggle = bmRCVTOG0;
    +            }
    +            break;
    +
    +        default:
    +            Serial.print("unkown desc type ");
    +            Serial.println( descType, HEX);
    +            break;
    +        }
    +
    +        p += descLen;
    +    }
    +
    +    if (!(inEp->epAddr && outEp->epAddr))
    +        Serial.println("can't find accessory endpoints");
    +
    +    return inEp->epAddr && outEp->epAddr;
    +}
    +
    +...
    +
    + +

    Back in the configureAndroid() function, if there were endpoints found, they are + appropriately set up for communication. The device's configuration is set to 1 and the state of + the device is set to "running", which signifies that the device is properly set up to communicate + with your USB accessory. Setting this status prevents the device from being re-detected and + re-configured in the AndroidAccessory::isConnected() function.

    +
    +bool AndroidAccessory::configureAndroid(void)
    +{
    +    byte err;
    +    EP_RECORD inEp, outEp;
    +
    +    if (!findEndpoints(1, &inEp, &outEp))
    +        return false;
    +
    +    memset(&epRecord, 0x0, sizeof(epRecord));
    +
    +    epRecord[inEp.epAddr] = inEp;
    +    if (outEp.epAddr != inEp.epAddr)
    +        epRecord[outEp.epAddr] = outEp;
    +
    +    in = inEp.epAddr;
    +    out = outEp.epAddr;
    +
    +    Serial.print("inEp: ");
    +    Serial.println(inEp.epAddr, HEX);
    +    Serial.print("outEp: ");
    +    Serial.println(outEp.epAddr, HEX);
    +
    +    epRecord[0] = *(usb.getDevTableEntry(0,0));
    +    usb.setDevTableEntry(1, epRecord);
    +
    +    err = usb.setConf( 1, 0, 1 );
    +    if (err) {
    +        Serial.print("Can't set config to 1\n");
    +        return false;
    +    }
    +
    +    usb.setUsbTaskState( USB_STATE_RUNNING );
    +
    +    return true;
    +}
    +
    + +

    Lastly, methods to read and write to the appropriate endpoints are needed. The + demokit.pde sketch calls these methods depending on the data that is read from the + Android-powered device or sent by the ADK board. For instance, moving the joystick on the ADK + shield writes data that is read by the DemoKit application running on the Android-powered device. + Moving sliders on the DemoKit application is read by the demokit.pde sketch and + changes the state of the accessory, such as lighting up or changing the color of the LED + lights.

    +
    +int AndroidAccessory::read(void *buff, int len, unsigned int nakLimit) {
    +  return usb.newInTransfer(1, in, len, (char *)buff, nakLimit); }
    +
    +int AndroidAccessory::write(void *buff, int len) {
    +  usb.outTransfer(1, out, len, (char *)buff);
    +  return len; }
    +
    + +

    See the demokit.pde sketch for information about how the ADK board + reads and writes data.

    diff --git a/docs/html/guide/topics/connectivity/usb/host.jd b/docs/html/guide/topics/connectivity/usb/host.jd new file mode 100644 index 000000000000..355dd2dd9199 --- /dev/null +++ b/docs/html/guide/topics/connectivity/usb/host.jd @@ -0,0 +1,440 @@ +page.title=USB Host +@jd:body + + + +

    When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, + and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.

    + +

    API Overview

    + +

    Before you begin, it is important to understand the classes that you need to work with. The + following table describes the USB host APIs in the {@link android.hardware.usb} package.

    + +

    Table 1. USB Host APIs

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ClassDescription
    {@link android.hardware.usb.UsbManager}Allows you to enumerate and communicate with connected USB devices.
    {@link android.hardware.usb.UsbDevice}Represents a connected USB device and contains methods to access its identifying + information, interfaces, and endpoints.
    {@link android.hardware.usb.UsbInterface}Represents an interface of a USB device, which defines a set of functionality for the + device. A device can have one or more interfaces on which to communicate on.
    {@link android.hardware.usb.UsbEndpoint}Represents an interface endpoint, which is a communication channel for this interface. An + interface can have one or more endpoints, and usually has input and output endpoints for + two-way communication with the device.
    {@link android.hardware.usb.UsbDeviceConnection}Represents a connection to the device, which transfers data on endpoints. This class + allows you to send data back and forth sychronously or asynchronously.
    {@link android.hardware.usb.UsbRequest}Represents an asynchronous request to communicate with a device through a {@link + android.hardware.usb.UsbDeviceConnection}.
    {@link android.hardware.usb.UsbConstants}Defines USB constants that correspond to definitions in linux/usb/ch9.h of the Linux + kernel.
    + +

    In most situations, you need to use all of these classes ({@link + android.hardware.usb.UsbRequest} is only required if you are doing asynchronous communication) + when communicating with a USB device. In general, you obtain a {@link + android.hardware.usb.UsbManager} to retrieve the desired {@link android.hardware.usb.UsbDevice}. + When you have the device, you need to find the appropriate {@link + android.hardware.usb.UsbInterface} and the {@link android.hardware.usb.UsbEndpoint} of that + interface to communicate on. Once you obtain the correct endpoint, open a {@link + android.hardware.usb.UsbDeviceConnection} to communicate with the USB device.

    + +

    Android Manifest Requirements

    + +

    The following list describes what you need to add to your application's manifest file before + working with the USB host APIs:

    + +
      +
    • Because not all Android-powered devices are guaranteed to support the USB host APIs, + include a <uses-feature> element that declares that your application uses + the android.hardware.usb.host feature.
    • + +
    • Set the minimum SDK of the application to API Level 12 or higher. The USB host APIs are not + present on earlier API levels.
    • + +
    • If you want your application to be notified of an attached USB device, specify an + <intent-filter> and <meta-data> element pair for the + android.hardware.usb.action.USB_DEVICE_ATTACHED intent in your main activity. The + <meta-data> element points to an external XML resource file that declares + identifying information about the device that you want to detect. + +

      In the XML resource file, declare <usb-device> elements for the USB + devices that you want to filter. The following list describes the attributes of + <usb-device>. In general, use vendor and product ID if you want to filter + for a specific device and use class, subclass, and protocol if you want to filter for a group + of USB devices, such as mass storage devices or digital cameras. You can specify none or + all of these attributes. Specifying no attributes matches every USB device, so only do this + if your application requires it:

      + +
        +
      • vendor-id
      • + +
      • product-id
      • + +
      • class
      • + +
      • subclass
      • + +
      • protocol (device or interface)
      • +
      + +

      Save the resource file in the res/xml/ directory. The resource file name + (without the .xml extension) must be the same as the one you specified in the + <meta-data> element. The format for the XML resource file is in the + example below.

      +
    • +
    + +

    Manifest and resource file examples

    + +

    The following example shows a sample manifest and its corresponding resource file:

    +
    +<manifest ...>
    +    <uses-feature android:name="android.hardware.usb.host" />
    +    <uses-sdk android:minSdkVersion="12" />
    +    ...
    +    <application>
    +        <activity ...>
    +            ...
    +            <intent-filter>
    +                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
    +            </intent-filter>
    +
    +            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
    +                android:resource="@xml/device_filter" />
    +        </activity>
    +    </application>
    +</manifest>
    +
    + +

    In this case, the following resource file should be saved in + res/xml/device_filter.xml and specifies that any USB device with the specified + attributes should be filtered:

    +
    +<?xml version="1.0" encoding="utf-8"?>
    +
    +<resources>
    +    <usb-device vendor-id="1234" product-id="5678" class="255" subclass="66" protocol="1" />
    +</resources>
    +
    + +

    Working with Devices

    + +

    When users connect USB devices to an Android-powered device, the Android system can determine + whether your application is interested in the connected device. If so, you can set up + communication with the device if desired. To do this, your application has to:

    + +
      +
    1. Discover connected USB devices by using an intent filter to be notified when the user + connects a USB device or by enumerating USB devices that are already connected.
    2. + +
    3. Ask the user for permission to connect to the USB device, if not already obtained.
    4. + +
    5. Communicate with the USB device by reading and writing data on the appropriate interface + endpoints.
    6. +
    + +

    Discovering a device

    + +

    Your application can discover USB devices by either using an intent filter to be notified when + the user connects a device or by enumerating USB devices that are already connected. Using an + intent filter is useful if you want to be able to have your application automatically detect a + desired device. Enumerating connected USB devices is useful if you want to get a list of all + connected devices or if your application did not filter for an intent.

    + +

    Using an intent filter

    + +

    To have your application discover a particular USB device, you can specify an intent filter to + filter for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent. Along with + this intent filter, you need to specify a resource file that specifies properties of the USB + device, such as product and vendor ID. When users connect a device that matches your device + filter, the system presents them with a dialog that asks if they want to start your application. + If users accept, your application automatically has permission to access the device until the + device is disconnected.

    + +

    The following example shows how to declare the intent filter:

    +
    +<activity ...>
    +...
    +    <intent-filter>
    +        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
    +    </intent-filter>
    +
    +    <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
    +        android:resource="@xml/device_filter" />
    +</activity>
    +
    + +

    The following example shows how to declare the corresponding resource file that specifies the + USB devices that you're interested in:

    +
    +<?xml version="1.0" encoding="utf-8"?>
    +
    +<resources>
    +    <usb-device vendor-id="1234" product-id="5678" />
    +</resources>
    +
    + +

    In your activity, you can obtain the {@link android.hardware.usb.UsbDevice} that represents + the attached device from the intent like this:

    +
    +UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
    +
    + +

    Enumerating devices

    + +

    If your application is interested in inspecting all of the USB devices currently connected + while your application is running, it can enumerate devices on the bus. Use the {@link + android.hardware.usb.UsbManager#getDeviceList() getDeviceList()} method to get a hash map of all + the USB devices that are connected. The hash map is keyed by the USB device's name if you want to + obtain a device from the map.

    +
    +UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    +...  
    +HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    +UsbDevice device = deviceList.get("deviceName");
    +
    + +

    If desired, you can also just obtain an iterator from the hash map and process each device one + by one:

    +
    +UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    +...
    +HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    +Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    +while(deviceIterator.hasNext()){
    +    UsbDevice device = deviceIterator.next()
    +    //your code
    +}
    +
    + +

    Obtaining permission to communicate with a device

    + +

    Before communicating with the USB device, your applicaton must have permission from your + users.

    + +

    Note: If your application uses an + intent filter to discover USB devices as they're connected, it automatically receives + permission if the user allows your application to handle the intent. If not, you must request + permission explicitly in your application before connecting to the device.

    + +

    Explicitly asking for permission might be neccessary in some situations such as when your + application enumerates USB devices that are already connected and then wants to communicate with + one. You must check for permission to access a device before trying to communicate with it. If + not, you will receive a runtime error if the user denied permission to access the device.

    + +

    To explicitly obtain permission, first create a broadcast receiver. This receiver listens for + the intent that gets broadcast when you call {@link + android.hardware.usb.UsbManager#requestPermission requestPermission()}. The call to {@link + android.hardware.usb.UsbManager#requestPermission requestPermission()} displays a dialog to the + user asking for permission to connect to the device. The following sample code shows how to + create the broadcast receiver:

    +
    +private static final String ACTION_USB_PERMISSION =
    +    "com.android.example.USB_PERMISSION";
    +private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    +
    +    public void onReceive(Context context, Intent intent) {
    +        String action = intent.getAction();
    +        if (ACTION_USB_PERMISSION.equals(action)) {
    +            synchronized (this) {
    +                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
    +
    +                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
    +                    if(device != null){
    +                      //call method to set up device communication
    +                   }
    +                } 
    +                else {
    +                    Log.d(TAG, "permission denied for device " + device);
    +                }
    +            }
    +        }
    +    }
    +};
    +
    + +

    To register the broadcast receiver, add this in your onCreate() method in your + activity:

    +
    +UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    +private static final String ACTION_USB_PERMISSION =
    +    "com.android.example.USB_PERMISSION";
    +...
    +mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    +IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    +registerReceiver(mUsbReceiver, filter);
    +
    + +

    To display the dialog that asks users for permission to connect to the device, call the {@link + android.hardware.usb.UsbManager#requestPermission requestPermission()} method:

    +
    +UsbDevice device;
    +...
    +mUsbManager.requestPermission(device, mPermissionIntent);
    +
    + +

    When users reply to the dialog, your broadcast receiver receives the intent that contains the + {@link android.hardware.usb.UsbManager#EXTRA_PERMISSION_GRANTED} extra, which is a boolean + representing the answer. Check this extra for a value of true before connecting to the + device.

    + +

    Communicating with a device

    + +

    Communication with a USB device can be either synchronous or asynchronous. In either case, you + should create a new thread on which to carry out all data transmissions, so you don't block the + UI thread. To properly set up communication with a device, you need to obtain the appropriate + {@link android.hardware.usb.UsbInterface} and {@link android.hardware.usb.UsbEndpoint} of the + device that you want to communicate on and send requests on this endpoint with a {@link + android.hardware.usb.UsbDeviceConnection}. In general, your code should:

    + +
      +
    • Check a {@link android.hardware.usb.UsbDevice} object's attributes, such as product ID, + vendor ID, or device class to figure out whether or not you want to communicate with the + device.
    • + +
    • When you are certain that you want to communicate with the device, find the appropriate + {@link android.hardware.usb.UsbInterface} that you want to use to communicate along with the + appropriate {@link android.hardware.usb.UsbEndpoint} of that interface. Interfaces can have one + or more endpoints, and commonly will have an input and output endpoint for two-way + communication.
    • + +
    • When you find the correct endpoint, open a {@link android.hardware.usb.UsbDeviceConnection} + on that endpoint.
    • + +
    • Supply the data that you want to transmit on the endpoint with the {@link + android.hardware.usb.UsbDeviceConnection#bulkTransfer bulkTransfer()} or {@link + android.hardware.usb.UsbDeviceConnection#controlTransfer controlTransfer()} method. You should + carry out this step in another thread to prevent blocking the main UI thread. For more + information about using threads in Android, see Processes and + Threads.
    • +
    + +

    The following code snippet is a trivial way to do a synchronous data transfer. Your code + should have more logic to correctly find the correct interface and endpoints to communicate on + and also should do any transferring of data in a different thread than the main UI thread:

    +
    +private Byte[] bytes
    +private static int TIMEOUT = 0;
    +private boolean forceClaim = true;
    +
    +...
    +
    +UsbInterface intf = device.getInterface(0);
    +UsbEndpoint endpoint = intf.getEndpoint(0);
    +UsbDeviceConnection connection = mUsbManager.openDevice(device); 
    +connection.claimInterface(intf, forceClaim);
    +connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //do in another thread
    +
    + +

    To send data asynchronously, use the {@link android.hardware.usb.UsbRequest} class to {@link + android.hardware.usb.UsbRequest#initialize initialize} and {@link + android.hardware.usb.UsbRequest#queue queue} an asynchronous request, then wait for the result + with {@link android.hardware.usb.UsbDeviceConnection#requestWait requestWait()}.

    + +

    For more information, see the AdbTest sample, which shows how to do + asynchronous bulk transfers, and the MissleLauncher sample, which + shows how to listen on an interrupt endpoint asynchronously.

    + +

    Terminating communication with a device

    + +

    When you are done communicating with a device or if the device was detached, close the {@link + android.hardware.usb.UsbInterface} and {@link android.hardware.usb.UsbDeviceConnection} by + calling {@link android.hardware.usb.UsbDeviceConnection#releaseInterface releaseInterface()} and + {@link android.hardware.usb.UsbDeviceConnection#close() close()}. To listen for detached events, + create a broadcast receiver like below:

    +
    +BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    +    public void onReceive(Context context, Intent intent) {
    +        String action = intent.getAction(); 
    +
    +      if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
    +            UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
    +            if (device != null) {
    +                // call your method that cleans up and closes communication with the device
    +            }
    +        }
    +    }
    +};
    +
    + +

    Creating the broadcast receiver within the application, and not the manifest, allows your + application to only handle detached events while it is running. This way, detached events are + only sent to the application that is currently running and not broadcast to all applications.

    + diff --git a/docs/html/guide/topics/connectivity/usb/index.jd b/docs/html/guide/topics/connectivity/usb/index.jd new file mode 100644 index 000000000000..7086ab199d6e --- /dev/null +++ b/docs/html/guide/topics/connectivity/usb/index.jd @@ -0,0 +1,67 @@ +page.title=USB Host and Accessory +@jd:body + +
    +
    +

    Topics

    + +
      +
    1. USB Accessory
    2. + +
    3. USB Host
    4. +
    +
    +
    + +

    Android supports a variety of USB peripherals and Android USB accessories (hardware that + implements the Android accessory protocol) through two modes: USB accessory and USB host. In USB + accessory mode, the external USB hardware act as the USB hosts. Examples of accessories might + include robotics controllers; docking stations; diagnostic and musical equipment; kiosks; card + readers; and much more. This gives Android-powered devices that do not have host capabilities the + ability to interact with USB hardware. Android USB accessories must be designed to work with + Android-powered devices and must adhere to the Android accessory communication protocol. In USB + host mode, the Android-powered device acts as the host. Examples of devices include digital + cameras, keyboards, mice, and game controllers. USB devices that are designed for a wide range of + applications and environments can still interact with Android applications that can correctly + communicate with the device.

    + +

    Figure 1 shows the differences between the two modes. When the Android-powered device is in + host mode, it acts as the USB host and powers the bus. When the Android-powered device is in USB + accessory mode, the connected USB hardware (an Android USB accessory in this case) acts as the + host and powers the bus.

    + +

    Figure 1. USB Host and Accessory Modes

    + +

    USB accessory and host modes are directly supported in Android 3.1 (API level 12) or newer + platforms. USB accessory mode is also backported to Android 2.3.4 (API level 10) as an add-on + library to support a broader range of devices. Device manufacturers can choose whether or not to + include the add-on library on the device's system image.

    + +

    Note: Support for USB host and accessory modes are ultimately + dependant on the device's hardware, regardless of platform level. You can filter for devices that + support USB host and accessory through a <uses-feature> element. See + the USB accessory and host documentation for more details.

    + +

    Debugging considerations

    + +

    When debugging applications that use USB accessory or host features, you most likely will have + USB hardware connected to your Android-powered device. This will prevent you from having an + adb connection to the Android-powered device via USB. You can still access + adb over a network connection. To enable adb over a network + connection:

    + +
      +
    1. Connect the Android-powered device via USB to your computer.
    2. + +
    3. From your SDK platform-tools/ directory, enter adb tcpip 5555 at + the command prompt.
    4. + +
    5. Enter adb connect <device-ip-address>:5555 You should now be connected + to the Android-powered device and can issue the usual adb commands like adb + logcat.
    6. + +
    7. To set your device to listen on USB, enter adb usb.
    8. +
    diff --git a/docs/html/guide/topics/connectivity/wifip2p.jd b/docs/html/guide/topics/connectivity/wifip2p.jd new file mode 100644 index 000000000000..82c9abdb1066 --- /dev/null +++ b/docs/html/guide/topics/connectivity/wifip2p.jd @@ -0,0 +1,611 @@ +page.title=Wi-Fi Direct + +@jd:body + + + +

    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.

    + +

    The Wi-Fi Direct APIs consist of the following main parts:

    + +
      +
    • Methods that allow you to discover, request, and connect to peers are defined + in the {@link android.net.wifi.p2p.WifiP2pManager} class.
    • + +
    • 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.
    • + +
    • Intents that notify you of specific events detected by the Wi-Fi Direct framework, + such as a dropped connection or a newly discovered peer.
    • +
    + +

    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.

    + +

    API Overview

    + +

    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:

    + +

    Table 1.Wi-Fi Direct Methods

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    MethodDescription
    {@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}Registers the application with the Wi-Fi framework. This must be called before calling any other Wi-Fi Direct method.
    {@link android.net.wifi.p2p.WifiP2pManager#connect connect()}Starts a peer-to-peer connection with a device with the specified configuration.
    {@link android.net.wifi.p2p.WifiP2pManager#cancelConnect cancelConnect()}Cancels any ongoing peer-to-peer group negotiation.
    {@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}Requests a device's connection information.
    {@link android.net.wifi.p2p.WifiP2pManager#createGroup createGroup()}Creates a peer-to-peer group with the current device as the group owner.
    {@link android.net.wifi.p2p.WifiP2pManager#removeGroup removeGroup()}Removes the current peer-to-peer group.
    {@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}Requests peer-to-peer group information.
    {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}Initiates peer discovery
    {@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}Requests the current list of discovered peers.
    + + +

    {@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:

    + +

    Table 2. Wi-Fi Direct Listeners

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Listener interfaceAssociated actions
    {@link android.net.wifi.p2p.WifiP2pManager.ActionListener}{@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()}
    {@link android.net.wifi.p2p.WifiP2pManager.ChannelListener}{@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}
    {@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener}{@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}
    {@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener}{@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}
    {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener}{@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}
    + +

    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 creating a broadcast + receiver that handles these intents:

    + +

    Table 3. Wi-Fi Direct Intents

    + + + + + + + + + + + + + + + + + + + + + + +
    IntentDescription
    {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}Broadcast when the state of the device's Wi-Fi connection changes.
    {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}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.
    {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}Broadcast when Wi-Fi Direct is enabled or disabled on the device.
    {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}Broadcast when a device's details have changed, such as the device's name.
    + + + +

    Creating a Broadcast Receiver for Wi-Fi Direct Intents

    + +

    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:

    + +
      +
    1. 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.
    2. + +
    3. In the broadcast receiver, check for the intents that you are interested in + {@link android.content.BroadcastReceiver#onReceive onReceive()}. + 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.
    4. +
    + +

    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:

    + +
    +/**
    + * 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
    +        }
    +    }
    +}
    +
    + +

    Creating a Wi-Fi Direct Application

    + +

    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.

    + +

    Initial setup

    +

    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.

    +
      +
    1. +

      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:

      +
      +<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" />
      +
      +
    2. + +
    3. 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: +
      +@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
      +        }
      +    }
      +    ...
      +}
      +
      +
    4. + +
    5. 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: +
      +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);
      +    ...
      +}
      +
      +
    6. + +
    7. Create an intent filter and add the same intents that your + broadcast receiver checks for: +
      +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);
      +    ...
      +}
      +
      +
    8. + +
    9. 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: +
      +/* 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);
      +}
      +
      + +

      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.

      +
    10. + +

      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.

      +
    + +

    Discovering peers

    + +

    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:

    +
    +manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
    +    @Override
    +    public void onSuccess() {
    +        ...
    +    }
    +
    +    @Override
    +    public void onFailure(int reasonCode) {
    +        ...
    +    }
    +});
    +
    +
    + +

    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:

    +
    +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);
    +    }
    +}
    +
    + +

    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.

    + +

    Connecting to peers

    + +

    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:

    +
    +//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
    +    }
    +});
    +
    +
    + + +

    Transferring data

    +

    Once a connection is established, you can transfer data between the devices with + sockets. The basic steps of transferring data are as follows:

    + +
      +
    1. 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.
    2. + +
    3. 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.
    4. + +
    5. 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.
    6. + +
    7. 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.
    8. +
    + +

    The following example, modified from the Wi-Fi Direct Demo 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 Wi-Fi Direct Demo sample.

    +
    +public static class FileServerAsyncTask extends AsyncTask {
    +
    +    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);
    +        }
    +    }
    +}
    +
    + +

    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.

    + +
    +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
    +            }
    +        }
    +    }
    +}
    +
    diff --git a/docs/html/guide/topics/data/backup.jd b/docs/html/guide/topics/data/backup.jd index d91e422a2388..602b6e84b225 100644 --- a/docs/html/guide/topics/data/backup.jd +++ b/docs/html/guide/topics/data/backup.jd @@ -47,7 +47,7 @@ data onto the new device

    See also

      -
    1. {@code bmgr} tool
    2. +
    3. {@code bmgr} tool
    @@ -316,7 +316,7 @@ backup for all applications that have requested a backup since the last backup w

    Tip: While developing your application, you can initiate an immediate backup operation from the Backup Manager with the {@code bmgr} tool.

    +href="{@docRoot}tools/help/bmgr.html">{@code bmgr} tool.

    When the Backup Manager calls your {@link android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor) @@ -460,7 +460,7 @@ android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore( href="#RequestingRestore">Requesting restore for more information).

    Note: While developing your application, you can also request a -restore operation with the {@code bmgr} +restore operation with the {@code bmgr} tool.

    When the Backup Manager calls your {@link @@ -863,7 +863,7 @@ onBackup()}.

    Note: While developing your application, you can request a backup and initiate an immediate backup operation with the {@code bmgr} +href="{@docRoot}tools/help/bmgr.html">{@code bmgr} tool.

    @@ -878,7 +878,7 @@ android.app.backup.BackupAgent#onRestore(BackupDataInput,int,ParcelFileDescripto implementation, passing the data from the current set of backup data.

    Note: While developing your application, you can request a -restore operation with the {@code bmgr} +restore operation with the {@code bmgr} tool.

    @@ -886,7 +886,7 @@ tool.

    Once you've implemented your backup agent, you can test the backup and restore functionality with the following procedure, using {@code bmgr}.

    +href="{@docRoot}tools/help/bmgr.html">{@code bmgr}.

    1. Install your application on a suitable Android system image diff --git a/docs/html/guide/topics/data/data-storage.jd b/docs/html/guide/topics/data/data-storage.jd index d31afa554c5e..e9d2d25eefb7 100644 --- a/docs/html/guide/topics/data/data-storage.jd +++ b/docs/html/guide/topics/data/data-storage.jd @@ -1,4 +1,4 @@ -page.title=Data Storage +page.title=Storage Options @jd:body @@ -16,22 +16,9 @@ page.title=Data Storage

      In this document

      1. Using Shared Preferences
      2. -
      3. Using the Internal Storage -
          -
        1. Saving cache files
        2. -
        3. Other useful methods
        4. -
      4. -
      5. Using the External Storage -
          -
        1. Checking media availability
        2. -
        3. Accessing files on external storage
        4. -
        5. Saving files that should be shared
        6. -
        7. Saving cache files
        8. -
      6. -
      7. Using Databases -
          -
        1. Database debugging
        2. -
      8. +
      9. Using the Internal Storage
      10. +
      11. Using the External Storage
      12. +
      13. Using Databases
      14. Using a Network Connection
      @@ -449,7 +436,7 @@ applications.

      The Android SDK includes a {@code sqlite3} database tool that allows you to browse table contents, run SQL commands, and perform other useful functions on SQLite -databases. See Examining sqlite3 +databases. See Examining sqlite3 databases from a remote shell to learn how to run this tool.

      diff --git a/docs/html/guide/topics/data/index.html b/docs/html/guide/topics/data/index.html deleted file mode 100644 index a94f8c0b2fe8..000000000000 --- a/docs/html/guide/topics/data/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - -Redirecting... - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/topics/data/index.jd b/docs/html/guide/topics/data/index.jd new file mode 100644 index 000000000000..1e082b3fef95 --- /dev/null +++ b/docs/html/guide/topics/data/index.jd @@ -0,0 +1,23 @@ +page.title=Data Storage +page.landing=true +page.landing.intro=Store application data in databases, files, or preferences, in internal or removeable storage. You can also add a data backup service to let users store and recover application and system data. +page.landing.image= + +@jd:body + + \ No newline at end of file diff --git a/docs/html/guide/topics/data/install-location.jd b/docs/html/guide/topics/data/install-location.jd new file mode 100644 index 000000000000..19c4b3900ef1 --- /dev/null +++ b/docs/html/guide/topics/data/install-location.jd @@ -0,0 +1,206 @@ +page.title=App Install Location +@jd:body + + +
      +
      + +

      Quickview

      +
        +
      • You can allow your application to install on the device's external storage.
      • +
      • Some types of applications should not allow installation on the external +storage.
      • +
      • Installing on the external storage is ideal for large applications that are not tightly +integrated with the system (most commonly, games).
      • +
      + +

      In this document

      +
        +
      1. Backward Compatibility
      2. +
      3. Applications That Should NOT Install on External Storage
      4. +
      5. Applications That Should Install on External Storage
      6. +
      + +

      See also

      +
        +
      1. +<manifest>
      2. +
      + +
      +
      + +

      Beginning with API Level 8, you can allow your application to be installed on the +external storage (for example, the device's SD card). This is an optional feature you can declare +for your application with the {@code +android:installLocation} manifest attribute. If you do +not declare this attribute, your application will be installed on the internal storage +only and it cannot be moved to the external storage.

      + +

      To allow the system to install your application on the external storage, modify your +manifest file to include the {@code +android:installLocation} attribute in the <manifest> element, +with a value of either "{@code preferExternal}" or "{@code auto}". For example:

      + +
      +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      +    android:installLocation="preferExternal"
      +    ... >
      +
      + +

      If you declare "{@code preferExternal}", you request that your application be installed on the +external storage, but the system does not guarantee that your application will be installed on +the external storage. If the external storage is full, the system will install it on the internal +storage. The user can also move your application between the two locations.

      + +

      If you declare "{@code auto}", you indicate that your application may be installed on the +external storage, but you don't have a preference of install location. The system will +decide where to install your application based on several factors. The user can also move your +application between the two locations.

      + +

      When your application is installed on the external storage:

      +
        +
      • There is no effect on the application performance so long +as the external storage is mounted on the device.
      • +
      • The {@code .apk} file is saved on the external storage, but all private user data, +databases, optimized {@code .dex} files, and extracted native code are saved on the +internal device memory.
      • +
      • The unique container in which your application is stored is encrypted with a randomly +generated key that can be decrypted only by the device that originally installed it. Thus, an +application installed on an SD card works for only one device.
      • +
      • The user can move your application to the internal storage through the system settings.
      • +
      + +

      Warning: When the user enables USB mass storage to share files +with a computer or unmounts the SD card via the system settings, the external storage is unmounted +from the device and all applications running on the external storage are immediately killed.

      + + + +

      Backward Compatibility

      + +

      The ability for your application to install on the external storage is a feature available only +on devices running API Level 8 (Android 2.2) or greater. Existing applications that were built prior +to API Level 8 will always install on the internal storage and cannot be moved to the external +storage (even on devices with API Level 8). However, if your application is designed to support an +API Level lower than 8, you can choose to support this feature for devices with API Level 8 +or greater and still be compatible with devices using an API Level lower than 8.

      + +

      To allow installation on external storage and remain compatible with versions lower than API +Level 8:

      +
        +
      1. Include the {@code android:installLocation} attribute with a value of "{@code auto}" or +"{@code preferExternal}" in the <manifest> +element.
      2. +
      3. Leave your {@code android:minSdkVersion} attribute as is (something less +than "8") and be certain that your application code uses only APIs compatible with that +level.
      4. +
      5. In order to compile your application, change your build target to API Level 8. This is +necessary because older Android libraries don't understand the {@code android:installLocation} +attribute and will not compile your application when it's present.
      6. +
      + +

      When your application is installed on a device with an API Level lower than 8, the {@code +android:installLocation} attribute is ignored and the application is installed on the internal +storage.

      + +

      Caution: Although XML markup such as this will be ignored by +older platforms, you must be careful not to use programming APIs introduced in API Level 8 +while your {@code minSdkVersion} is less than "8", unless you perform the work necessary to +provide backward compatibility in your code. For information about building +backward compatibility in your application code, see the Backward Compatibility +article.

      + + + +

      Applications That Should NOT Install on External Storage

      + +

      When the user enables USB mass storage to share files with their computer (or otherwise +unmounts or removes the external storage), any application +installed on the external storage and currently running is killed. The system effectively becomes +unaware of the application until mass storage is disabled and the external storage is +remounted on the device. Besides killing the application and making it unavailable to the user, +this can break some types of applications in a more serious way. In order for your application to +consistently behave as expected, you should not allow your application to be +installed on the external storage if it uses any of the following features, due to the cited +consequences when the external storage is unmounted:

      + +
      +
      Services
      +
      Your running {@link android.app.Service} will be killed and will not be restarted when +external storage is remounted. You can, however, register for the {@link +android.content.Intent#ACTION_EXTERNAL_APPLICATIONS_AVAILABLE} broadcast Intent, which will notify +your application when applications installed on external storage have become available to the +system again. At which time, you can restart your Service.
      +
      Alarm Services
      +
      Your alarms registered with {@link android.app.AlarmManager} will be cancelled. You must +manually re-register any alarms when external storage is remounted.
      +
      Input Method Engines
      +
      Your IME will be +replaced by the default IME. When external storage is remounted, the user can open system settings +to enable your IME again.
      +
      Live Wallpapers
      +
      Your running Live Wallpaper +will be replaced by the default Live Wallpaper. When external storage is remounted, the user can +select your Live Wallpaper again.
      +
      Live Folders
      +
      Your Live Folder will be +removed from the home screen. When external storage is remounted, the user can add your Live Folder +to the home screen again.
      +
      App Widgets
      +
      Your App Widget will be removed +from the home screen. When external storage is remounted, your App Widget will not be +available for the user to select until the system resets the home application (usually not until a +system reboot).
      +
      Account Managers
      +
      Your accounts created with {@link android.accounts.AccountManager} will disappear until +external storage is remounted.
      +
      Sync Adapters
      +
      Your {@link android.content.AbstractThreadedSyncAdapter} and all its sync functionality will +not work until external storage is remounted.
      +
      Device Administrators
      +
      Your {@link android.app.admin.DeviceAdminReceiver} and all its admin capabilities will +be disabled, which can have unforeseeable consequences for the device functionality, which may +persist after external storage is remounted.
      +
      Broadcast Receivers listening for "boot completed"
      +
      The system delivers the {@link android.content.Intent#ACTION_BOOT_COMPLETED} broadcast +before the external storage is mounted to the device. If your application is installed on the +external storage, it can never receive this broadcast.
      +
      Copy Protection
      +
      Your application cannot be installed to a device's SD card if it uses Google Play's + Copy Protection feature. However, if you use Google Play's + Application Licensing instead, your + application can be installed to internal or external storage, including SD cards.
      +
      + +

      If your application uses any of the features listed above, you should not allow +your application to install on external storage. By default, the system will not allow your +application to install on the external storage, so you don't need to worry about your existing +applications. However, if you're certain that your application should never be installed on the +external storage, then you should make this clear by declaring {@code +android:installLocation} with a value of "{@code internalOnly}". Though this does not +change the default behavior, it explicitly states that your application should only be installed +on the internal storage and serves as a reminder to you and other developers that this decision has +been made.

      + + +

      Applications That Should Install on External Storage

      + +

      In simple terms, anything that does not use the features listed in the previous section +are safe when installed on external storage. Large games are more commonly the types of +applications that should allow installation on external storage, because games don't typically +provide additional services when inactive. When external storage becomes unavailable and a game +process is killed, there should be no visible effect when the storage becomes available again and +the user restarts the game (assuming that the game properly saved its state during the normal +Activity lifecycle).

      + +

      If your application requires several megabytes for the APK file, you should +carefully consider whether to enable the application to install on the external storage so that +users can preserve space on their internal storage.

      + diff --git a/docs/html/guide/topics/drawing/index.html b/docs/html/guide/topics/drawing/index.html deleted file mode 100644 index 43c14994df23..000000000000 --- a/docs/html/guide/topics/drawing/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - -Redirecting... - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/topics/drawing/opengl.jd b/docs/html/guide/topics/drawing/opengl.jd deleted file mode 100644 index e22a251f6962..000000000000 --- a/docs/html/guide/topics/drawing/opengl.jd +++ /dev/null @@ -1,53 +0,0 @@ -page.title=OpenGL -@jd:body - -

      Android includes support for 3D hardware acceleration. This functionality is -accessed via the OpenGL API — specifically, the OpenGL ES API.

      - -

      OpenGL ES is a flavor of the OpenGL specification intended for embedded -devices. Versions of OpenGL ES are loosely peered to versions of the primary -OpenGL standard. Android currently supports OpenGL ES 1.0, which corresponds -to OpenGL 1.3. So, if the application you have in mind is possible with OpenGL -1.3 on a desktop system, it should be possible on Android.

      - -

      The specific API provided by Android is similar to the J2ME JSR239 OpenGL -ES API. However, it may not be identical, so watch out for deviations.

      - -

      Using the API

      - -

      Here's how to use the API at an extremely high level:

      - -
        -
      1. Write a custom View subclass.
      2. -
      3. Obtain a handle to an OpenGLContext, which provides access to the OpenGL functionality.
      4. -
      5. In your View's onDraw() method, get a handle to a GL object, and use its methods to perform GL operations.
      6. -
      - -

      For an example of this usage model (based on the classic GL ColorCube), -see -com.android.samples.graphics.GLView1.java -in the ApiDemos sample code project. A slightly more sophisticated version showing how to use -it with threads can be found in -com.android.samples.graphics.GLSurfaceViewActivity.java. -

      - -

      Writing a summary of how to actually write 3D applications using OpenGL is -beyond the scope of this text and is left as an exercise for the reader.

      - -

      Links to Additional Information

      - -

      Information about OpenGL ES can be -found at http://www.khronos.org/opengles/.

      - -

      Information specifically -about OpenGL ES 1.0 (including a detailed specification) can be found -at http://www.khronos.org/opengles/1_X/.

      - -

      The documentation for the Android {@link javax.microedition.khronos.opengles.GL -OpenGL ES implementations} are also available.

      - -

      Finally, note that though Android does include some basic support for -OpenGL ES 1.1, the support is not complete, and should not be relied -upon at this time.

      diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd deleted file mode 100644 index a86d905ad2ce..000000000000 --- a/docs/html/guide/topics/fundamentals.jd +++ /dev/null @@ -1,518 +0,0 @@ -page.title=Application Fundamentals -@jd:body - -
      -
      - -

      Quickview

      -
        -
      • Android applications are composed of one or more application components (activities, -services, content providers, and broadcast receivers)
      • -
      • Each component performs a different role in the overall application behavior, and each -one can be activated individually (even by other applications)
      • -
      • The manifest file must declare all components in the application and should also declare -all application requirements, such as the minimum version of Android required and any hardware -configurations required
      • -
      • Non-code application resources (images, strings, layout files, etc.) should include -alternatives for different device configurations (such as different strings for different -languages and different layouts for different screen sizes)
      • -
      - - -

      In this document

      -
        -
      1. Application Components -
          -
        1. Activating components
        2. -
        -
      2. -
      3. The Manifest File -
          -
        1. Declaring components
        2. -
        3. Declaring application requirements
        4. -
        -
      4. -
      5. Application Resources
      6. -
      -
      -
      - -

      Android applications are written in the Java programming language. The Android SDK tools compile -the code—along with any data and resource files—into an Android package, an -archive file with an {@code .apk} suffix. All the code in a single {@code .apk} file is considered -to be one application and is the file that Android-powered devices use to install the -application.

      - -

      Once installed on a device, each Android application lives in its own security sandbox:

      - -
        -
      • The Android operating system is a multi-user Linux system in which each application is a -different user.
      • - -
      • By default, the system assigns each application a unique Linux user ID (the ID is used only by -the system and is unknown to the application). The system sets permissions for all the files in an -application so that only the user ID assigned to that application can access them.
      • - -
      • Each process has its own virtual machine (VM), so an application's code runs in isolation from -other applications.
      • - -
      • By default, every application runs in its own Linux process. Android starts the process when any -of the application's components need to be executed, then shuts down the process when it's no longer -needed or when the system must recover memory for other applications.
      • -
      - -

      In this way, the Android system implements the principle of least privilege. That is, -each application, by default, has access only to the components that it requires to do its work and -no more. This creates a very secure environment in which an application cannot access parts of -the system for which it is not given permission.

      - -

      However, there are ways for an application to share data with other applications and for an -application to access system services:

      - -
        -
      • It's possible to arrange for two applications to share the same Linux user ID, in which case -they are able to access each other's files. To conserve system resources, applications with the -same user ID can also arrange to run in the same Linux process and share the same VM (the -applications must also be signed with the same certificate).
      • -
      • An application can request permission to access device data such as the user's -contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All -application permissions must be granted by the user at install time.
      • -
      - -

      That covers the basics regarding how an Android application exists within the system. The rest of -this document introduces you to:

      -
        -
      • The core framework components that define your application.
      • -
      • The manifest file in which you declare components and required device features for your -application.
      • -
      • Resources that are separate from the application code and allow your application to -gracefully optimize its behavior for a variety of device configurations.
      • -
      - - - - -

      Application Components

      - -

      Application components are the essential building blocks of an Android application. Each -component is a different point through which the system can enter your application. Not all -components are actual entry points for the user and some depend on each other, but each one exists -as its own entity and plays a specific role—each one is a unique building block that -helps define your application's overall behavior.

      - -

      There are four different types of application components. Each type serves a distinct purpose -and has a distinct lifecycle that defines how the component is created and destroyed.

      - -

      Here are the four types of application components:

      - -
      - -
      Activities
      - -
      An activity represents a single screen with a user interface. For example, -an email application might have one activity that shows a list of new -emails, another activity to compose an email, and another activity for reading emails. Although -the activities work together to form a cohesive user experience in the email application, each one -is independent of the others. As such, a different application can start any one of these -activities (if the email application allows it). For example, a camera application can start the -activity in the email application that composes new mail, in order for the user to share a picture. - -

      An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more -about it in the Activities -developer guide.

      -
      - - -
      Services
      - -
      A service is a component that runs in the background to perform long-running -operations or to perform work for remote processes. A service -does not provide a user interface. For example, a service might play music in the background while -the user is in a different application, or it might fetch data over the network without -blocking user interaction with an activity. Another component, such as an activity, can start the -service and let it run or bind to it in order to interact with it. - -

      A service is implemented as a subclass of {@link android.app.Service} and you can learn more -about it in the Services developer -guide.

      -
      - - -
      Content providers
      - -
      A content provider manages a shared set of application data. You can store the data in -the file system, an SQLite database, on the web, or any other persistent storage location your -application can access. Through the content provider, other applications can query or even modify -the data (if the content provider allows it). For example, the Android system provides a content -provider that manages the user's contact information. As such, any application with the proper -permissions can query part of the content provider (such as {@link -android.provider.ContactsContract.Data}) to read and write information about a particular person. - -

      Content providers are also useful for reading and writing data that is private to your -application and not shared. For example, the Note Pad sample application uses a -content provider to save notes.

      - -

      A content provider is implemented as a subclass of {@link android.content.ContentProvider} -and must implement a standard set of APIs that enable other applications to perform -transactions. For more information, see the Content Providers developer -guide.

      -
      - - -
      Broadcast receivers
      - -
      A broadcast receiver is a component that responds to system-wide broadcast -announcements. Many broadcasts originate from the system—for example, a broadcast announcing -that the screen has turned off, the battery is low, or a picture was captured. -Applications can also initiate broadcasts—for example, to let other applications know that -some data has been downloaded to the device and is available for them to use. Although broadcast -receivers don't display a user interface, they may create a status bar notification -to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is -just a "gateway" to other components and is intended to do a very minimal amount of work. For -instance, it might initiate a service to perform some work based on the event. - -

      A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver} -and each broadcast is delivered as an {@link android.content.Intent} object. For more information, -see the {@link android.content.BroadcastReceiver} class.

      -
      - -
      - - - -

      A unique aspect of the Android system design is that any application can start another -application’s component. For example, if you want the user to capture a -photo with the device camera, there's probably another application that does that and your -application can use it, instead of developing an activity to capture a photo yourself. You don't -need to incorporate or even link to the code from the camera application. -Instead, you can simply start the activity in the camera application that captures a -photo. When complete, the photo is even returned to your application so you can use it. To the user, -it seems as if the camera is actually a part of your application.

      - -

      When the system starts a component, it starts the process for that application (if it's not -already running) and instantiates the classes needed for the component. For example, if your -application starts the activity in the camera application that captures a photo, that activity -runs in the process that belongs to the camera application, not in your application's process. -Therefore, unlike applications on most other systems, Android applications don't have a single entry -point (there's no {@code main()} function, for example).

      - -

      Because the system runs each application in a separate process with file permissions that -restrict access to other applications, your application cannot directly activate a component from -another application. The Android system, however, can. So, to activate a component in -another application, you must deliver a message to the system that specifies your intent to -start a particular component. The system then activates the component for you.

      - - -

      Activating Components

      - -

      Three of the four component types—activities, services, and -broadcast receivers—are activated by an asynchronous message called an intent. -Intents bind individual components to each other at runtime (you can think of them -as the messengers that request an action from other components), whether the component belongs -to your application or another.

      - -

      An intent is created with an {@link android.content.Intent} object, which defines a message to -activate either a specific component or a specific type of component—an intent -can be either explicit or implicit, respectively.

      - -

      For activities and services, an intent defines the action to perform (for example, to "view" or -"send" something) and may specify the URI of the data to act on (among other things that the -component being started might need to know). For example, an intent might convey a request for an -activity to show an image or to open a web page. In some cases, you can start an -activity to receive a result, in which case, the activity also returns -the result in an {@link android.content.Intent} (for example, you can issue an intent to let -the user pick a personal contact and have it returned to you—the return intent includes a -URI pointing to the chosen contact).

      - -

      For broadcast receivers, the intent simply defines the -announcement being broadcast (for example, a broadcast to indicate the device battery is low -includes only a known action string that indicates "battery is low").

      - -

      The other component type, content provider, is not activated by intents. Rather, it is -activated when targeted by a request from a {@link android.content.ContentResolver}. The content -resolver handles all direct transactions with the content provider so that the component that's -performing transactions with the provider doesn't need to and instead calls methods on the {@link -android.content.ContentResolver} object. This leaves a layer of abstraction between the content -provider and the component requesting information (for security).

      - -

      There are separate methods for activating each type of component:

      -
        -
      • 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 -startActivity()} or {@link android.app.Activity#startActivityForResult startActivityForResult()} -(when you want the activity to return a result).
      • -
      • You can start a service (or give new instructions to an ongoing service) by -passing an {@link android.content.Intent} to {@link android.content.Context#startService -startService()}. Or you can bind to the service by passing an {@link android.content.Intent} to -{@link android.content.Context#bindService bindService()}.
      • -
      • You can initiate a broadcast by passing an {@link android.content.Intent} to methods like -{@link android.content.Context#sendBroadcast(Intent) sendBroadcast()}, {@link -android.content.Context#sendOrderedBroadcast(Intent, String) sendOrderedBroadcast()}, or {@link -android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.
      • -
      • You can perform a query to a content provider by calling {@link -android.content.ContentProvider#query query()} on a {@link android.content.ContentResolver}.
      • -
      - -

      For more information about using intents, see the Intents and -Intent Filters document. More information about activating specific components is also provided -in the following documents: Activities, Services, {@link -android.content.BroadcastReceiver} and Content Providers.

      - - -

      The Manifest File

      - -

      Before the Android system can start an application component, the system must know that the -component exists by reading the application's {@code AndroidManifest.xml} file (the "manifest" -file). Your application must declare all its components in this file, which must be at the root of -the application project directory.

      - -

      The manifest does a number of things in addition to declaring the application's components, -such as:

      -
        -
      • Identify any user permissions the application requires, such as Internet access or -read-access to the user's contacts.
      • -
      • Declare the minimum API Level -required by the application, based on which APIs the application uses.
      • -
      • Declare hardware and software features used or required by the application, such as a camera, -bluetooth services, or a multitouch screen.
      • -
      • API libraries the application needs to be linked against (other than the Android framework -APIs), such as the Google Maps -library.
      • -
      • And more
      • -
      - - -

      Declaring components

      - -

      The primary task of the manifest is to inform the system about the application's components. For -example, a manifest file can declare an activity as follows:

      - -
      -<?xml version="1.0" encoding="utf-8"?>
      -<manifest ... >
      -    <application android:icon="@drawable/app_icon.png" ... >
      -        <activity android:name="com.example.project.ExampleActivity"
      -                  android:label="@string/example_label" ... >
      -        </activity>
      -        ...
      -    </application>
      -</manifest>
      - -

      In the <application> -element, the {@code android:icon} attribute points to resources for an icon that identifies the -application.

      - -

      In the <activity> element, -the {@code android:name} attribute specifies the fully qualified class name of the {@link -android.app.Activity} subclass and the {@code android:label} attributes specifies a string -to use as the user-visible label for the activity.

      - -

      You must declare all application components this way:

      - - -

      Activities, services, and content providers that you include in your source but do not declare -in the manifest are not visible to the system and, consequently, can never run. However, -broadcast -receivers can be either declared in the manifest or created dynamically in code (as -{@link android.content.BroadcastReceiver} objects) and registered with the system by calling -{@link android.content.Context#registerReceiver registerReceiver()}.

      - -

      For more about how to structure the manifest file for your application, see the The AndroidManifest.xml File -documentation.

      - - - -

      Declaring component capabilities

      - -

      As discussed above, in Activating Components, you can use an -{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so -by explicitly naming the target component (using the component class name) in the intent. However, -the real power of intents lies in the concept of intent actions. With intent actions, you simply -describe the type of action you want to perform (and optionally, the data upon which you’d like to -perform the action) and allow the system to find a component on the device that can perform the -action and start it. If there are multiple components that can perform the action described by the -intent, then the user selects which one to use.

      - -

      The way the system identifies the components that can respond to an intent is by comparing the -intent received to the intent filters provided in the manifest file of other applications on -the device.

      - -

      When you declare a component in your application's manifest, you can optionally include -intent filters that declare the capabilities of the component so it can respond to intents -from other applications. You can declare an intent filter for your component by -adding an {@code -<intent-filter>} element as a child of the component's declaration element.

      - -

      For example, an email application with an activity for composing a new email might declare an -intent filter in its manifest entry to respond to "send" intents (in order to send email). An -activity in your application can then create an intent with the “send” action ({@link -android.content.Intent#ACTION_SEND}), which the system matches to the email application’s “send” -activity and launches it when you invoke the intent with {@link android.app.Activity#startActivity -startActivity()}.

      - -

      For more about creating intent filters, see the Intents and Intent Filters document. -

      - - - -

      Declaring application requirements

      - -

      There are a variety of devices powered by Android and not all of them provide the -same features and capabilities. In order to prevent your application from being installed on devices -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 Google Play do read them in order to provide filtering -for users when they search for applications from their device.

      - -

      For example, if your application requires a camera and uses APIs introduced in Android 2.1 (API Level 7), you should declare these as -requirements in your manifest file. That way, devices that do not have a camera and have an -Android version lower than 2.1 cannot install your application from Google Play.

      - -

      However, you can also declare that your application uses the camera, but does not -require 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.

      - -

      Here are some of the important device characteristics that you should consider as you design and -develop your application:

      - -
      -
      Screen size and density
      -
      In order to categorize devices by their screen type, Android defines two characteristics for -each device: screen size (the physical dimensions of the screen) and screen density (the physical -density of the pixels on the screen, or dpi—dots per inch). To simplify all the different -types of screen configurations, the Android system generalizes them into select groups that make -them easier to target. -

      The screen sizes are: small, normal, large, and extra large.
      -The screen densities are: low density, medium density, high density, and extra high density.

      - -

      By default, your application is compatible with all screen sizes and densities, -because the Android system makes the appropriate adjustments to your UI layout and image -resources. However, you should create specialized layouts for certain screen sizes and provide -specialized images for certain densities, using alternative layout resources, and by declaring in -your manifest exactly which screen sizes your application supports with the {@code -<supports-screens>} element.

      -

      For more information, see the Supporting Multiple Screens -document.

      - -
      Input configurations
      -
      Many devices provide a different type of user input mechanism, such as a hardware keyboard, a -trackball, or a five-way navigation pad. If your application requires a particular kind of input -hardware, then you should declare it in your manifest with the {@code -<uses-configuration>} element. However, it is rare that an application should require -a certain input configuration.
      - -
      Device features
      -
      There are many hardware and software features that may or may not exist on a given -Android-powered device, such as a camera, a light sensor, bluetooth, a certain -version of OpenGL, or the fidelity of the touchscreen. You should never assume that a certain -feature is available on all Android-powered devices (other than the availability of the standard -Android library), so you should declare any features used by your application with the {@code <uses-feature>} -element.
      - -
      Platform Version
      -
      Different Android-powered devices often run different versions of the Android platform, -such as Android 1.6 or Android 2.3. Each successive version often includes additional APIs not -available in the previous version. In order to indicate which set of APIs are available, each -platform version specifies an API Level (for example, Android 1.0 is API Level -1 and Android 2.3 is API Level 9). If you use any APIs that were added to the platform after -version 1.0, you should declare the minimum API Level in which those APIs were introduced using the -{@code <uses-sdk>} -element.
      -
      - -

      It's important that you declare all such requirements for your application, because, when you -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.

      - -

      For more information about how Google Play filters applications based on these (and other) -requirements, see the Filters on Google Play -document.

      - - - -

      Application Resources

      - -

      An Android application is composed of more than just code—it requires resources that are -separate from the source code, such as images, audio files, and anything relating to the visual -presentation of the application. For example, you should define animations, menus, styles, colors, -and the layout of activity user interfaces with XML files. Using application resources makes it easy -to update various characteristics of your application without modifying code and—by providing -sets of alternative resources—enables you to optimize your application for a variety of -device configurations (such as different languages and screen sizes).

      - -

      For every resource that you include in your Android project, the SDK build tools define a unique -integer ID, which you can use to reference the resource from your application code or from -other resources defined in XML. For example, if your application contains an image file named {@code -logo.png} (saved in the {@code res/drawable/} directory), the SDK tools generate a resource ID -named {@code R.drawable.logo}, which you can use to reference the image and insert it in your -user interface.

      - -

      One of the most important aspects of providing resources separate from your source code -is the ability for you to provide alternative resources for different device -configurations. For example, by defining UI strings in XML, you can translate the strings into other -languages and save those strings in separate files. Then, based on a language qualifier -that you append to the resource directory's name (such as {@code res/values-fr/} for French string -values) and the user's language setting, the Android system applies the appropriate language strings -to your UI.

      - -

      Android supports many different qualifiers for your alternative resources. The -qualifier is a short string that you include in the name of your resource directories in order to -define the device configuration for which those resources should be used. As another -example, you should often create different layouts for your activities, depending on the -device's screen orientation and size. For example, when the device screen is in portrait -orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in -landscape orientation (wide), the buttons should be aligned horizontally. To change the layout -depending on the orientation, you can define two different layouts and apply the appropriate -qualifier to each layout's directory name. Then, the system automatically applies the appropriate -layout depending on the current device orientation.

      - -

      For more about the different kinds of resources you can include in your application and how -to create alternative resources for various device configurations, see the Application Resources developer guide.

      - - - diff --git a/docs/html/guide/topics/fundamentals/activities.jd b/docs/html/guide/topics/fundamentals/activities.jd deleted file mode 100644 index b79136cbb8c0..000000000000 --- a/docs/html/guide/topics/fundamentals/activities.jd +++ /dev/null @@ -1,777 +0,0 @@ -page.title=Activities -@jd:body - -
      -
      -

      Quickview

      -
        -
      • An activity provides a user interface for a single screen in your application
      • -
      • Activities can move into the background and then be resumed with their state restored
      • -
      - -

      In this document

      -
        -
      1. Creating an Activity -
          -
        1. Implementing a user interface
        2. -
        3. Declaring the activity in the manifest
        4. -
        -
      2. -
      3. Starting an Activity -
          -
        1. Starting an activity for a result
        2. -
        -
      4. -
      5. Shutting Down an Activity
      6. -
      7. Managing the Activity Lifecycle -
          -
        1. Implementing the lifecycle callbacks
        2. -
        3. Saving activity state
        4. -
        5. Handling configuration changes
        6. -
        7. Coordinating activities
        8. -
        -
      8. -
      - -

      Key classes

      -
        -
      1. {@link android.app.Activity}
      2. -
      - -

      See also

      -
        -
      1. Hello World Tutorial
      2. -
      3. Tasks and Back -Stack
      4. -
      - -
      -
      - - - -

      An {@link android.app.Activity} is an application component that provides a screen with which -users can interact in order to do something, such as dial the phone, take a photo, send an email, or -view a map. Each activity is given a window in which to draw its user interface. The window -typically fills the screen, but may be smaller than the screen and float on top of other -windows.

      - -

      An application usually consists of multiple activities that are loosely bound -to each other. Typically, one activity in an application is specified as the "main" activity, which -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" stack mechanism, -so, when the user is done with the current activity and presses the Back button, it -is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is -discussed more in the Tasks -and Back Stack document.)

      - -

      When an activity is stopped because a new activity starts, it is notified of this change in state -through the activity's lifecycle callback methods. -There are several callback methods that an activity might receive, due to a change in its -state—whether the system is creating it, stopping it, resuming it, or destroying it—and -each callback provides you the opportunity to perform specific work that's -appropriate to that state change. For instance, when stopped, your activity should release any -large objects, such as network or database connections. When the activity resumes, you can -reacquire the necessary resources and resume actions that were interrupted. These state transitions -are all part of the activity lifecycle.

      - -

      The rest of this document discusses the basics of how to build and use an activity, -including a complete discussion of how the activity lifecycle works, so you can properly manage -the transition between various activity states.

      - - - -

      Creating an Activity

      - -

      To create an activity, you must create a subclass of {@link android.app.Activity} (or -an existing subclass of it). In your subclass, you need to implement callback methods that the -system calls when the activity transitions between various states of its lifecycle, such as when -the activity is being created, stopped, resumed, or destroyed. The two most important callback -methods are:

      - -
      -
      {@link android.app.Activity#onCreate onCreate()}
      -
      You must implement this method. The system calls this when creating your - activity. Within your implementation, you should initialize the essential components of your -activity. - Most importantly, this is where you must call {@link android.app.Activity#setContentView - setContentView()} to define the layout for the activity's user interface.
      -
      {@link android.app.Activity#onPause onPause()}
      -
      The system calls this method as the first indication that the user is leaving your -activity (though it does not always mean the activity is being destroyed). This is usually where you -should commit any changes that should be persisted beyond the current user session (because -the user might not come back).
      -
      - -

      There are several other lifecycle callback methods that you should use in order to provide a -fluid user experience between activities and handle unexpected interuptions that cause your activity -to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in -the section about Managing the Activity Lifecycle.

      - - - -

      Implementing a user interface

      - -

      The user interface for an activity is provided by a hierarchy of views—objects derived -from the {@link android.view.View} class. Each view controls a particular rectangular space -within the activity's window and can respond to user interaction. For example, a view might be a -button that initiates an action when the user touches it.

      - -

      Android provides a number of ready-made views that you can use to design and organize your -layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such -as a button, text field, checkbox, or just an image. "Layouts" are views derived from {@link -android.view.ViewGroup} that provide a unique layout model for its child views, such as a linear -layout, a grid layout, or relative layout. You can also subclass the {@link android.view.View} and -{@link android.view.ViewGroup} classes (or existing subclasses) to create your own widgets and -layouts and apply them to your activity layout.

      - -

      The most common way to define a layout using views is with an XML layout file saved in your -application resources. This way, you can maintain the design of your user interface separately from -the source code that defines the activity's behavior. You can set the layout as the UI for your -activity with {@link android.app.Activity#setContentView(int) setContentView()}, passing the -resource ID for the layout. However, you can also create new {@link android.view.View}s in your -activity code and build a view hierarchy by inserting new {@link -android.view.View}s into a {@link android.view.ViewGroup}, then use that layout by passing the root -{@link android.view.ViewGroup} to {@link android.app.Activity#setContentView(View) -setContentView()}.

      - -

      For information about creating a user interface, see the User Interface documentation.

      - - - -

      Declaring the activity in the manifest

      - -

      You must declare your activity in the manifest file in order for it to -be accessible to the system. To declare your activity, open your manifest file and add an {@code <activity>} element -as a child of the {@code <application>} -element. For example:

      - -
      -<manifest ... >
      -  <application ... >
      -      <activity android:name=".ExampleActivity" />
      -      ...
      -  </application ... >
      -  ...
      -</manifest >
      -
      - -

      There are several other attributes that you can include in this element, to define properties -such as the label for the activity, an icon for the activity, or a theme to style the activity's -UI. The {@code android:name} -attribute is the only required attribute—it specifies the class name of the activity. Once -you publish your application, you should not change this name, because if you do, you might break -some functionality, such as application shortcuts (read the blog post, Things -That Cannot Change).

      - -

      See the {@code <activity>} element -reference for more information about declaring your activity in the manifest.

      - - -

      Using intent filters

      - -

      An {@code -<activity>} element can also specify various intent filters—using the {@code -<intent-filter>} element—in order to declare how other application components may -activate it.

      - -

      When you create a new application using the Android SDK tools, the stub activity -that's created for you automatically includes an intent filter that declares the activity -responds to the "main" action and should be placed in the "launcher" category. The intent filter -looks like this:

      - -
      -<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
      -    <intent-filter>
      -        <action android:name="android.intent.action.MAIN" />
      -        <category android:name="android.intent.category.LAUNCHER" />
      -    </intent-filter>
      -</activity>
      -
      - -

      The {@code -<action>} element specifies that this is the "main" entry point to the application. The {@code -<category>} element specifies that this activity should be listed in the -system's application launcher (to allow users to launch this activity).

      - -

      If you intend for your application to be self-contained and not allow other applications to -activate its activities, then you don't need any other intent filters. Only one activity should -have the "main" action and "launcher" category, as in the previous example. Activities that -you don't want to make available to other applications should have no intent filters and you can -start them yourself using explicit intents (as discussed in the following section).

      - -

      However, if you want your activity to respond to implicit intents that are delivered from -other applications (and your own), then you must define additional intent filters for your -activity. For each type of intent to which you want to respond, you must include an {@code -<intent-filter>} that includes an -{@code -<action>} element and, optionally, a {@code -<category>} element and/or a {@code -<data>} element. These elements specify the type of intent to which your activity can -respond.

      - -

      For more information about how your activities can respond to intents, see the Intents and Intent Filters -document.

      - - - -

      Starting an Activity

      - -

      You can start another activity by calling {@link android.app.Activity#startActivity - startActivity()}, passing it an {@link android.content.Intent} that describes the activity you - want to start. The intent specifies either the exact activity you want to start or describes the - type of action you want to perform (and the system selects the appropriate activity for you, -which - can even be from a different application). An intent can also carry small amounts of data to be - used by the activity that is started.

      - -

      When working within your own application, you'll often need to simply launch a known activity. - You can do so by creating an intent that explicitly defines the activity you want to start, -using the class name. For example, here's how one activity starts another activity named {@code -SignInActivity}:

      - -
      -Intent intent = new Intent(this, SignInActivity.class);
      -startActivity(intent);
      -
      - -

      However, your application might also want to perform some action, such as send an email, text - message, or status update, using data from your activity. In this case, your application might - not have its own activities to perform such actions, so you can instead leverage the activities - provided by other applications on the device, which can perform the actions for you. This is where -intents are really valuable—you can create an intent that describes an action you want to -perform and the system - launches the appropriate activity from another application. If there are - multiple activities that can handle the intent, then the user can select which one to use. For - example, if you want to allow the user to send an email message, you can create the - following intent:

      - -
      -Intent intent = new Intent(Intent.ACTION_SEND);
      -intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
      -startActivity(intent);
      -
      - -

      The {@link android.content.Intent#EXTRA_EMAIL} extra added to the intent is a string array of - email addresses to which the email should be sent. When an email application responds to this - intent, it reads the string array provided in the extra and places them in the "to" field of the - email composition form. In this situation, the email application's activity starts and when the - user is done, your activity resumes.

      - - - - -

      Starting an activity for a result

      - -

      Sometimes, you might want to receive a result from the activity that you start. In that case, - start the activity by calling {@link android.app.Activity#startActivityForResult - startActivityForResult()} (instead of {@link android.app.Activity#startActivity - startActivity()}). To then receive the result from the subsequent -activity, implement the {@link android.app.Activity#onActivityResult onActivityResult()} callback - method. When the subsequent activity is done, it returns a result in an {@link -android.content.Intent} to your {@link android.app.Activity#onActivityResult onActivityResult()} -method.

      - -

      For example, perhaps you want the user to pick one of their contacts, so your activity can -do something with the information in that contact. Here's how you can create such an intent and -handle the result:

      - -
      -private void pickContact() {
      -    // Create an intent to "pick" a contact, as defined by the content provider URI
      -    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
      -    startActivityForResult(intent, PICK_CONTACT_REQUEST);
      -}
      -
      -@Override
      -protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      -    // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
      -    if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
      -        // Perform a query to the contact's content provider for the contact's name
      -        Cursor cursor = getContentResolver().query(data.getData(),
      -        new String[] {Contacts.DISPLAY_NAME}, null, null, null);
      -        if (cursor.moveToFirst()) { // True if the cursor is not empty
      -            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
      -            String name = cursor.getString(columnIndex);
      -            // Do something with the selected contact's name...
      -        }
      -    }
      -}
      -
      - -

      This example shows the basic logic you should use in your {@link -android.app.Activity#onActivityResult onActivityResult()} method in order to handle an -activity result. The first condition checks whether the request was successful—if it was, then -the {@code resultCode} will be {@link android.app.Activity#RESULT_OK}—and whether the request -to which this result is responding is known—in this case, the {@code requestCode} matches the -second parameter sent with {@link android.app.Activity#startActivityForResult -startActivityForResult()}. From there, the code handles the activity result by querying the -data returned in an {@link android.content.Intent} (the {@code data} parameter).

      - -

      What happens is, a {@link -android.content.ContentResolver} performs a query against a content provider, which returns a -{@link android.database.Cursor} that allows the queried data to be read. For more information, see -the Content Providers document.

      - -

      For more information about using intents, see the Intents and Intent -Filters document.

      - - -

      Shutting Down an Activity

      - -

      You can shut down an activity by calling its {@link android.app.Activity#finish -finish()} method. You can also shut down a separate activity that you previously started by calling -{@link android.app.Activity#finishActivity finishActivity()}.

      - -

      Note: In most cases, you should not explicitly finish an activity -using these methods. As discussed in the following section about the activity lifecycle, the -Android system manages the life of an activity for you, so you do not need to finish your own -activities. Calling these methods could adversely affect the expected user -experience and should only be used when you absolutely do not want the user to return to this -instance of the activity.

      - - -

      Managing the Activity Lifecycle

      - -

      Managing the lifecycle of your activities by implementing callback methods is -crucial to developing a strong -and flexible application. The lifecycle of an activity is directly affected by its association with -other activities, its task and back stack.

      - -

      An activity can exist in essentially three states:

      - -
      -
      Resumed
      -
      The activity is in the foreground of the screen and has user focus. (This state is -also sometimes referred to as "running".)
      - -
      Paused
      -
      Another activity is in the foreground and has focus, but this one is still visible. That is, -another activity is visible on top of this one and that activity is partially transparent or doesn't -cover the entire screen. A paused activity is completely alive (the {@link android.app.Activity} -object is retained in memory, it maintains all state and member information, and remains attached to -the window manager), but can be killed by the system in extremely low memory situations.
      - -
      Stopped
      -
      The activity is completely obscured by another activity (the activity is now in the -"background"). A stopped activity is also still alive (the {@link android.app.Activity} -object is retained in memory, it maintains all state and member information, but is not -attached to the window manager). However, it is no longer visible to the user and it -can be killed by the system when memory is needed elsewhere.
      -
      - -

      If an activity is paused or stopped, the system can drop it from memory either by asking it to -finish (calling its {@link android.app.Activity#finish finish()} method), or simply killing its -process. When the activity is opened again (after being finished or killed), it must be created all -over.

      - - - -

      Implementing the lifecycle callbacks

      - -

      When an activity transitions into and out of the different states described above, it is notified -through various callback methods. All of the callback methods are hooks that you -can override to do appropriate work when the state of your activity changes. The following skeleton -activity includes each of the fundamental lifecycle methods:

      - - -
      -public class ExampleActivity extends Activity {
      -    @Override
      -    public void {@link android.app.Activity#onCreate onCreate}(Bundle savedInstanceState) {
      -        super.onCreate(savedInstanceState);
      -        // The activity is being created.
      -    }
      -    @Override
      -    protected void {@link android.app.Activity#onStart onStart()} {
      -        super.onStart();
      -        // The activity is about to become visible.
      -    }
      -    @Override
      -    protected void {@link android.app.Activity#onResume onResume()} {
      -        super.onResume();
      -        // The activity has become visible (it is now "resumed").
      -    }
      -    @Override
      -    protected void {@link android.app.Activity#onPause onPause()} {
      -        super.onPause();
      -        // Another activity is taking focus (this activity is about to be "paused").
      -    }
      -    @Override
      -    protected void {@link android.app.Activity#onStop onStop()} {
      -        super.onStop();
      -        // The activity is no longer visible (it is now "stopped")
      -    }
      -    @Override
      -    protected void {@link android.app.Activity#onDestroy onDestroy()} {
      -        super.onDestroy();
      -        // The activity is about to be destroyed.
      -    }
      -}
      -
      - -

      Note: Your implementation of these lifecycle methods must -always call the superclass implementation before doing any work, as shown in the examples above.

      - -

      Taken together, these methods define the entire lifecycle of an activity. By implementing these -methods, you can monitor three nested loops in the activity lifecycle:

      - -
        -
      • The entire lifetime of an activity happens between the call to {@link -android.app.Activity#onCreate onCreate()} and the call to {@link -android.app.Activity#onDestroy}. Your activity should perform setup of -"global" state (such as defining layout) in {@link android.app.Activity#onCreate onCreate()}, and -release all remaining resources in {@link android.app.Activity#onDestroy}. For example, if your -activity has a thread running in the background to download data from the network, it might create -that thread in {@link android.app.Activity#onCreate onCreate()} and then stop the thread in {@link -android.app.Activity#onDestroy}.
      • - -
      • The visible lifetime of an activity happens between the call to {@link -android.app.Activity#onStart onStart()} and the call to {@link -android.app.Activity#onStop onStop()}. During this time, the user can see the activity -on-screen and interact with it. For example, {@link android.app.Activity#onStop onStop()} is called -when a new activity starts and this one is no longer visible. Between these two methods, you can -maintain resources that are needed to show the activity to the user. For example, you can register a -{@link android.content.BroadcastReceiver} in {@link -android.app.Activity#onStart onStart()} to monitor changes that impact your UI, and unregister -it in {@link android.app.Activity#onStop onStop()} when the user can no longer see what you are -displaying. The system might call {@link android.app.Activity#onStart onStart()} and {@link -android.app.Activity#onStop onStop()} multiple times during the entire lifetime of the activity, as -the activity alternates between being visible and hidden to the user.

      • - -
      • The foreground lifetime of an activity happens between the call to {@link -android.app.Activity#onResume onResume()} and the call to {@link android.app.Activity#onPause -onPause()}. During this time, the activity is in front of all other activities on screen and has -user input focus. An activity can frequently transition in and out of the foreground—for -example, {@link android.app.Activity#onPause onPause()} is called when the device goes to sleep or -when a dialog appears. Because this state can transition often, the code in these two methods should -be fairly lightweight in order to avoid slow transitions that make the user wait.

      • -
      - -

      Figure 1 illustrates these loops and the paths an activity might take between states. -The rectangles represent the callback methods you can implement to perform operations when -the activity transitions between states.

      - - -

      Figure 1. The activity lifecycle.

      - -

      The same lifecycle callback methods are listed in table 1, which describes each of the callback -methods in more detail and locates each one within the -activity's overall lifecycle, including whether the system can kill the activity after the -callback method completes.

      - -

      Table 1. A summary of the activity lifecycle's -callback methods.

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Method Description Killable after? Next
      {@link android.app.Activity#onCreate onCreate()}Called when the activity is first created. - This is where you should do all of your normal static set up — - create views, bind data to lists, and so on. This method is passed - a Bundle object containing the activity's previous state, if that - state was captured (see Saving Activity State, - later). -

      Always followed by {@code onStart()}.

      No{@code onStart()}
          {@link android.app.Activity#onRestart -onRestart()}Called after the activity has been stopped, just prior to it being - started again. -

      Always followed by {@code onStart()}

      No{@code onStart()}
      {@link android.app.Activity#onStart onStart()}Called just before the activity becomes visible to the user. -

      Followed by {@code onResume()} if the activity comes - to the foreground, or {@code onStop()} if it becomes hidden.

      No{@code onResume()}
      or
      {@code onStop()}
          {@link android.app.Activity#onResume onResume()}Called just before the activity starts - interacting with the user. At this point the activity is at - the top of the activity stack, with user input going to it. -

      Always followed by {@code onPause()}.

      No{@code onPause()}
      {@link android.app.Activity#onPause onPause()}Called when the system is about to start resuming another - activity. This method is typically used to commit unsaved changes to - persistent data, stop animations and other things that may be consuming - CPU, and so on. It should do whatever it does very quickly, because - the next activity will not be resumed until it returns. -

      Followed either by {@code onResume()} if the activity - returns back to the front, or by {@code onStop()} if it becomes - invisible to the user.

      Yes{@code onResume()}
      or
      {@code onStop()}
      {@link android.app.Activity#onStop onStop()}Called when the activity is no longer visible to the user. This - may happen because it is being destroyed, or because another activity - (either an existing one or a new one) has been resumed and is covering it. -

      Followed either by {@code onRestart()} if - the activity is coming back to interact with the user, or by - {@code onDestroy()} if this activity is going away.

      Yes{@code onRestart()}
      or
      {@code onDestroy()}
      {@link android.app.Activity#onDestroy -onDestroy()}Called before the activity is destroyed. This is the final call - that the activity will receive. It could be called either because the - activity is finishing (someone called {@link android.app.Activity#finish - finish()} on it), or because the system is temporarily destroying this - instance of the activity to save space. You can distinguish - between these two scenarios with the {@link - android.app.Activity#isFinishing isFinishing()} method.Yesnothing
      - -

      The column labeled "Killable after?" indicates whether or not the system can -kill the process hosting the activity at any time after the method returns, without -executing another line of the activity's code. Three methods are marked "yes": ({@link -android.app.Activity#onPause -onPause()}, {@link android.app.Activity#onStop onStop()}, and {@link android.app.Activity#onDestroy -onDestroy()}). Because {@link android.app.Activity#onPause onPause()} is the first -of the three, once the activity is created, {@link android.app.Activity#onPause onPause()} is the -last method that's guaranteed to be called before the process can be killed—if -the system must recover memory in an emergency, then {@link -android.app.Activity#onStop onStop()} and {@link android.app.Activity#onDestroy onDestroy()} might -not be called. Therefore, you should use {@link android.app.Activity#onPause onPause()} to write -crucial persistent data (such as user edits) to storage. However, you should be selective about -what information must be retained during {@link android.app.Activity#onPause onPause()}, because any -blocking procedures in this method block the transition to the next activity and slow the user -experience.

      - -

      Methods that are marked "No" in the Killable column protect the process hosting the -activity from being killed from the moment they are called. Thus, an activity is killable -from the time {@link android.app.Activity#onPause onPause()} returns to the time -{@link android.app.Activity#onResume onResume()} is called. It will not again be killable until -{@link android.app.Activity#onPause onPause()} is again called and returns.

      - -

      Note: An activity that's not technically "killable" by this -definition in table 1 might still be killed by the system—but that would happen only in -extreme circumstances when there is no other recourse. When an activity might be killed is -discussed more in the Processes and -Threading document.

      - - -

      Saving activity state

      - -

      The introduction to Managing the Activity Lifecycle briefly mentions -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 so that when the activity returns to the -foreground (when it "resumes"), those changes are still there.

      - -

      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 -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: {@link -android.app.Activity#onSaveInstanceState onSaveInstanceState()}.

      - -

      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()} 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).

      - - -

      Figure 2. 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.

      - -

      Note: 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 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()}.

      - -

      However, even if you do nothing and do not implement {@link -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 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 {@code android:id} -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.

      - - - -

      Although the default implementation of {@link -android.app.Activity#onSaveInstanceState onSaveInstanceState()} saves useful information about -your activity's UI, you still might need to override it to save additional information. -For example, you might need to save member values that changed during the activity's life (which -might correlate to values restored in the UI, but the members that hold those UI values are not -restored, by default).

      - -

      Because the default implementation of {@link -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. 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.

      - -

      Note: Because {@link android.app.Activity#onSaveInstanceState -onSaveInstanceState()} is not guaranteed -to be called, you should use it only to record the transient state of the activity (the state of -the UI)—you should never use it to store persistent data. Instead, you should use {@link -android.app.Activity#onPause onPause()} to store persistent data (such as data that should be saved -to a database) when the user leaves the activity.

      - -

      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 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.

      - - -

      Handling configuration changes

      - -

      Some device configurations can change during runtime (such as screen orientation, keyboard -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 (such as different layouts for -different screen orientations and sizes).

      - -

      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.

      - -

      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.

      - -

      For more information about configuration changes that happen at runtime and how you can handle -them, read the guide to Handling -Runtime Changes.

      - - - -

      Coordinating activities

      - -

      When one activity starts another, they both experience lifecycle transitions. The first activity -pauses and stops (though, it won't stop if it's still visible in the background), while the other -activity is created. In case these activities share data saved to disc or elsewhere, it's important -to understand that the first activity is not completely stopped before the second one is created. -Rather, the process of starting the second one overlaps with the process of stopping the first -one.

      - -

      The order of lifecycle callbacks is well defined, particularly when the two activities are in the -same process and one is starting the other. Here's the order of operations that occur when Activity -A starts Acivity B:

      - -
        -
      1. Activity A's {@link android.app.Activity#onPause onPause()} method executes.
      2. - -
      3. Activity B's {@link android.app.Activity#onCreate onCreate()}, {@link -android.app.Activity#onStart onStart()}, and {@link android.app.Activity#onResume onResume()} -methods execute in sequence. (Activity B now has user focus.)
      4. - -
      5. Then, if Activity A is no longer visible on screen, its {@link -android.app.Activity#onStop onStop()} method executes.
      6. -
      - -

      This predictable sequence of lifecycle callbacks allows you to manage the transition of -information from one activity to another. For example, if you must write to a database when the -first activity stops so that the following activity can read it, then you should write to the -database during {@link android.app.Activity#onPause onPause()} instead of during {@link -android.app.Activity#onStop onStop()}.

      - - \ No newline at end of file diff --git a/docs/html/guide/topics/fundamentals/bound-services.jd b/docs/html/guide/topics/fundamentals/bound-services.jd deleted file mode 100644 index ec7d7230d90e..000000000000 --- a/docs/html/guide/topics/fundamentals/bound-services.jd +++ /dev/null @@ -1,675 +0,0 @@ -page.title=Bound Services -parent.title=Services -parent.link=services.html -@jd:body - - -
      -
        -

        Quickview

        -
          -
        • A bound service allows other components to bind to it, in order to interact with it and -perform interprocess communication
        • -
        • A bound service is destroyed once all clients unbind, unless the service was also started
        • -
        -

        In this document

        -
          -
        1. The Basics
        2. -
        3. Creating a Bound Service -
            -
          1. Extending the Binder class
          2. -
          3. Using a Messenger
          4. -
          -
        4. -
        5. Binding to a Service
        6. -
        7. Managing the Lifecycle of a Bound Service
        8. -
        - -

        Key classes

        -
          -
        1. {@link android.app.Service}
        2. -
        3. {@link android.content.ServiceConnection}
        4. -
        5. {@link android.os.IBinder}
        6. -
        - -

        Samples

        -
          -
        1. {@code - RemoteService}
        2. -
        3. {@code - LocalService}
        4. -
        - -

        See also

        -
          -
        1. Services
        2. -
        -
      - - -

      A bound service is the server in a client-server interface. A bound service allows components -(such as activities) to bind to the service, send requests, receive responses, and even perform -interprocess communication (IPC). A bound service typically lives only while it serves another -application component and does not run in the background indefinitely.

      - -

      This document shows you how to create a bound service, including how to bind -to the service from other application components. However, you should also refer to the Services document for additional -information about services in general, such as how to deliver notifications from a service, set -the service to run in the foreground, and more.

      - - -

      The Basics

      - -

      A bound service is an implementation of the {@link android.app.Service} class that allows -other applications to bind to it and interact with it. To provide binding for a -service, you must implement the {@link android.app.Service#onBind onBind()} callback method. This -method returns an {@link android.os.IBinder} object that defines the programming interface that -clients can use to interact with the service.

      - - - -

      A client can bind to the service by calling {@link android.content.Context#bindService -bindService()}. When it does, it must provide an implementation of {@link -android.content.ServiceConnection}, which monitors the connection with the service. The {@link -android.content.Context#bindService bindService()} method returns immediately without a value, but -when the Android system creates the connection between the -client and service, it calls {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link -android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that -the client can use to communicate with the service.

      - -

      Multiple clients can connect to the service at once. However, the system calls your service's -{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only -when the first client binds. The system then delivers the same {@link android.os.IBinder} to any -additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.

      - -

      When the last client unbinds from the service, the system destroys the service (unless the -service was also started by {@link android.content.Context#startService startService()}).

      - -

      When you implement your bound service, the most important part is defining the interface -that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few -different ways you can define your service's {@link android.os.IBinder} interface and the following -section discusses each technique.

      - - - -

      Creating a Bound Service

      - -

      When creating a service that provides binding, you must provide an {@link android.os.IBinder} -that provides the programming interface that clients can use to interact with the service. There -are three ways you can define the interface:

      - -
      -
      Extending the Binder class
      -
      If your service is private to your own application and runs in the same process as the client -(which is common), you should create your interface by extending the {@link android.os.Binder} class -and returning an instance of it from -{@link android.app.Service#onBind onBind()}. The client receives the {@link android.os.Binder} and -can use it to directly access public methods available in either the {@link android.os.Binder} -implementation or even the {@link android.app.Service}. -

      This is the preferred technique when your service is merely a background worker for your own -application. The only reason you would not create your interface this way is because -your service is used by other applications or across separate processes.

      - -
      Using a Messenger
      -
      If you need your interface to work across different processes, you can create -an interface for the service with a {@link android.os.Messenger}. In this manner, the service -defines a {@link android.os.Handler} that responds to different types of {@link -android.os.Message} objects. This {@link android.os.Handler} -is the basis for a {@link android.os.Messenger} that can then share an {@link android.os.IBinder} -with the client, allowing the client to send commands to the service using {@link -android.os.Message} objects. Additionally, the client can define a {@link android.os.Messenger} of -its own so the service can send messages back. -

      This is the simplest way to perform interprocess communication (IPC), because the {@link -android.os.Messenger} queues all requests into a single thread so that you don't have to design -your service to be thread-safe.

      -
      - -
      Using AIDL
      -
      AIDL (Android Interface Definition Language) performs all the work to decompose objects into -primitives that the operating system can understand and marshall them across processes to perform -IPC. The previous technique, using a {@link android.os.Messenger}, is actually based on AIDL as -its underlying structure. As mentioned above, the {@link android.os.Messenger} creates a queue of -all the client requests in a single thread, so the service receives requests one at a time. If, -however, you want your service to handle multiple requests simultaneously, then you can use AIDL -directly. In this case, your service must be capable of multi-threading and be built thread-safe. -

      To use AIDL directly, you must -create an {@code .aidl} file that defines the programming interface. The Android SDK tools use -this file to generate an abstract class that implements the interface and handles IPC, which you -can then extend within your service.

      -
      -
      - -

      Note: Most applications should not use AIDL to -create a bound service, because it may require multithreading capabilities and -can result in a more complicated implementation. As such, AIDL is not suitable for most applications -and this document does not discuss how to use it for your service. If you're certain that you need -to use AIDL directly, see the AIDL -document.

      - - - - -

      Extending the Binder class

      - -

      If your service is used only by the local application and does not need to work across processes, -then you can implement your own {@link android.os.Binder} class that provides your client direct -access to public methods in the service.

      - -

      Note: This works only if the client and service are in the same -application and process, which is most common. For example, this would work well for a music -application that needs to bind an activity to its own service that's playing music in the -background.

      - -

      Here's how to set it up:

      -
        -
      1. In your service, create an instance of {@link android.os.Binder} that either: -
          -
        • contains public methods that the client can call
        • -
        • returns the current {@link android.app.Service} instance, which has public methods the -client can call
        • -
        • or, returns an instance of another class hosted by the service with public methods the -client can call
        • -
        -
      2. Return this instance of {@link android.os.Binder} from the {@link -android.app.Service#onBind onBind()} callback method.
      3. -
      4. In the client, receive the {@link android.os.Binder} from the {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method and -make calls to the bound service using the methods provided.
      5. -
      - -

      Note: The reason the service and client must be in the same -application is so the client can cast the returned object and properly call its APIs. The service -and client must also be in the same process, because this technique does not perform any -marshalling across processes.

      - -

      For example, here's a service that provides clients access to methods in the service through -a {@link android.os.Binder} implementation:

      - -
      -public class LocalService extends Service {
      -    // Binder given to clients
      -    private final IBinder mBinder = new LocalBinder();
      -    // Random number generator
      -    private final Random mGenerator = new Random();
      -
      -    /**
      -     * Class used for the client Binder.  Because we know this service always
      -     * runs in the same process as its clients, we don't need to deal with IPC.
      -     */
      -    public class LocalBinder extends Binder {
      -        LocalService getService() {
      -            // Return this instance of LocalService so clients can call public methods
      -            return LocalService.this;
      -        }
      -    }
      -
      -    @Override
      -    public IBinder onBind(Intent intent) {
      -        return mBinder;
      -    }
      -
      -    /** method for clients */
      -    public int getRandomNumber() {
      -      return mGenerator.nextInt(100);
      -    }
      -}
      -
      - -

      The {@code LocalBinder} provides the {@code getService()} method for clients to retrieve the -current instance of {@code LocalService}. This allows clients to call public methods in the -service. For example, clients can call {@code getRandomNumber()} from the service.

      - -

      Here's an activity that binds to {@code LocalService} and calls {@code getRandomNumber()} -when a button is clicked:

      - -
      -public class BindingActivity extends Activity {
      -    LocalService mService;
      -    boolean mBound = false;
      -
      -    @Override
      -    protected void onCreate(Bundle savedInstanceState) {
      -        super.onCreate(savedInstanceState);
      -        setContentView(R.layout.main);
      -    }
      -
      -    @Override
      -    protected void onStart() {
      -        super.onStart();
      -        // Bind to LocalService
      -        Intent intent = new Intent(this, LocalService.class);
      -        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
      -    }
      -
      -    @Override
      -    protected void onStop() {
      -        super.onStop();
      -        // Unbind from the service
      -        if (mBound) {
      -            unbindService(mConnection);
      -            mBound = false;
      -        }
      -    }
      -
      -    /** Called when a button is clicked (the button in the layout file attaches to
      -      * this method with the android:onClick attribute) */
      -    public void onButtonClick(View v) {
      -        if (mBound) {
      -            // Call a method from the LocalService.
      -            // However, if this call were something that might hang, then this request should
      -            // occur in a separate thread to avoid slowing down the activity performance.
      -            int num = mService.getRandomNumber();
      -            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
      -        }
      -    }
      -
      -    /** Defines callbacks for service binding, passed to bindService() */
      -    private ServiceConnection mConnection = new ServiceConnection() {
      -
      -        @Override
      -        public void onServiceConnected(ComponentName className,
      -                IBinder service) {
      -            // We've bound to LocalService, cast the IBinder and get LocalService instance
      -            LocalBinder binder = (LocalBinder) service;
      -            mService = binder.getService();
      -            mBound = true;
      -        }
      -
      -        @Override
      -        public void onServiceDisconnected(ComponentName arg0) {
      -            mBound = false;
      -        }
      -    };
      -}
      -
      - -

      The above sample shows how the client binds to the service using an implementation of -{@link android.content.ServiceConnection} and the {@link -android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. The next -section provides more information about this process of binding to the service.

      - -

      Note: The example above doesn't explicitly unbind from the service, -but all clients should unbind at an appropriate time (such as when the activity pauses).

      - -

      For more sample code, see the {@code -LocalService.java} class and the {@code -LocalServiceActivities.java} class in ApiDemos.

      - - - - - -

      Using a Messenger

      - - - -

      If you need your service to communicate with remote processes, then you can use a -{@link android.os.Messenger} to provide the interface for your service. This technique allows -you to perform interprocess communication (IPC) without the need to use AIDL.

      - -

      Here's a summary of how to use a {@link android.os.Messenger}:

      - -
        -
      • The service implements a {@link android.os.Handler} that receives a callback for each -call from a client.
      • -
      • The {@link android.os.Handler} is used to create a {@link android.os.Messenger} object -(which is a reference to the {@link android.os.Handler}).
      • -
      • The {@link android.os.Messenger} creates an {@link android.os.IBinder} that the service -returns to clients from {@link android.app.Service#onBind onBind()}.
      • -
      • Clients use the {@link android.os.IBinder} to instantiate the {@link android.os.Messenger} -(that references the service's {@link android.os.Handler}), which the client uses to send -{@link android.os.Message} objects to the service.
      • -
      • The service receives each {@link android.os.Message} in its {@link -android.os.Handler}—specifically, in the {@link android.os.Handler#handleMessage -handleMessage()} method.
      • -
      - - -

      In this way, there are no "methods" for the client to call on the service. Instead, the -client delivers "messages" ({@link android.os.Message} objects) that the service receives in -its {@link android.os.Handler}.

      - -

      Here's a simple example service that uses a {@link android.os.Messenger} interface:

      - -
      -public class MessengerService extends Service {
      -    /** Command to the service to display a message */
      -    static final int MSG_SAY_HELLO = 1;
      -
      -    /**
      -     * Handler of incoming messages from clients.
      -     */
      -    class IncomingHandler extends Handler {
      -        @Override
      -        public void handleMessage(Message msg) {
      -            switch (msg.what) {
      -                case MSG_SAY_HELLO:
      -                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
      -                    break;
      -                default:
      -                    super.handleMessage(msg);
      -            }
      -        }
      -    }
      -
      -    /**
      -     * Target we publish for clients to send messages to IncomingHandler.
      -     */
      -    final Messenger mMessenger = new Messenger(new IncomingHandler());
      -
      -    /**
      -     * When binding to the service, we return an interface to our messenger
      -     * for sending messages to the service.
      -     */
      -    @Override
      -    public IBinder onBind(Intent intent) {
      -        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
      -        return mMessenger.getBinder();
      -    }
      -}
      -
      - -

      Notice that the {@link android.os.Handler#handleMessage handleMessage()} method in the -{@link android.os.Handler} is where the service receives the incoming {@link android.os.Message} -and decides what to do, based on the {@link android.os.Message#what} member.

      - -

      All that a client needs to do is create a {@link android.os.Messenger} based on the {@link -android.os.IBinder} returned by the service and send a message using {@link -android.os.Messenger#send send()}. For example, here's a simple activity that binds to the -service and delivers the {@code MSG_SAY_HELLO} message to the service:

      - -
      -public class ActivityMessenger extends Activity {
      -    /** Messenger for communicating with the service. */
      -    Messenger mService = null;
      -
      -    /** Flag indicating whether we have called bind on the service. */
      -    boolean mBound;
      -
      -    /**
      -     * Class for interacting with the main interface of the service.
      -     */
      -    private ServiceConnection mConnection = new ServiceConnection() {
      -        public void onServiceConnected(ComponentName className, IBinder service) {
      -            // This is called when the connection with the service has been
      -            // established, giving us the object we can use to
      -            // interact with the service.  We are communicating with the
      -            // service using a Messenger, so here we get a client-side
      -            // representation of that from the raw IBinder object.
      -            mService = new Messenger(service);
      -            mBound = true;
      -        }
      -
      -        public void onServiceDisconnected(ComponentName className) {
      -            // This is called when the connection with the service has been
      -            // unexpectedly disconnected -- that is, its process crashed.
      -            mService = null;
      -            mBound = false;
      -        }
      -    };
      -
      -    public void sayHello(View v) {
      -        if (!mBound) return;
      -        // Create and send a message to the service, using a supported 'what' value
      -        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
      -        try {
      -            mService.send(msg);
      -        } catch (RemoteException e) {
      -            e.printStackTrace();
      -        }
      -    }
      -
      -    @Override
      -    protected void onCreate(Bundle savedInstanceState) {
      -        super.onCreate(savedInstanceState);
      -        setContentView(R.layout.main);
      -    }
      -
      -    @Override
      -    protected void onStart() {
      -        super.onStart();
      -        // Bind to the service
      -        bindService(new Intent(this, MessengerService.class), mConnection,
      -            Context.BIND_AUTO_CREATE);
      -    }
      -
      -    @Override
      -    protected void onStop() {
      -        super.onStop();
      -        // Unbind from the service
      -        if (mBound) {
      -            unbindService(mConnection);
      -            mBound = false;
      -        }
      -    }
      -}
      -
      - -

      Notice that this example does not show how the service can respond to the client. If you want the -service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then -when the client receives the {@link android.content.ServiceConnection#onServiceConnected -onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes -the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter -of the {@link android.os.Messenger#send send()} method.

      - -

      You can see an example of how to provide two-way messaging in the {@code -MessengerService.java} (service) and {@code -MessengerServiceActivities.java} (client) samples.

      - - - - - -

      Binding to a Service

      - -

      Application components (clients) can bind to a service by calling -{@link android.content.Context#bindService bindService()}. The Android -system then calls the service's {@link android.app.Service#onBind -onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.

      - -

      The binding is asynchronous. {@link android.content.Context#bindService -bindService()} returns immediately and does not return the {@link android.os.IBinder} to -the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link -android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService -bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the -system calls to deliver the {@link android.os.IBinder}.

      - -

      Note: Only activities, services, and content providers can bind -to a service—you cannot bind to a service from a broadcast receiver.

      - -

      So, to bind to a service from your client, you must:

      -
        -
      1. Implement {@link android.content.ServiceConnection}. -

        Your implementation must override two callback methods:

        -
        -
        {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}
        -
        The system calls this to deliver the {@link android.os.IBinder} returned by -the service's {@link android.app.Service#onBind onBind()} method.
        -
        {@link android.content.ServiceConnection#onServiceDisconnected -onServiceDisconnected()}
        -
        The Android system calls this when the connection to the service is unexpectedly -lost, such as when the service has crashed or has been killed. This is not called when the -client unbinds.
        -
        -
      2. -
      3. Call {@link -android.content.Context#bindService bindService()}, passing the {@link -android.content.ServiceConnection} implementation.
      4. -
      5. When the system calls your {@link android.content.ServiceConnection#onServiceConnected -onServiceConnected()} callback method, you can begin making calls to the service, using -the methods defined by the interface.
      6. -
      7. To disconnect from the service, call {@link -android.content.Context#unbindService unbindService()}. -

        When your client is destroyed, it will unbind from the service, but you should always unbind -when you're done interacting with the service or when your activity pauses so that the service can -shutdown while its not being used. (Appropriate times to bind and unbind is discussed -more below.)

        -
      8. -
      - -

      For example, the following snippet connects the client to the service created above by -extending the Binder class, so all it must do is cast the returned -{@link android.os.IBinder} to the {@code LocalService} class and request the {@code -LocalService} instance:

      - -
      -LocalService mService;
      -private ServiceConnection mConnection = new ServiceConnection() {
      -    // Called when the connection with the service is established
      -    public void onServiceConnected(ComponentName className, IBinder service) {
      -        // Because we have bound to an explicit
      -        // service that is running in our own process, we can
      -        // cast its IBinder to a concrete class and directly access it.
      -        LocalBinder binder = (LocalBinder) service;
      -        mService = binder.getService();
      -        mBound = true;
      -    }
      -
      -    // Called when the connection with the service disconnects unexpectedly
      -    public void onServiceDisconnected(ComponentName className) {
      -        Log.e(TAG, "onServiceDisconnected");
      -        mBound = false;
      -    }
      -};
      -
      - -

      With this {@link android.content.ServiceConnection}, the client can bind to a service by passing -this it to {@link android.content.Context#bindService bindService()}. For example:

      - -
      -Intent intent = new Intent(this, LocalService.class);
      -bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
      -
      - -
        -
      • The first parameter of {@link android.content.Context#bindService bindService()} is an -{@link android.content.Intent} that explicitly names the service to bind (thought the intent -could be implicit).
      • -
      • The second parameter is the {@link android.content.ServiceConnection} object.
      • -
      • The third parameter is a flag indicating options for the binding. It should usually be {@link -android.content.Context#BIND_AUTO_CREATE} in order to create the service if its not already alive. -Other possible values are {@link android.content.Context#BIND_DEBUG_UNBIND} -and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.
      • -
      - - -

      Additional notes

      - -

      Here are some important notes about binding to a service:

      -
        -
      • You should always trap {@link android.os.DeadObjectException} exceptions, which are thrown -when the connection has broken. This is the only exception thrown by remote methods.
      • -
      • Objects are reference counted across processes.
      • -
      • You should usually pair the binding and unbinding during -matching bring-up and tear-down moments of the client's lifecycle. For example: -
          -
        • If you only need to interact with the service while your activity is visible, you -should bind during {@link android.app.Activity#onStart onStart()} and unbind during {@link -android.app.Activity#onStop onStop()}.
        • -
        • If you want your activity to receive responses even while it is stopped in the -background, then you can bind during {@link android.app.Activity#onCreate onCreate()} and unbind -during {@link android.app.Activity#onDestroy onDestroy()}. Beware that this implies that your -activity needs to use the service the entire time it's running (even in the background), so if -the service is in another process, then you increase the weight of the process and it becomes -more likely that the system will kill it.
        • -
        -

        Note: You should usually not bind and unbind -during your activity's {@link android.app.Activity#onResume onResume()} and {@link -android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition -and you should keep the processing that occurs at these transitions to a minimum. Also, if -multiple activities in your application bind to the same service and there is a transition between -two of those activities, the service may be destroyed and recreated as the current activity unbinds -(during pause) before the next one binds (during resume). (This activity transition for how -activities coordinate their lifecycles is described in the Activities -document.)

        -
      - -

      For more sample code, showing how to bind to a service, see the {@code -RemoteService.java} class in ApiDemos.

      - - - - - -

      Managing the Lifecycle of a Bound Service

      - -
      - -

      Figure 1. The lifecycle for a service that is started -and also allows binding.

      -
      - -

      When a service is unbound from all clients, the Android system destroys it (unless it was also -started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have -to manage the lifecycle of your service if it's purely a bound -service—the Android system manages it for you based on whether it is bound to any clients.

      - -

      However, if you choose to implement the {@link android.app.Service#onStartCommand -onStartCommand()} callback method, then you must explicitly stop the service, because the -service is now considered to be started. In this case, the service runs until the service -stops itself with {@link android.app.Service#stopSelf()} or another component calls {@link -android.content.Context#stopService stopService()}, regardless of whether it is bound to any -clients.

      - -

      Additionally, if your service is started and accepts binding, then when the system calls -your {@link android.app.Service#onUnbind onUnbind()} method, you can optionally return -{@code true} if you would like to receive a call to {@link android.app.Service#onRebind -onRebind()} the next time a client binds to the service (instead of receiving a call to {@link -android.app.Service#onBind onBind()}). {@link android.app.Service#onRebind -onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its -{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. -Below, figure 1 illustrates the logic for this kind of lifecycle.

      - -

      For more information about the lifecycle of an started service, see the Services document.

      - - - - diff --git a/docs/html/guide/topics/fundamentals/fragments.jd b/docs/html/guide/topics/fundamentals/fragments.jd deleted file mode 100644 index 2a223946726f..000000000000 --- a/docs/html/guide/topics/fundamentals/fragments.jd +++ /dev/null @@ -1,836 +0,0 @@ -page.title=Fragments -parent.title=Activities -parent.link=activities.html -@jd:body - -
      -
      - -

      Quickview

      -
        -
      • Fragments decompose application functionality and UI into reusable modules
      • -
      • Add multiple fragments to a screen to avoid switching activities
      • -
      • Fragments have their own lifecycle, state, and back stack
      • -
      • Fragments require API Level 11 or greater
      • -
      - -

      In this document

      -
        -
      1. Design Philosophy
      2. -
      3. Creating a Fragment -
          -
        1. Adding a user interface
        2. -
        3. Adding a fragment to an activity
        4. -
        -
      4. -
      5. Managing Fragments
      6. -
      7. Performing Fragment Transactions
      8. -
      9. Communicating with the Activity -
          -
        1. Creating event callbacks to the activity
        2. -
        3. Adding items to the Action Bar
        4. -
        -
      10. -
      11. Handling the Fragment Lifecycle -
          -
        1. Coordinating with the activity lifecycle
        2. -
        -
      12. -
      13. Example
      14. -
      - -

      Key classes

      -
        -
      1. {@link android.app.Fragment}
      2. -
      3. {@link android.app.FragmentManager}
      4. -
      5. {@link android.app.FragmentTransaction}
      6. -
      - -

      Related samples

      -
        -
      1. Honeycomb Gallery
      2. -
      3. ApiDemos
      4. -
      - -

      See also

      -
        -
      1. Supporting Tablets -and Handsets
      2. -
      -
      -
      - -

      A {@link android.app.Fragment} represents a behavior or a portion of user interface in an -{@link android.app.Activity}. You can combine multiple fragments in a single activity to build a -multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a -modular section of an activity, which has its own lifecycle, receives its own input events, and -which you can add or remove while the activity is running (sort of like a "sub activity" that -you can reuse in different activities).

      - -

      A fragment must always be embedded in an activity and the fragment's lifecycle is directly -affected by the host activity's lifecycle. For example, when the activity is paused, so are all -fragments in it, and when the activity is destroyed, so are all fragments. However, while an -activity is running (it is in the resumed lifecycle state), you can -manipulate each fragment independently, such as add or remove them. When you perform such a -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.

      - -

      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 -layout. -You can insert a fragment into your activity layout by declaring the fragment in the activity's -layout file, as a {@code <fragment>} element, or from your application code by adding it to an -existing {@link android.view.ViewGroup}. However, a fragment is not required to be a part of the -activity layout; you may also use a fragment without its own UI as an invisible worker for the -activity.

      - -

      This document describes how to build your application to use fragments, including -how fragments can maintain their state when added to the activity's back stack, share -events with the activity and other fragments in the activity, contribute to the activity's action -bar, and more.

      - - -

      Design Philosophy

      - -

      Android introduced fragments in Android 3.0 (API level 11), primarily to support more -dynamic and flexible UI designs on large screens, such as tablets. Because a -tablet's screen is much larger than that of a handset, there's more room to combine and -interchange UI components. Fragments allow such designs without the need for you to manage complex -changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able -to modify the activity's appearance at runtime and preserve those changes in a back stack -that's managed by the activity.

      - -

      For example, a news application can use one fragment to show a list of articles on the -left and another fragment to display an article on the right—both fragments appear in one -activity, side by side, and each fragment has its own set of lifecycle callback methods and handle -their own user input events. Thus, instead of using one activity to select an article and another -activity to read the article, the user can select an article and read it all within the same -activity, as illustrated in the tablet layout in figure 1.

      - -

      You should design each fragment as a modular and reusable activity component. That is, because -each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can -include one fragment in multiple activities, so you should design for reuse and avoid directly -manipulating one fragment from another fragment. This is especially important because a modular -fragment allows you to change your fragment combinations for different screen sizes. When designing -your application to support both tablets and handsets, you can reuse your fragments in different -layout configurations to optimize the user experience based on the available screen space. For -example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when -more than one cannot fit within the same activity.

      - - -

      Figure 1. An example of how two UI modules defined by -fragments can be combined into one activity for a tablet design, but separated for a -handset design.

      - -

      For example—to continue with the news application example—the application can embed -two fragments in Activity A, when running on a tablet-sized device. However, on a -handset-sized screen, there's not enough room for both fragments, so Activity A includes -only the fragment for the list of articles, and when the user selects an article, it starts -Activity B, 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 -figure 1.

      - -

      For more information about designing your application with different fragment combinations for -different screen configurations, see the guide to Supporting Tablets and Handsets.

      - - - -

      Creating a Fragment

      - -
      - -

      Figure 2. The lifecycle of a fragment (while its -activity is running).

      -
      - -

      To create a fragment, you must create a subclass of {@link android.app.Fragment} (or an existing -subclass of it). The {@link android.app.Fragment} class has code that looks a lot like -an {@link android.app.Activity}. It contains callback methods similar to an activity, such -as {@link android.app.Fragment#onCreate onCreate()}, {@link android.app.Fragment#onStart onStart()}, -{@link android.app.Fragment#onPause onPause()}, and {@link android.app.Fragment#onStop onStop()}. In -fact, if you're converting an existing Android application to use fragments, you might simply move -code from your activity's callback methods into the respective callback methods of your -fragment.

      - -

      Usually, you should implement at least the following lifecycle methods:

      - -
      -
      {@link android.app.Fragment#onCreate onCreate()}
      -
      The system calls this when creating the fragment. Within your implementation, you should -initialize essential components of the fragment that you want to retain when the fragment is -paused or stopped, then resumed.
      -
      {@link android.app.Fragment#onCreateView onCreateView()}
      -
      The system calls this when it's time for the fragment to draw its user interface for the -first time. To draw a UI for your fragment, you must return a {@link android.view.View} from this -method that is the root of your fragment's layout. You can return null if the fragment does not -provide a UI.
      -
      {@link android.app.Activity#onPause onPause()}
      -
      The system calls this method as the first indication that the user is leaving the -fragment (though it does not always mean the fragment is being destroyed). This is usually where you -should commit any changes that should be persisted beyond the current user session (because -the user might not come back).
      -
      - -

      Most applications should implement at least these three methods for every fragment, but there are -several other callback methods you should also use to handle various stages of the -fragment lifecycle. All the lifecycle callback methods are discussed more later, in the section -about Handling the Fragment Lifecycle.

      - - -

      There are also a few subclasses that you might want to extend, instead of the base {@link -android.app.Fragment} class:

      - -
      -
      {@link android.app.DialogFragment}
      -
      Displays a floating dialog. Using this class to create a dialog is a good alternative to using -the dialog helper methods in the {@link android.app.Activity} class, because you can -incorporate a fragment dialog into the back stack of fragments managed by the activity, -allowing the user to return to a dismissed fragment.
      - -
      {@link android.app.ListFragment}
      -
      Displays a list of items that are managed by an adapter (such as a {@link -android.widget.SimpleCursorAdapter}), similar to {@link android.app.ListActivity}. It provides -several methods for managing a list view, such as the {@link -android.app.ListFragment#onListItemClick(ListView,View,int,long) onListItemClick()} callback to -handle click events.
      - -
      {@link android.preference.PreferenceFragment}
      -
      Displays a hierarchy of {@link android.preference.Preference} objects as a list, similar to -{@link android.preference.PreferenceActivity}. This is useful when creating a "settings" -activity for your application.
      -
      - - -

      Adding a user interface

      - -

      A fragment is usually used as part of an activity's user interface and contributes its own -layout to the activity.

      - -

      To provide a layout for a fragment, you must implement the {@link -android.app.Fragment#onCreateView onCreateView()} callback method, which the Android system calls -when it's time for the fragment to draw its layout. Your implementation of this method must return a -{@link android.view.View} that is the root of your fragment's layout.

      - -

      Note: If your fragment is a subclass of {@link -android.app.ListFragment}, the default implementation returns a {@link android.widget.ListView} from -{@link android.app.Fragment#onCreateView onCreateView()}, so you don't need to implement it.

      - -

      To return a layout from {@link -android.app.Fragment#onCreateView onCreateView()}, you can inflate it from a layout resource defined in XML. To -help you do so, {@link android.app.Fragment#onCreateView onCreateView()} provides a -{@link android.view.LayoutInflater} object.

      - -

      For example, here's a subclass of {@link android.app.Fragment} that loads a layout from the -{@code example_fragment.xml} file:

      - -
      -public static class ExampleFragment extends Fragment {
      -    @Override
      -    public View onCreateView(LayoutInflater inflater, ViewGroup container,
      -                             Bundle savedInstanceState) {
      -        // Inflate the layout for this fragment
      -        return inflater.inflate(R.layout.example_fragment, container, false);
      -    }
      -}
      -
      - - - -

      The {@code container} parameter passed to {@link android.app.Fragment#onCreateView -onCreateView()} is the parent {@link android.view.ViewGroup} (from the activity's layout) in which -your fragment layout -will be inserted. The {@code savedInstanceState} parameter is a {@link android.os.Bundle} that -provides data about the previous instance of the fragment, if the fragment is being resumed -(restoring state is discussed more in the section about Handling the -Fragment Lifecycle).

      - -

      The {@link android.view.LayoutInflater#inflate(int,ViewGroup,boolean) inflate()} method takes -three arguments:

      -
        -
      • The resource ID of the layout you want to inflate.
      • -
      • The {@link android.view.ViewGroup} to be the parent of the inflated layout. Passing the {@code -container} is important in order for the system to apply layout parameters to the root view of the -inflated layout, specified by the parent view in which it's going.
      • -
      • A boolean indicating whether the inflated layout should be attached to the {@link -android.view.ViewGroup} (the second parameter) during inflation. (In this case, this -is false because the system is already inserting the inflated layout into the {@code -container}—passing true would create a redundant view group in the final layout.)
      • -
      - -

      Now you've seen how to create a fragment that provides a layout. Next, you need to add -the fragment to your activity.

      - - - -

      Adding a fragment to an activity

      - -

      Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part -of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity -layout:

      - -
        -
      • Declare the fragment inside the activity's layout file. -

        In this case, you can -specify layout properties for the fragment as if it were a view. For example, here's the layout -file for an activity with two fragments:

        -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:orientation="horizontal"
        -    android:layout_width="match_parent"
        -    android:layout_height="match_parent">
        -    <fragment android:name="com.example.news.ArticleListFragment"
        -            android:id="@+id/list"
        -            android:layout_weight="1"
        -            android:layout_width="0dp"
        -            android:layout_height="match_parent" />
        -    <fragment android:name="com.example.news.ArticleReaderFragment"
        -            android:id="@+id/viewer"
        -            android:layout_weight="2"
        -            android:layout_width="0dp"
        -            android:layout_height="match_parent" />
        -</LinearLayout>
        -
        -

        The {@code android:name} attribute in the {@code <fragment>} specifies the {@link -android.app.Fragment} class to instantiate in the layout.

        - -

        When the system creates this activity layout, it instantiates each fragment specified in the -layout and calls the {@link android.app.Fragment#onCreateView onCreateView()} method for each one, -to retrieve each fragment's layout. The system inserts the {@link android.view.View} returned by the -fragment directly in place of the {@code <fragment>} element.

        - -
        -

        Note: Each fragment requires a unique identifier that -the system can use to restore the fragment if the activity is restarted (and which you can use to -capture the fragment to perform transactions, such as remove it). There are three ways to provide an -ID for a fragment:

        -
          -
        • Supply the {@code android:id} attribute with a unique ID.
        • -
        • Supply the {@code android:tag} attribute with a unique string.
        • -
        • If you provide neither of the previous two, the system uses the ID of the container -view.
        • -
        -
        -
      • - -
      • Or, programmatically add the fragment to an existing {@link android.view.ViewGroup}. -

        At any time while your activity is running, you can add fragments to your activity layout. You -simply need to specify a {@link -android.view.ViewGroup} in which to place the fragment.

        -

        To make fragment transactions in your activity (such as add, remove, or replace a -fragment), you must use APIs from {@link android.app.FragmentTransaction}. You can get an instance -of {@link android.app.FragmentTransaction} from your {@link android.app.Activity} like this:

        - -
        -FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()}
        -FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
        -
        - -

        You can then add a fragment using the {@link -android.app.FragmentTransaction#add(int,Fragment) add()} method, specifying the fragment to add and -the view in which to insert it. For example:

        - -
        -ExampleFragment fragment = new ExampleFragment();
        -fragmentTransaction.add(R.id.fragment_container, fragment);
        -fragmentTransaction.commit();
        -
        - -

        The first argument passed to {@link android.app.FragmentTransaction#add(int,Fragment) add()} -is the {@link android.view.ViewGroup} in which the fragment should be placed, specified by -resource ID, and the second parameter is the fragment to add.

        -

        Once you've made your changes with -{@link android.app.FragmentTransaction}, you must -call {@link android.app.FragmentTransaction#commit} for the changes to take effect.

        -
      • -
      - - -

      Adding a fragment without a UI

      - -

      The examples above show how to add a fragment to your activity in order to provide a UI. However, -you can also use a fragment to provide a background behavior for the activity without presenting -additional UI.

      - -

      To add a fragment without a UI, add the fragment from the activity using {@link -android.app.FragmentTransaction#add(Fragment,String)} (supplying a unique string "tag" for the -fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a -view in the activity layout, it does not receive a call to {@link -android.app.Fragment#onCreateView onCreateView()}. So you don't need to implement that method.

      - -

      Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also -supply string tags to fragments that do have a UI—but if the fragment does not have a -UI, then the string tag is the only way to identify it. If you want to get the fragment from the -activity later, you need to use {@link android.app.FragmentManager#findFragmentByTag -findFragmentByTag()}.

      - -

      For an example activity that uses a fragment as a background worker, without a UI, see the {@code -FragmentRetainInstance.java} sample.

      - - - -

      Managing Fragments

      - -

      To manage the fragments in your activity, you need to use {@link android.app.FragmentManager}. To -get it, call {@link android.app.Activity#getFragmentManager()} from your activity.

      - -

      Some things that you can do with {@link android.app.FragmentManager} include:

      - -
        -
      • Get fragments that exist in the activity, with {@link -android.app.FragmentManager#findFragmentById findFragmentById()} (for fragments that provide a UI in -the activity layout) or {@link android.app.FragmentManager#findFragmentByTag -findFragmentByTag()} (for fragments that do or don't provide a UI).
      • -
      • Pop fragments off the back stack, with {@link -android.app.FragmentManager#popBackStack()} (simulating a Back command by the user).
      • -
      • Register a listener for changes to the back stack, with {@link -android.app.FragmentManager#addOnBackStackChangedListener addOnBackStackChangedListener()}.
      • -
      - -

      For more information about these methods and others, refer to the {@link -android.app.FragmentManager} class documentation.

      - -

      As demonstrated in the previous section, you can also use {@link android.app.FragmentManager} -to open a {@link android.app.FragmentTransaction}, which allows you to perform transactions, such as -add and remove fragments.

      - - -

      Performing Fragment Transactions

      - -

      A great feature about using fragments in your activity is the ability to add, remove, replace, -and perform other actions with them, in response to user interaction. Each set of changes that you -commit to the activity is called a transaction and you can perform one using APIs in {@link -android.app.FragmentTransaction}. You can also save each transaction to a back stack managed by the -activity, allowing the user to navigate backward through the fragment changes (similar to navigating -backward through activities).

      - -

      You can acquire an instance of {@link android.app.FragmentTransaction} from the {@link -android.app.FragmentManager} like this:

      - -
      -FragmentManager fragmentManager = {@link android.app.Activity#getFragmentManager()};
      -FragmentTransaction fragmentTransaction = fragmentManager.{@link android.app.FragmentManager#beginTransaction()};
      -
      - -

      Each transaction is a set of changes that you want to perform at the same time. You can set -up all the changes you want to perform for a given transaction using methods such as {@link -android.app.FragmentTransaction#add add()}, {@link android.app.FragmentTransaction#remove remove()}, -and {@link android.app.FragmentTransaction#replace replace()}. Then, to apply the transaction -to the activity, you must call {@link android.app.FragmentTransaction#commit()}.

      - - -

      Before you call {@link -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 button.

      - -

      For example, here's how you can replace one fragment with another, and preserve the previous -state in the back stack:

      - -
      -// Create new fragment and transaction
      -Fragment newFragment = new ExampleFragment();
      -FragmentTransaction transaction = getFragmentManager().beginTransaction();
      -
      -// Replace whatever is in the fragment_container view with this fragment,
      -// and add the transaction to the back stack
      -transaction.replace(R.id.fragment_container, newFragment);
      -transaction.addToBackStack(null);
      -
      -// Commit the transaction
      -transaction.commit();
      -
      - -

      In this example, {@code newFragment} replaces whatever fragment (if any) is currently in the -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 button.

      - -

      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 button will reverse them all together.

      - -

      The order in which you add changes to a {@link android.app.FragmentTransaction} doesn't matter, -except:

      -
        -
      • You must call {@link android.app.FragmentTransaction#commit()} last
      • -
      • If you're adding multiple fragments to the same container, then the order in which -you add them determines the order they appear in the view hierarchy
      • -
      - -

      If you do not call {@link android.app.FragmentTransaction#addToBackStack(String) -addToBackStack()} when you perform a transaction that removes a fragment, then that fragment is -destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you -do call {@link android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} when -removing a fragment, then the fragment is stopped and will be resumed if the user navigates -back.

      - -

      Tip: For each fragment transaction, you can apply a transition -animation, by calling {@link android.app.FragmentTransaction#setTransition setTransition()} before -you commit.

      - -

      Calling {@link android.app.FragmentTransaction#commit()} does not perform the transaction -immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon -as the thread is able to do so. If necessary, however, you may call {@link -android.app.FragmentManager#executePendingTransactions()} from your UI thread to immediately execute -transactions submitted by {@link android.app.FragmentTransaction#commit()}. Doing so is -usually not necessary unless the transaction is a dependency for jobs in other threads.

      - -

      Caution: You can commit a transaction using {@link -android.app.FragmentTransaction#commit commit()} only prior to the activity saving its -state (when the user leaves the activity). If you attempt to commit after that point, an -exception will be thrown. This is because the state after the commit can be lost if the activity -needs to be restored. For situations in which its okay that you lose the commit, use {@link -android.app.FragmentTransaction#commitAllowingStateLoss()}.

      - - - - -

      Communicating with the Activity

      - -

      Although a {@link android.app.Fragment} is implemented as an object that's independent from an -{@link android.app.Activity} and can be used inside multiple activities, a given instance of -a fragment is directly tied to the activity that contains it.

      - -

      Specifically, the fragment can access the {@link android.app.Activity} instance with {@link -android.app.Fragment#getActivity()} and easily perform tasks such as find a view in the -activity layout:

      - -
      -View listView = {@link android.app.Fragment#getActivity()}.{@link android.app.Activity#findViewById findViewById}(R.id.list);
      -
      - -

      Likewise, your activity can call methods in the fragment by acquiring a reference to the -{@link android.app.Fragment} from {@link android.app.FragmentManager}, using {@link -android.app.FragmentManager#findFragmentById findFragmentById()} or {@link -android.app.FragmentManager#findFragmentByTag findFragmentByTag()}. For example:

      - -
      -ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
      -
      - - -

      Creating event callbacks to the activity

      - -

      In some cases, you might need a fragment to share events with the activity. A good way to do that -is to define a callback interface inside the fragment and require that the host activity implement -it. When the activity receives a callback through the interface, it can share the information with -other fragments in the layout as necessary.

      - -

      For example, if a news application has two fragments in an activity—one to show a list of -articles (fragment A) and another to display an article (fragment B)—then fragment A must tell -the activity when a list item is selected so that it can tell fragment B to display the article. In -this case, the {@code OnArticleSelectedListener} interface is declared inside fragment A:

      - -
      -public static class FragmentA extends ListFragment {
      -    ...
      -    // Container Activity must implement this interface
      -    public interface OnArticleSelectedListener {
      -        public void onArticleSelected(Uri articleUri);
      -    }
      -    ...
      -}
      -
      - -

      Then the activity that hosts the fragment implements the {@code OnArticleSelectedListener} -interface and -overrides {@code onArticleSelected()} to notify fragment B of the event from fragment A. To ensure -that the host activity implements this interface, fragment A's {@link -android.app.Fragment#onAttach onAttach()} callback method (which the system calls when adding -the fragment to the activity) instantiates an instance of {@code OnArticleSelectedListener} by -casting the {@link android.app.Activity} that is passed into {@link android.app.Fragment#onAttach -onAttach()}:

      - -
      -public static class FragmentA extends ListFragment {
      -    OnArticleSelectedListener mListener;
      -    ...
      -    @Override
      -    public void onAttach(Activity activity) {
      -        super.onAttach(activity);
      -        try {
      -            mListener = (OnArticleSelectedListener) activity;
      -        } catch (ClassCastException e) {
      -            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
      -        }
      -    }
      -    ...
      -}
      -
      - -

      If the activity has not implemented the interface, then the fragment throws a -{@link java.lang.ClassCastException}. -On success, the {@code mListener} member holds a reference to activity's implementation of -{@code OnArticleSelectedListener}, so that fragment A can share events with the activity by calling -methods defined by the {@code OnArticleSelectedListener} interface. For example, if fragment A is an -extension of {@link android.app.ListFragment}, each time -the user clicks a list item, the system calls {@link android.app.ListFragment#onListItemClick -onListItemClick()} in the fragment, which then calls {@code onArticleSelected()} to share -the event with the activity:

      - -
      -public static class FragmentA extends ListFragment {
      -    OnArticleSelectedListener mListener;
      -    ...
      -    @Override
      -    public void onListItemClick(ListView l, View v, int position, long id) {
      -        // Append the clicked item's row ID with the content provider Uri
      -        Uri noteUri = ContentUris.{@link android.content.ContentUris#withAppendedId withAppendedId}(ArticleColumns.CONTENT_URI, id);
      -        // Send the event and Uri to the host activity
      -        mListener.onArticleSelected(noteUri);
      -    }
      -    ...
      -}
      -
      - -

      The {@code id} parameter passed to {@link -android.app.ListFragment#onListItemClick onListItemClick()} is the row ID of the clicked item, -which the activity (or other fragment) uses to fetch the article from the application's {@link -android.content.ContentProvider}.

      - -

      More information about -using a content provider is available in the Content Providers document.

      - - - -

      Adding items to the Action Bar

      - -

      Your fragments can contribute menu items to the activity's Options Menu (and, consequently, the Action Bar) by implementing -{@link android.app.Fragment#onCreateOptionsMenu(Menu,MenuInflater) onCreateOptionsMenu()}. In order -for this method to receive calls, however, you must call {@link -android.app.Fragment#setHasOptionsMenu(boolean) setHasOptionsMenu()} during {@link -android.app.Fragment#onCreate(Bundle) onCreate()}, to indicate that the fragment -would like to add items to the Options Menu (otherwise, the fragment will not receive a call to -{@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()}).

      - -

      Any items that you then add to the Options Menu from the fragment are appended to the existing -menu items. The fragment also receives callbacks to {@link -android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} when a menu item -is selected.

      - -

      You can also register a view in your fragment layout to provide a context menu by calling {@link -android.app.Fragment#registerForContextMenu(View) registerForContextMenu()}. When the user opens -the context menu, the fragment receives a call to {@link -android.app.Fragment#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo) -onCreateContextMenu()}. When the user selects an item, the fragment receives a call to {@link -android.app.Fragment#onContextItemSelected(MenuItem) onContextItemSelected()}.

      - -

      Note: Although your fragment receives an on-item-selected callback -for each menu item it adds, the activity is first to receive the respective callback when the user -selects a menu item. If the activity's implementation of the on-item-selected callback does not -handle the selected item, then the event is passed to the fragment's callback. This is true for -the Options Menu and context menus.

      - -

      For more information about menus, see the Menus and Action Bar developer guides.

      - - - - -

      Handling the Fragment Lifecycle

      - -
      - -

      Figure 3. The effect of the activity lifecycle on the fragment -lifecycle.

      -
      - -

      Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like -an activity, a fragment can exist in three states:

      - -
      -
      Resumed
      -
      The fragment is visible in the running activity.
      - -
      Paused
      -
      Another activity is in the foreground and has focus, but the activity in which this -fragment lives is still visible (the foreground activity is partially transparent or doesn't -cover the entire screen).
      - -
      Stopped
      -
      The fragment is not visible. Either the host activity has been stopped or the -fragment has been removed from the activity but added to the back stack. A stopped fragment is -still alive (all state and member information is retained by the system). However, it is no longer -visible to the user and will be killed if the activity is killed.
      -
      - -

      Also like an activity, you can retain the state of a fragment using a {@link -android.os.Bundle}, in case the activity's process is killed and you need to restore the -fragment state when the activity is recreated. You can save the state during the fragment's {@link -android.app.Fragment#onSaveInstanceState onSaveInstanceState()} callback and restore it during -either {@link android.app.Fragment#onCreate onCreate()}, {@link -android.app.Fragment#onCreateView onCreateView()}, or {@link -android.app.Fragment#onActivityCreated onActivityCreated()}. For more information about saving -state, see the Activities -document.

      - -

      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 button, as discussed in Tasks and Back Stack). -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 -android.app.FragmentTransaction#addToBackStack(String) addToBackStack()} during a transaction that -removes the fragment.

      - -

      Otherwise, managing the fragment lifecycle is very similar to managing the activity -lifecycle. So, the same practices for managing the activity -lifecycle also apply to fragments. What you also need to understand, though, is how the life -of the activity affects the life of the fragment.

      - - -

      Coordinating with the activity lifecycle

      - -

      The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the -fragment, such that each lifecycle callback for the activity results in a similar callback for each -fragment. For example, when the activity receives {@link android.app.Activity#onPause}, each -fragment in the activity receives {@link android.app.Fragment#onPause}.

      - -

      Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the -activity in order to perform actions such as build and destroy the fragment's UI. These additional -callback methods are:

      - -
      -
      {@link android.app.Fragment#onAttach onAttach()}
      -
      Called when the fragment has been associated with the activity (the {@link -android.app.Activity} is passed in here).
      -
      {@link android.app.Fragment#onCreateView onCreateView()}
      -
      Called to create the view hierarchy associated with the fragment.
      -
      {@link android.app.Fragment#onActivityCreated onActivityCreated()}
      -
      Called when the activity's {@link android.app.Activity#onCreate -onCreate()} method has returned.
      -
      {@link android.app.Fragment#onDestroyView onDestroyView()}
      -
      Called when the view hierarchy associated with the fragment is being removed.
      -
      {@link android.app.Fragment#onDetach onDetach()}
      -
      Called when the fragment is being disassociated from the activity.
      -
      - -

      The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated -by figure 3. In this figure, you can see how each successive state of the activity determines which -callback methods a fragment may receive. For example, when the activity has received its {@link -android.app.Activity#onCreate onCreate()} callback, a fragment in the activity receives no more than -the {@link android.app.Fragment#onActivityCreated onActivityCreated()} callback.

      - -

      Once the activity reaches the resumed state, you can freely add and remove fragments to the -activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment -change independently.

      - -

      However, when the activity leaves the resumed state, the fragment again is pushed through its -lifecycle by the activity.

      - - - - -

      Example

      - -

      To bring everything discussed in this document together, here's an example of an activity -using two fragments to create a two-pane layout. The activity below includes one fragment to -show a list of Shakespeare play titles and another to show a summary of the play when selected -from the list. It also demonstrates how to provide different configurations of the fragments, -based on the screen configuration.

      - -

      Note: The complete source code for this activity is available in -{@code -FragmentLayout.java}.

      - -

      The main activity applies a layout in the usual way, during {@link -android.app.Activity#onCreate onCreate()}:

      - -{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java main} - -

      The layout applied is {@code fragment_layout.xml}:

      - -{@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout} - -

      Using this layout, the system instantiates the {@code TitlesFragment} (which lists the play -titles) as soon as the activity loads the layout, while the {@link android.widget.FrameLayout} -(where the fragment for showing the play summary will go) consumes space on the right side of the -screen, but remains empty at first. As you'll see below, it's not until the user selects an item -from the list that a fragment is placed into the {@link android.widget.FrameLayout}.

      - -

      However, not all screen configurations are wide enough to show both the list of -plays and the summary, side by side. So, the layout above is used only for the landscape -screen configuration, by saving it at {@code res/layout-land/fragment_layout.xml}.

      - -

      Thus, when the screen is in portrait orientation, the system applies the following layout, which -is saved at {@code res/layout/fragment_layout.xml}:

      - -{@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout} - -

      This layout includes only {@code TitlesFragment}. This means that, when the device is in -portrait orientation, only the list of play titles is visible. So, when the user clicks a list -item in this configuration, the application will start a new activity to show the summary, -instead of loading a second fragment.

      - -

      Next, you can see how this is accomplished in the fragment classes. First is {@code -TitlesFragment}, which shows the list of Shakespeare play titles. This fragment extends {@link -android.app.ListFragment} and relies on it to handle most of the list view work.

      - -

      As you inspect this code, notice that there are two possible behaviors when the user clicks a -list item: depending on which of the two layouts is active, it can either create and display a new -fragment to show the details in the same activity (adding the fragment to the {@link -android.widget.FrameLayout}), or start a new activity (where the fragment can be shown).

      - -{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java titles} - -

      The second fragment, {@code DetailsFragment} shows the play summary for the item selected from -the list from {@code TitlesFragment}:

      - -{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java details} - -

      Recall from the {@code TitlesFragment} class, that, if the user clicks a list item and the -current layout does not include the {@code R.id.details} view (which is where the -{@code DetailsFragment} belongs), then the application starts the {@code DetailsActivity} -activity to display the content of the item.

      - -

      Here is the {@code DetailsActivity}, which simply embeds the {@code DetailsFragment} to display -the selected play summary when the screen is in portrait orientation:

      - -{@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java -details_activity} - -

      Notice that this activity finishes itself if the configuration is landscape, so that the main -activity can take over and display the {@code DetailsFragment} alongside the {@code TitlesFragment}. -This can happen if the user begins the {@code DetailsActivity} while in portrait orientation, but -then rotates to landscape (which restarts the current activity).

      - - -

      For more samples using fragments (and complete source files for this example), -see the sample code available in -ApiDemos (available for download from the Samples SDK component).

      - - diff --git a/docs/html/guide/topics/fundamentals/loaders.jd b/docs/html/guide/topics/fundamentals/loaders.jd deleted file mode 100644 index ddd513b2a2c5..000000000000 --- a/docs/html/guide/topics/fundamentals/loaders.jd +++ /dev/null @@ -1,500 +0,0 @@ -page.title=Loaders -parent.title=Activities -parent.link=activities.html -@jd:body -
      -
      -

      In this document

      -
        -
      1. Loader API Summary
      2. -
      3. Using Loaders in an Application -
          -
        1. -
        2. Starting a Loader
        3. -
        4. Restarting a Loader
        5. -
        6. Using the LoaderManager Callbacks
        7. -
        -
      4. -
      5. Example -
          -
        1. More Examples
        2. -
        -
      6. -
      - -

      Key classes

      -
        -
      1. {@link android.app.LoaderManager}
      2. -
      3. {@link android.content.Loader}
      4. - -
      - -

      Related samples

      -
        -
      1. -LoaderCursor
      2. -
      3. -LoaderThrottle
      4. -
      -
      -
      - -

      Introduced in Android 3.0, loaders make it easy to asynchronously load data -in an activity or fragment. Loaders have these characteristics:

      -
        -
      • They are available to every {@link android.app.Activity} and {@link -android.app.Fragment}.
      • -
      • They provide asynchronous loading of data.
      • -
      • They monitor the source of their data and deliver new results when the -content changes.
      • -
      • They automatically reconnect to the last loader's cursor when being -recreated after a configuration change. Thus, they don't need to re-query their -data.
      • -
      - -

      Loader API Summary

      - -

      There are multiple classes and interfaces that may be involved in using -loaders in an application. They are summarized in this table:

      - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Class/InterfaceDescription
      {@link android.app.LoaderManager}An abstract class associated with an {@link android.app.Activity} or -{@link android.app.Fragment} for managing one or more {@link -android.content.Loader} instances. This helps an application manage -longer-running operations in conjunction with the {@link android.app.Activity} -or {@link android.app.Fragment} lifecycle; the most common use of this is with a -{@link android.content.CursorLoader}, however applications are free to write -their own loaders for loading other types of data. -
      -
      - There is only one {@link android.app.LoaderManager} per activity or fragment. But a {@link android.app.LoaderManager} can have -multiple loaders.
      {@link android.app.LoaderManager.LoaderCallbacks}A callback interface for a client to interact with the {@link -android.app.LoaderManager}. For example, you use the {@link -android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} -callback method to create a new loader.
      {@link android.content.Loader}An abstract class that performs asynchronous loading of data. This is -the base class for a loader. You would typically use {@link -android.content.CursorLoader}, but you can implement your own subclass. While -loaders are active they should monitor the source of their data and deliver new -results when the contents change.
      {@link android.content.AsyncTaskLoader}Abstract loader that provides an {@link android.os.AsyncTask} to do the work.
      {@link android.content.CursorLoader}A subclass of {@link android.content.AsyncTaskLoader} that queries the -{@link android.content.ContentResolver} and returns a {@link -android.database.Cursor}. This class implements the {@link -android.content.Loader} protocol in a standard way for querying cursors, -building on {@link android.content.AsyncTaskLoader} to perform the cursor query -on a background thread so that it does not block the application's UI. Using -this loader is the best way to asynchronously load data from a {@link -android.content.ContentProvider}, instead of performing a managed query through -the fragment or activity's APIs.
      - -

      The classes and interfaces in the above table are the essential components -you'll use to implement a loader in your application. You won't need all of them -for each loader you create, but you'll always need a reference to the {@link -android.app.LoaderManager} in order to initialize a loader and an implementation -of a {@link android.content.Loader} class such as {@link -android.content.CursorLoader}. The following sections show you how to use these -classes and interfaces in an application.

      - -

      Using Loaders in an Application

      -

      This section describes how to use loaders in an Android application. An -application that uses loaders typically includes the following:

      -
        -
      • An {@link android.app.Activity} or {@link android.app.Fragment}.
      • -
      • An instance of the {@link android.app.LoaderManager}.
      • -
      • A {@link android.content.CursorLoader} to load data backed by a {@link -android.content.ContentProvider}. Alternatively, you can implement your own subclass -of {@link android.content.Loader} or {@link android.content.AsyncTaskLoader} to -load data from some other source.
      • -
      • An implementation for {@link android.app.LoaderManager.LoaderCallbacks}. -This is where you create new loaders and manage your references to existing -loaders.
      • -
      • A way of displaying the loader's data, such as a {@link -android.widget.SimpleCursorAdapter}.
      • -
      • A data source, such as a {@link android.content.ContentProvider}, when using a -{@link android.content.CursorLoader}.
      • -
      -

      Starting a Loader

      - -

      The {@link android.app.LoaderManager} manages one or more {@link -android.content.Loader} instances within an {@link android.app.Activity} or -{@link android.app.Fragment}. There is only one {@link -android.app.LoaderManager} per activity or fragment.

      - -

      You typically -initialize a {@link android.content.Loader} within the activity's {@link -android.app.Activity#onCreate onCreate()} method, or within the fragment's -{@link android.app.Fragment#onActivityCreated onActivityCreated()} method. You -do this as follows:

      - -
      // Prepare the loader.  Either re-connect with an existing one,
      -// or start a new one.
      -getLoaderManager().initLoader(0, null, this);
      - -

      The {@link android.app.LoaderManager#initLoader initLoader()} method takes -the following parameters:

      -
        -
      • A unique ID that identifies the loader. In this example, the ID is 0.
      • -
      • Optional arguments to supply to the loader at -construction (null in this example).
      • - -
      • A {@link android.app.LoaderManager.LoaderCallbacks} implementation, which -the {@link android.app.LoaderManager} calls to report loader events. In this -example, the local class implements the {@link -android.app.LoaderManager.LoaderCallbacks} interface, so it passes a reference -to itself, {@code this}.
      • -
      -

      The {@link android.app.LoaderManager#initLoader initLoader()} call ensures that a loader -is initialized and active. It has two possible outcomes:

      -
        -
      • If the loader specified by the ID already exists, the last created loader -is reused.
      • -
      • If the loader specified by the ID does not exist, -{@link android.app.LoaderManager#initLoader initLoader()} triggers the -{@link android.app.LoaderManager.LoaderCallbacks} method {@link android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}. -This is where you implement the code to instantiate and return a new loader. -For more discussion, see the section onCreateLoader.
      • -
      -

      In either case, the given {@link android.app.LoaderManager.LoaderCallbacks} -implementation is associated with the loader, and will be called when the -loader state changes. If at the point of this call the caller is in its -started state, and the requested loader already exists and has generated its -data, then the system calls {@link -android.app.LoaderManager.LoaderCallbacks#onLoadFinished onLoadFinished()} -immediately (during {@link android.app.LoaderManager#initLoader initLoader()}), -so you must be prepared for this to happen. See -onLoadFinished for more discussion of this callback

      - -

      Note that the {@link android.app.LoaderManager#initLoader initLoader()} -method returns the {@link android.content.Loader} that is created, but you don't -need to capture a reference to it. The {@link android.app.LoaderManager} manages -the life of the loader automatically. The {@link android.app.LoaderManager} -starts and stops loading when necessary, and maintains the state of the loader -and its associated content. As this implies, you rarely interact with loaders -directly (though for an example of using loader methods to fine-tune a loader's -behavior, see the LoaderThrottle sample). -You most commonly use the {@link -android.app.LoaderManager.LoaderCallbacks} methods to intervene in the loading -process when particular events occur. For more discussion of this topic, see Using the LoaderManager Callbacks.

      - -

      Restarting a Loader

      - -

      When you use {@link android.app.LoaderManager#initLoader initLoader()}, as -shown above, it uses an existing loader with the specified ID if there is one. -If there isn't, it creates one. But sometimes you want to discard your old data -and start over.

      - -

      To discard your old data, you use {@link -android.app.LoaderManager#restartLoader restartLoader()}. For example, this -implementation of {@link android.widget.SearchView.OnQueryTextListener} restarts -the loader when the user's query changes. The loader needs to be restarted so -that it can use the revised search filter to do a new query:

      - -
      -public boolean onQueryTextChanged(String newText) {
      -    // Called when the action bar search text has changed.  Update
      -    // the search filter, and restart the loader to do a new query
      -    // with this filter.
      -    mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
      -    getLoaderManager().restartLoader(0, null, this);
      -    return true;
      -}
      - -

      Using the LoaderManager Callbacks

      - -

      {@link android.app.LoaderManager.LoaderCallbacks} is a callback interface -that lets a client interact with the {@link android.app.LoaderManager}.

      -

      Loaders, in particular {@link android.content.CursorLoader}, are expected to -retain their data after being stopped. This allows applications to keep their -data across the activity or fragment's {@link android.app.Activity#onStop -onStop()} and {@link android.app.Activity#onStart onStart()} methods, so that -when users return to an application, they don't have to wait for the data to -reload. You use the {@link android.app.LoaderManager.LoaderCallbacks} methods -when to know when to create a new loader, and to tell the application when it is - time to stop using a loader's data.

      - -

      {@link android.app.LoaderManager.LoaderCallbacks} includes these -methods:

      -
        -
      • {@link android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} — -Instantiate and return a new {@link android.content.Loader} for the given ID. -
      -
        -
      • {@link android.app.LoaderManager.LoaderCallbacks#onLoadFinished onLoadFinished()} -— Called when a previously created loader has finished its load. -
      -
        -
      • {@link android.app.LoaderManager.LoaderCallbacks#onLoaderReset onLoaderReset()} - — Called when a previously created loader is being reset, thus making its -data unavailable. -
      • -
      -

      These methods are described in more detail in the following sections.

      - -

      onCreateLoader

      - -

      When you attempt to access a loader (for example, through {@link -android.app.LoaderManager#initLoader initLoader()}), it checks to see whether -the loader specified by the ID exists. If it doesn't, it triggers the {@link -android.app.LoaderManager.LoaderCallbacks} method {@link -android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()}. This -is where you create a new loader. Typically this will be a {@link -android.content.CursorLoader}, but you can implement your own {@link -android.content.Loader} subclass.

      - -

      In this example, the {@link -android.app.LoaderManager.LoaderCallbacks#onCreateLoader onCreateLoader()} -callback method creates a {@link android.content.CursorLoader}. You must build -the {@link android.content.CursorLoader} using its constructor method, which -requires the complete set of information needed to perform a query to the {@link -android.content.ContentProvider}. Specifically, it needs:

      -
        -
      • uri — The URI for the content to retrieve.
      • -
      • projection — A list of which columns to return. Passing -null will return all columns, which is inefficient.
      • -
      • selection — A filter declaring which rows to return, -formatted as an SQL WHERE clause (excluding the WHERE itself). Passing -null will return all rows for the given URI.
      • -
      • selectionArgs — You may include ?s in the selection, which will -be replaced by the values from selectionArgs, in the order that they appear in -the selection. The values will be bound as Strings.
      • -
      • sortOrder — How to order the rows, formatted as an SQL -ORDER BY clause (excluding the ORDER BY itself). Passing null will -use the default sort order, which may be unordered.
      • -
      -

      For example:

      -
      - // If non-null, this is the current filter the user has provided.
      -String mCurFilter;
      -...
      -public Loader<Cursor> onCreateLoader(int id, Bundle args) {
      -    // This is called when a new Loader needs to be created.  This
      -    // sample only has one Loader, so we don't care about the ID.
      -    // First, pick the base URI to use depending on whether we are
      -    // currently filtering.
      -    Uri baseUri;
      -    if (mCurFilter != null) {
      -        baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
      -                  Uri.encode(mCurFilter));
      -    } else {
      -        baseUri = Contacts.CONTENT_URI;
      -    }
      -
      -    // Now create and return a CursorLoader that will take care of
      -    // creating a Cursor for the data being displayed.
      -    String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
      -            + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
      -            + Contacts.DISPLAY_NAME + " != '' ))";
      -    return new CursorLoader(getActivity(), baseUri,
      -            CONTACTS_SUMMARY_PROJECTION, select, null,
      -            Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
      -}
      -

      onLoadFinished

      - -

      This method is called when a previously created loader has finished its load. -This method is guaranteed to be called prior to the release of the last data -that was supplied for this loader. At this point you should remove all use of -the old data (since it will be released soon), but should not do your own -release of the data since its loader owns it and will take care of that.

      - - -

      The loader will release the data once it knows the application is no longer -using it. For example, if the data is a cursor from a {@link -android.content.CursorLoader}, you should not call {@link -android.database.Cursor#close close()} on it yourself. If the cursor is being -placed in a {@link android.widget.CursorAdapter}, you should use the {@link -android.widget.SimpleCursorAdapter#swapCursor swapCursor()} method so that the -old {@link android.database.Cursor} is not closed. For example:

      - -
      -// This is the Adapter being used to display the list's data.
      SimpleCursorAdapter mAdapter; -... - -public void onLoadFinished(Loader<Cursor> loader, Cursor data) { - // Swap the new cursor in.  (The framework will take care of closing the - // old cursor once we return.) - mAdapter.swapCursor(data); -}
      - -

      onLoaderReset

      - -

      This method is called when a previously created loader is being reset, thus -making its data unavailable. This callback lets you find out when the data is -about to be released so you can remove your reference to it.  

      -

      This implementation calls -{@link android.widget.SimpleCursorAdapter#swapCursor swapCursor()} -with a value of null:

      - -
      -// This is the Adapter being used to display the list's data.
      -SimpleCursorAdapter mAdapter;
      -...
      -
      -public void onLoaderReset(Loader<Cursor> loader) {
      -    // This is called when the last Cursor provided to onLoadFinished()
      -    // above is about to be closed.  We need to make sure we are no
      -    // longer using it.
      -    mAdapter.swapCursor(null);
      -}
      - - -

      Example

      - -

      As an example, here is the full implementation of a {@link -android.app.Fragment} that displays a {@link android.widget.ListView} containing -the results of a query against the contacts content provider. It uses a {@link -android.content.CursorLoader} to manage the query on the provider.

      - -

      For an application to access a user's contacts, as shown in this example, its -manifest must include the permission -{@link android.Manifest.permission#READ_CONTACTS READ_CONTACTS}.

      - -
      -public static class CursorLoaderListFragment extends ListFragment
      -        implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
      -
      -    // This is the Adapter being used to display the list's data.
      -    SimpleCursorAdapter mAdapter;
      -
      -    // If non-null, this is the current filter the user has provided.
      -    String mCurFilter;
      -
      -    @Override public void onActivityCreated(Bundle savedInstanceState) {
      -        super.onActivityCreated(savedInstanceState);
      -
      -        // Give some text to display if there is no data.  In a real
      -        // application this would come from a resource.
      -        setEmptyText("No phone numbers");
      -
      -        // We have a menu item to show in action bar.
      -        setHasOptionsMenu(true);
      -
      -        // Create an empty adapter we will use to display the loaded data.
      -        mAdapter = new SimpleCursorAdapter(getActivity(),
      -                android.R.layout.simple_list_item_2, null,
      -                new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
      -                new int[] { android.R.id.text1, android.R.id.text2 }, 0);
      -        setListAdapter(mAdapter);
      -
      -        // Prepare the loader.  Either re-connect with an existing one,
      -        // or start a new one.
      -        getLoaderManager().initLoader(0, null, this);
      -    }
      -
      -    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      -        // Place an action bar item for searching.
      -        MenuItem item = menu.add("Search");
      -        item.setIcon(android.R.drawable.ic_menu_search);
      -        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
      -        SearchView sv = new SearchView(getActivity());
      -        sv.setOnQueryTextListener(this);
      -        item.setActionView(sv);
      -    }
      -
      -    public boolean onQueryTextChange(String newText) {
      -        // Called when the action bar search text has changed.  Update
      -        // the search filter, and restart the loader to do a new query
      -        // with this filter.
      -        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
      -        getLoaderManager().restartLoader(0, null, this);
      -        return true;
      -    }
      -
      -    @Override public boolean onQueryTextSubmit(String query) {
      -        // Don't care about this.
      -        return true;
      -    }
      -
      -    @Override public void onListItemClick(ListView l, View v, int position, long id) {
      -        // Insert desired behavior here.
      -        Log.i("FragmentComplexList", "Item clicked: " + id);
      -    }
      -
      -    // These are the Contacts rows that we will retrieve.
      -    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
      -        Contacts._ID,
      -        Contacts.DISPLAY_NAME,
      -        Contacts.CONTACT_STATUS,
      -        Contacts.CONTACT_PRESENCE,
      -        Contacts.PHOTO_ID,
      -        Contacts.LOOKUP_KEY,
      -    };
      -    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
      -        // This is called when a new Loader needs to be created.  This
      -        // sample only has one Loader, so we don't care about the ID.
      -        // First, pick the base URI to use depending on whether we are
      -        // currently filtering.
      -        Uri baseUri;
      -        if (mCurFilter != null) {
      -            baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
      -                    Uri.encode(mCurFilter));
      -        } else {
      -            baseUri = Contacts.CONTENT_URI;
      -        }
      -
      -        // Now create and return a CursorLoader that will take care of
      -        // creating a Cursor for the data being displayed.
      -        String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
      -                + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
      -                + Contacts.DISPLAY_NAME + " != '' ))";
      -        return new CursorLoader(getActivity(), baseUri,
      -                CONTACTS_SUMMARY_PROJECTION, select, null,
      -                Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
      -    }
      -
      -    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
      -        // Swap the new cursor in.  (The framework will take care of closing the
      -        // old cursor once we return.)
      -        mAdapter.swapCursor(data);
      -    }
      -
      -    public void onLoaderReset(Loader<Cursor> loader) {
      -        // This is called when the last Cursor provided to onLoadFinished()
      -        // above is about to be closed.  We need to make sure we are no
      -        // longer using it.
      -        mAdapter.swapCursor(null);
      -    }
      -}
      -

      More Examples

      - -

      There are a few different samples in ApiDemos that -illustrate how to use loaders:

      -
        -
      • -LoaderCursor — A complete version of the -snippet shown above.
      • -
      • LoaderThrottle — An example of how to use throttling to -reduce the number of queries a content provider does when its data changes.
      • -
      - -

      For information on downloading and installing the SDK samples, see Getting the -Samples.

      - diff --git a/docs/html/guide/topics/fundamentals/processes-and-threads.jd b/docs/html/guide/topics/fundamentals/processes-and-threads.jd deleted file mode 100644 index 814d34edac4c..000000000000 --- a/docs/html/guide/topics/fundamentals/processes-and-threads.jd +++ /dev/null @@ -1,486 +0,0 @@ -page.title=Processes and Threads -@jd:body - -
      -
      -

      Quickview

      -
        -
      • Every application runs in its own process and all components of the application run in that -process, by default
      • -
      • Any slow, blocking operations in an activity should be done in a new thread, to avoid slowing -down the user interface
      • -
      - -

      In this document

      -
        -
      1. Processes -
          -
        1. Process lifecycle
        2. -
        -
      2. -
      3. Threads -
          -
        1. Worker threads
        2. -
        3. Thread-safe methods
        4. -
        -
      4. -
      5. Interprocess Communication
      6. -
      - -
      -
      - -

      When an application component starts and the process that should host that thread is not already -running, the Android system starts a new Linux process for the application with a single thread of -execution. By default, all components of the same application run in the same process and thread -(called the "main" thread). If an application component starts and there already exists a process -for that application (because another component from the application exists or Android has been -able to retain its previous process cached in the background), then the component is -started within that process and uses the same thread of execution. However, you can arrange for -different components in your application to run in separate processes, and you can create additional -threads for any process.

      - -

      This document discusses how processes and threads work in an Android application.

      - - -

      Processes

      - -

      By default, all components of the same application run in the same process and most applications -should not change this. However, if you find that you need to control which process a certain -component belongs to, you can do so in the manifest file.

      - -

      The manifest entry for each type of component element—{@code -<activity>}, {@code -<service>}, {@code -<receiver>}, and {@code -<provider>}—supports an {@code android:process} attribute that can specify a -process in which that component should run. You can set this attribute so that each component runs -in its own process or so that some components share a process while others do not. You can also set -{@code android:process} so that components of different applications run in the same -process—provided that the applications share the same Linux user ID and are signed with the -same certificates.

      - -

      The {@code -<application>} element also supports an {@code android:process} attribute, to set a -default value that applies to all components.

      - -

      Android might decide to shut down a process at some point, when memory is low and required by -other processes that are more immediately serving the user. Application -components running in the process that's killed are consequently destroyed. A process is started -again for those components when there's again work for them to do.

      - -

      When deciding which processes to kill, the Android system weighs their relative importance to -the user. For example, it more readily shuts down a process hosting activities that are no longer -visible on screen, compared to a process hosting visible activities. The decision whether to -terminate a process, therefore, depends on the state of the components running in that process. The -rules used to decide which processes to terminate is discussed below.

      - - -

      Process lifecycle

      - -

      The Android system tries to maintain an application process for as long as possible, but -eventually needs to remove old processes to reclaim memory for new or more important processes. To -determine which processes to keep -and which to kill, the system places each process into an "importance hierarchy" based on the -components running in the process and the state of those components. Processes with the lowest -importance are eliminated first, then those with the next lowest importance, and so on, as necessary -to recover system resources.

      - -

      The exact mapping of processes to importance and the management of these processes is -an implementation detail of the platform that changes over time. Broadly speaking, there -are five levels in the current implementation that are of most relevance to application -developers. The following list presents these different -types of processes in order of importance (the first process is most important and is -killed last):

      - -
        -
      1. Foreground process -

        A process that is required for what the user is currently doing. A - process is considered to be in the foreground if any of the following conditions are true:

        - -
          -
        • It hosts an {@link android.app.Activity} that the user is interacting with (the {@link -android.app.Activity}'s {@link android.app.Activity#onResume onResume()} method has been -called).
        • - -
        • It hosts a {@link android.app.Service} that's executing one of its lifecycle -callbacks ({@link android.app.Service#onCreate onCreate()}, {@link android.app.Service#onStart -onStart()}, or {@link android.app.Service#onDestroy onDestroy()}).
        • - -
        • It hosts a {@link android.content.BroadcastReceiver} that's executing its {@link - android.content.BroadcastReceiver#onReceive onReceive()} method.
        • - -
        • Another foreground process has a dependency on this one: either bound - to a Service in this process, or using a Content Provider of the process.
        • -
        - -

        Generally, only a few foreground processes exist at any given time. They are killed only as -a last resort—if memory is so low that they cannot all continue to run. Generally, at that -point, the device has reached a memory paging state, so killing some foreground processes is -required to keep the user interface responsive.

      2. - -
      3. Visible process -

        A process that doesn't have any foreground components, but still can - affect what the user sees on screen. A process is considered to be visible if either of the - following conditions are true:

        - -
          -
        • It hosts an {@link android.app.Activity} that is not in the foreground, but is still -visible to the user (its {@link android.app.Activity#onPause onPause()} method has been called). -This might occur, for example, if the foreground activity started a dialog, which allows the -previous activity to be seen behind it.
        • - -
        • Another visible process has a dependency on this one: either bound - to a Service in this process, or using a Content Provider of the process.
        • -
        - -

        A visible process is considered extremely important and will not be killed unless doing so -is required to keep all foreground processes running.

        -
      4. - -
      5. Perceptible process -

        A process that doesn't have any foreground or visible components, but is still - doing something that is directly perceptible by the user. A classic example of such - a process would be one doing background music playback. The main way applications - get into this state is through {@link android.app.Service#startForeground} or because - another perceptible process has a dependency on one of its services or content - providers. In addition, as of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, - processes can go into this state when {@link android.app.Activity#onStop - Activity.onStop()} is executing, allowing the process to continue executing - critical code after no longer being visible to the user but before going - fully into the background.

        - -

        Like visible processes, a perceptible process is considered extremely important - and will not be killed unless doing so is required to keep all foreground and - visible processes running.

        -
      6. - -
      7. Service process -

        A process that is running a service that has been started with the {@link -android.content.Context#startService startService()} method and does not fall into any of the -higher categories. Although service processes are not directly tied to anything the user sees, they -are generally doing things that the user cares about (such as downloading a file the user has requested), -so the system keeps them running unless there's not enough memory to retain them along with all -foreground and visible processes.

        - -

        Even though Android tries to keep these processes running, it is considered normal - operation for them to temporarily be killed to support the needs of more important - processes. For example, if the user opens a very heavy-weight web page that needs - most of the device's RAM, background services may be temporarily killed to satisfy - those needs. Services in these processes thus must be prepared to deal gracefully - with being killed while doing their work and later restarted.

        - -

        In recent implementations of Android, there are actually a number of sub-divisions - in this area for processes that Android considers more important to the user and so - would like to try harder to keep around. For example, the process hosting the current - home app is generally kept in this area so that the user will not see long delays in - returning home because that process has been killed.

        -
      8. - -
      9. Background (cached) process -

        The final importance level is for processes that are not of current significance. - This is basically any process that does not fall into one of the previous levels. - These processes have no direct impact on the user experience, and the system can kill - them at any time to reclaim memory for the other more important processes. - This includes everything from processes holding running activity objects that are not currently - visible to the user (the activity's {@link android.app.Activity#onStop onStop()} - method has been called) to processes that have no active code at all but may be - useful to keep around in case they are needed in the near future.

        - -

        Usually there are many background processes being maintained, so they are kept - in an LRU list to allow older processes to be killed before more recent ones. This - helps reduce the frequency that new processes need to be creating, facilitating things - like more rapid switching between the applications the user has recently visited. - However, processes in this state must deal correctly with being killed and later - restarted when needed. For example, if an activity implements its lifecycle methods -correctly, and saves its current state, killing its process will not have a visible effect on -the user experience, because when the user navigates back to the activity, the activity restores -all of its visible state. See the Activities -document for information about saving and restoring state.

        - -

        Android may also employ other additional policies for killing background processes. For - example, there are typically restrictions on a maximum number of such processes to - keep around, and limits on the amount of time they can spend holding wake locks - or consuming CPU power until they will be removed.

        -
      10. -
      - - -

      Android ranks a process at the highest level it can, based upon the importance of the -components currently active in the process. For example, if a process hosts a service and a visible -activity, the process is ranked as a visible process, not a service process.

      - -

      In addition, a process's ranking might be increased because other processes are dependent on -it—a process that is serving another process can not generally be ranked lower than the process it is -serving. For example, if a content provider in process A is serving a client in process B, or if a -service in process A has been bound to by a client in process B, process A is always considered at least -as important as process B.

      - -

      Because a process running a service is ranked higher than a process with background activities, -an activity that initiates a long-running operation may sometimes start a service for that operation, rather than -simply create a worker thread—but only when the operation is a specific task that needs -to be accomplished regardless of whether the user returns to the application. -For example, an activity that's uploading a picture to a web site should start a service to perform -the upload so that the upload can continue in the background even if the user leaves the activity. -Using a service guarantees that the operation will have at least "service process" priority, -regardless of what happens to the activity. This is not however an approach that should always -be used. It would not be appropriate when simply downloading the data for a web page, since -that can easily be restarted later if the user returns to the web browser. Allowing -such a process to be in the background (instead of running a service) gives Android better -information about how to manage that process in relation to others. - -

      For a similar reason, broadcast receivers will often employ services rather than - simply put time-consuming operations in a thread.

      - -

      Some command line tools are available to help you understand how Android is managing - its processes. The most common command is adb shell dumpsys activity - which provides a summary of various key state, including at the end a list of the - process states, one per line (plus an optional second line for any key dependency - on that process), ordered from higher importance to lowest. The exact - contents of these lines has changed across different versions of Android, but the - typical state for one process in the list would be:

      -
      -Proc # 2: adj=prcp /F  trm= 0 848:com.google.android.inputmethod.latin/u0a32 (service)
      -    com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME<=Proc{417:system/1000}
      -
      - -

      This is a perceptible process (adj=prcp) that is running with the foreground - scheduling class (/F), and has not recently been told to trim any memory - (trm= 0). Its process id is 848; its name is com.google.android.inputmethod.latin; - its Linux uid is u0a32 (10032), and the key state contributing to its current - importance level is a service.

      - -

      The second line provides the name of the service that is important, because another - process has a dependency on it (here the system process).

      - -

      Threads

      - -

      When an application is launched, the system creates a thread of execution for the application, -called "main." This thread is very important because it is in charge of dispatching events to -the appropriate user interface widgets, including drawing events. It is also the thread in which -your application interacts with components from the Android UI toolkit (components from the {@link -android.widget} and {@link android.view} packages). As such, the main thread is also sometimes -called the UI thread.

      - -

      The system does not create a separate thread for each instance of a component. All -components that run in the same process are instantiated in the UI thread, and system calls to -each component are dispatched from that thread. Consequently, methods that respond to system -callbacks (such as {@link android.view.View#onKeyDown onKeyDown()} to report user actions -or a lifecycle callback method) always run in the UI thread of the process.

      - -

      For instance, when the user touches a button on the screen, your app's UI thread dispatches the -touch event to the widget, which in turn sets its pressed state and posts an invalidate request to -the event queue. The UI thread dequeues the request and notifies the widget that it should redraw -itself.

      - -

      When your app performs intensive work in response to user interaction, this single thread model -can yield poor performance unless you implement your application properly. Specifically, if -everything is happening in the UI thread, performing long operations such as network access or -database queries will block the whole UI. When the thread is blocked, no events can be dispatched, -including drawing events. From the user's perspective, the -application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds -(about 5 seconds currently) the user is presented with the infamous "application not -responding" (ANR) dialog. The user might then decide to quit your application and uninstall it -if they are unhappy.

      - -

      Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate -your UI from a worker thread—you must do all manipulation to your user interface from the UI -thread. Thus, there are simply two rules to Android's single thread model:

      - -
        -
      1. Do not block the UI thread -
      2. Do not access the Android UI toolkit from outside the UI thread -
      - -

      Worker threads

      - -

      Because of the single thread model described above, it's vital to the responsiveness of your -application's UI that you do not block the UI thread. If you have operations to perform -that are not instantaneous, you should make sure to do them in separate threads ("background" or -"worker" threads).

      - -

      For example, below is some code for a click listener that downloads an image from a separate -thread and displays it in an {@link android.widget.ImageView}:

      - -
      -public void onClick(View v) {
      -    new Thread(new Runnable() {
      -        public void run() {
      -            Bitmap b = loadImageFromNetwork("http://example.com/image.png");
      -            mImageView.setImageBitmap(b);
      -        }
      -    }).start();
      -}
      -
      - -

      At first, this seems to work fine, because it creates a new thread to handle the network -operation. However, it violates the second rule of the single-threaded model: do not access the -Android UI toolkit from outside the UI thread—this sample modifies the {@link -android.widget.ImageView} from the worker thread instead of the UI thread. This can result in -undefined and unexpected behavior, which can be difficult and time-consuming to track down.

      - -

      To fix this problem, Android offers several ways to access the UI thread from other -threads. Here is a list of methods that can help:

      - -
        -
      • {@link android.app.Activity#runOnUiThread(java.lang.Runnable) -Activity.runOnUiThread(Runnable)}
      • -
      • {@link android.view.View#post(java.lang.Runnable) View.post(Runnable)}
      • -
      • {@link android.view.View#postDelayed(java.lang.Runnable, long) View.postDelayed(Runnable, -long)}
      • -
      - -

      For example, you can fix the above code by using the {@link -android.view.View#post(java.lang.Runnable) View.post(Runnable)} method:

      - -
      -public void onClick(View v) {
      -    new Thread(new Runnable() {
      -        public void run() {
      -            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
      -            mImageView.post(new Runnable() {
      -                public void run() {
      -                    mImageView.setImageBitmap(bitmap);
      -                }
      -            });
      -        }
      -    }).start();
      -}
      -
      - -

      Now this implementation is thread-safe: the network operation is done from a separate thread -while the {@link android.widget.ImageView} is manipulated from the UI thread.

      - -

      However, as the complexity of the operation grows, this kind of code can get complicated and -difficult to maintain. To handle more complex interactions with a worker thread, you might consider -using a {@link android.os.Handler} in your worker thread, to process messages delivered from the UI -thread. Perhaps the best solution, though, is to extend the {@link android.os.AsyncTask} class, -which simplifies the execution of worker thread tasks that need to interact with the UI.

      - - -

      Using AsyncTask

      - -

      {@link android.os.AsyncTask} allows you to perform asynchronous work on your user -interface. It performs the blocking operations in a worker thread and then publishes the results on -the UI thread, without requiring you to handle threads and/or handlers yourself.

      - -

      To use it, you must subclass {@link android.os.AsyncTask} and implement the {@link -android.os.AsyncTask#doInBackground doInBackground()} callback method, which runs in a pool of -background threads. To update your UI, you should implement {@link -android.os.AsyncTask#onPostExecute onPostExecute()}, which delivers the result from {@link -android.os.AsyncTask#doInBackground doInBackground()} and runs in the UI thread, so you can safely -update your UI. You can then run the task by calling {@link android.os.AsyncTask#execute execute()} -from the UI thread.

      - -

      For example, you can implement the previous example using {@link android.os.AsyncTask} this -way:

      - -
      -public void onClick(View v) {
      -    new DownloadImageTask().execute("http://example.com/image.png");
      -}
      -
      -private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      -    /** The system calls this to perform work in a worker thread and
      -      * delivers it the parameters given to AsyncTask.execute() */
      -    protected Bitmap doInBackground(String... urls) {
      -        return loadImageFromNetwork(urls[0]);
      -    }
      -    
      -    /** The system calls this to perform work in the UI thread and delivers
      -      * the result from doInBackground() */
      -    protected void onPostExecute(Bitmap result) {
      -        mImageView.setImageBitmap(result);
      -    }
      -}
      -
      - -

      Now the UI is safe and the code is simpler, because it separates the work into the -part that should be done on a worker thread and the part that should be done on the UI thread.

      - -

      You should read the {@link android.os.AsyncTask} reference for a full understanding on -how to use this class, but here is a quick overview of how it works:

      - -
        -
      • You can specify the type of the parameters, the progress values, and the final -value of the task, using generics
      • -
      • The method {@link android.os.AsyncTask#doInBackground doInBackground()} executes automatically -on a worker thread
      • -
      • {@link android.os.AsyncTask#onPreExecute onPreExecute()}, {@link -android.os.AsyncTask#onPostExecute onPostExecute()}, and {@link -android.os.AsyncTask#onProgressUpdate onProgressUpdate()} are all invoked on the UI thread
      • -
      • The value returned by {@link android.os.AsyncTask#doInBackground doInBackground()} is sent to -{@link android.os.AsyncTask#onPostExecute onPostExecute()}
      • -
      • You can call {@link android.os.AsyncTask#publishProgress publishProgress()} at anytime in {@link -android.os.AsyncTask#doInBackground doInBackground()} to execute {@link -android.os.AsyncTask#onProgressUpdate onProgressUpdate()} on the UI thread
      • -
      • You can cancel the task at any time, from any thread
      • -
      - -

      Caution: Another problem you might encounter when using a worker -thread is unexpected restarts in your activity due to a runtime configuration change -(such as when the user changes the screen orientation), which may destroy your worker thread. To -see how you can persist your task during one of these restarts and how to properly cancel the task -when the activity is destroyed, see the source code for the Shelves sample application.

      - - -

      Thread-safe methods

      - -

      In some situations, the methods you implement might be called from more than one thread, and -therefore must be written to be thread-safe.

      - -

      This is primarily true for methods that can be called remotely—such as methods in a bound service. When a call on a -method implemented in an {@link android.os.IBinder} originates in the same process in which the -{@link android.os.IBinder IBinder} is running, the method is executed in the caller's thread. -However, when the call originates in another process, the method is executed in a thread chosen from -a pool of threads that the system maintains in the same process as the {@link android.os.IBinder -IBinder} (it's not executed in the UI thread of the process). For example, whereas a service's -{@link android.app.Service#onBind onBind()} method would be called from the UI thread of the -service's process, methods implemented in the object that {@link android.app.Service#onBind -onBind()} returns (for example, a subclass that implements RPC methods) would be called from threads -in the pool. Because a service can have more than one client, more than one pool thread can engage -the same {@link android.os.IBinder IBinder} method at the same time. {@link android.os.IBinder -IBinder} methods must, therefore, be implemented to be thread-safe.

      - -

      Similarly, a content provider can receive data requests that originate in other processes. -Although the {@link android.content.ContentResolver} and {@link android.content.ContentProvider} -classes hide the details of how the interprocess communication is managed, {@link -android.content.ContentProvider} methods that respond to those requests—the methods {@link -android.content.ContentProvider#query query()}, {@link android.content.ContentProvider#insert -insert()}, {@link android.content.ContentProvider#delete delete()}, {@link -android.content.ContentProvider#update update()}, and {@link android.content.ContentProvider#getType -getType()}—are called from a pool of threads in the content provider's process, not the UI -thread for the process. Because these methods might be called from any number of threads at the -same time, they too must be implemented to be thread-safe.

      - - -

      Interprocess Communication

      - -

      Android offers a mechanism for interprocess communication (IPC) using remote procedure calls -(RPCs), in which a method is called by an activity or other application component, but executed -remotely (in another process), with any result returned back to the -caller. This entails decomposing a method call and its data to a level the operating system can -understand, transmitting it from the local process and address space to the remote process and -address space, then reassembling and reenacting the call there. Return values are then -transmitted in the opposite direction. Android provides all the code to perform these IPC -transactions, so you can focus on defining and implementing the RPC programming interface.

      - -

      To perform IPC, your application must bind to a service, using {@link -android.content.Context#bindService bindService()}. For more information, see the Services developer guide.

      - - - diff --git a/docs/html/guide/topics/fundamentals/services.jd b/docs/html/guide/topics/fundamentals/services.jd deleted file mode 100644 index 9c38897671c9..000000000000 --- a/docs/html/guide/topics/fundamentals/services.jd +++ /dev/null @@ -1,874 +0,0 @@ -page.title=Services -@jd:body - -
      -
        -

        Quickview

        -
          -
        • A service can run in the background to perform work even while the user is in a different -application
        • -
        • A service can allow other components to bind to it, in order to interact with it and -perform interprocess communication
        • -
        • A service runs in the main thread of the application that hosts it, by default
        • -
        -

        In this document

        -
          -
        1. The Basics
        2. -
            -
          1. Declaring a service in the manifest
          2. -
          -
        3. Creating a Started Service -
            -
          1. Extending the IntentService class
          2. -
          3. Extending the Service class
          4. -
          5. Starting a service
          6. -
          7. Stopping a service
          8. -
          -
        4. -
        5. Creating a Bound Service
        6. -
        7. Sending Notifications to the User
        8. -
        9. Running a Service in the Foreground
        10. -
        11. Managing the Lifecycle of a Service -
            -
          1. Implementing the lifecycle callbacks
          2. -
          -
        12. -
        - -

        Key classes

        -
          -
        1. {@link android.app.Service}
        2. -
        3. {@link android.app.IntentService}
        4. -
        - -

        Samples

        -
          -
        1. {@code - ServiceStartArguments}
        2. -
        3. {@code - LocalService}
        4. -
        - -

        Articles

        -
          -
        1. Multitasking the Android Way
        2. -
        3. Service API changes starting - with Android 2.0
        4. -
        - -

        See also

        -
          -
        1. Bound Services
        2. -
        - -
      - - -

      A {@link android.app.Service} is an application component that can perform -long-running operations in the background and does not provide a user interface. Another -application component can start a service and it will continue to run in the background even if the -user switches to another application. Additionally, a component can bind to a service to -interact with it and even perform interprocess communication (IPC). For example, a service might -handle network transactions, play music, perform file I/O, or interact with a content provider, all -from the background.

      - -

      A service can essentially take two forms:

      - -
      -
      Started
      -
      A service is "started" when an application component (such as an activity) starts it by -calling {@link android.content.Context#startService startService()}. Once started, a service -can run in the background indefinitely, even if the component that started it is destroyed. Usually, -a started service performs a single operation and does not return a result to the caller. -For example, it might download or upload a file over the network. When the operation is done, the -service should stop itself.
      -
      Bound
      -
      A service is "bound" when an application component binds to it by calling {@link -android.content.Context#bindService bindService()}. A bound service offers a client-server -interface that allows components to interact with the service, send requests, get results, and even -do so across processes with interprocess communication (IPC). A bound service runs only as long as -another application component is bound to it. Multiple components can bind to the service at once, -but when all of them unbind, the service is destroyed.
      -
      - -

      Although this documentation generally discusses these two types of services separately, your -service can work both ways—it can be started (to run indefinitely) and also allow binding. -It's simply a matter of whether you implement a couple callback methods: {@link -android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link -android.app.Service#onBind onBind()} to allow binding.

      - -

      Regardless of whether your application is started, bound, or both, any application component -can use the service (even from a separate application), in the same way that any component can use -an activity—by starting it with an {@link android.content.Intent}. However, you can declare -the service as private, in the manifest file, and block access from other applications. This is -discussed more in the section about Declaring the service in the -manifest.

      - -

      Caution: A service runs in the -main thread of its hosting process—the service does not create its own thread -and does not run in a separate process (unless you specify otherwise). This means -that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 -playback or networking), you should create a new thread within the service to do that work. By using -a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the -application's main thread can remain dedicated to user interaction with your activities.

      - - -

      The Basics

      - - - -

      To create a service, you must create a subclass of {@link android.app.Service} (or one -of its existing subclasses). In your implementation, you need to override some callback methods that -handle key aspects of the service lifecycle and provide a mechanism for components to bind to -the service, if appropriate. The most important callback methods you should override are:

      - -
      -
      {@link android.app.Service#onStartCommand onStartCommand()}
      -
      The system calls this method when another component, such as an activity, -requests that the service be started, by calling {@link android.content.Context#startService -startService()}. Once this method executes, the service is started and can run in the -background indefinitely. If you implement this, it is your responsibility to stop the service when -its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link -android.content.Context#stopService stopService()}. (If you only want to provide binding, you don't -need to implement this method.)
      -
      {@link android.app.Service#onBind onBind()}
      -
      The system calls this method when another component wants to bind with the -service (such as to perform RPC), by calling {@link android.content.Context#bindService -bindService()}. In your implementation of this method, you must provide an interface that clients -use to communicate with the service, by returning an {@link android.os.IBinder}. You must always -implement this method, but if you don't want to allow binding, then you should return null.
      -
      {@link android.app.Service#onCreate()}
      -
      The system calls this method when the service is first created, to perform one-time setup -procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or -{@link android.app.Service#onBind onBind()}). If the service is already running, this method is not -called.
      -
      {@link android.app.Service#onDestroy()}
      -
      The system calls this method when the service is no longer used and is being destroyed. -Your service should implement this to clean up any resources such as threads, registered -listeners, receivers, etc. This is the last call the service receives.
      -
      - -

      If a component starts the service by calling {@link -android.content.Context#startService startService()} (which results in a call to {@link -android.app.Service#onStartCommand onStartCommand()}), then the service -remains running until it stops itself with {@link android.app.Service#stopSelf()} or another -component stops it by calling {@link android.content.Context#stopService stopService()}.

      - -

      If a component calls -{@link android.content.Context#bindService bindService()} to create the service (and {@link -android.app.Service#onStartCommand onStartCommand()} is not called), then the service runs -only as long as the component is bound to it. Once the service is unbound from all clients, the -system destroys it.

      - -

      The Android system will force-stop a service only when memory is low and it must recover system -resources for the activity that has user focus. If the service is bound to an activity that has user -focus, then it's less likely to be killed, and if the service is declared to run in the foreground (discussed later), then it will almost never be killed. -Otherwise, if the service was started and is long-running, then the system will lower its position -in the list of background tasks over time and the service will become highly susceptible to -killing—if your service is started, then you must design it to gracefully handle restarts -by the system. If the system kills your service, it restarts it as soon as resources become -available again (though this also depends on the value you return from {@link -android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information -about when the system might destroy a service, see the Processes and Threading -document.

      - -

      In the following sections, you'll see how you can create each type of service and how to use -it from other application components.

      - - - -

      Declaring a service in the manifest

      - -

      Like activities (and other components), you must declare all services in your application's -manifest file.

      - -

      To declare your service, add a {@code <service>} element -as a child of the {@code <application>} -element. For example:

      - -
      -<manifest ... >
      -  ...
      -  <application ... >
      -      <service android:name=".ExampleService" />
      -      ...
      -  </application>
      -</manifest>
      -
      - -

      There are other attributes you can include in the {@code <service>} element to -define properties such as permissions required to start the service and the process in -which the service should run. The {@code android:name} -attribute is the only required attribute—it specifies the class name of the service. Once -you publish your application, you should not change this name, because if you do, you might break -some functionality where explicit intents are used to reference your service (read the blog post, Things -That Cannot Change). - -

      See the {@code <service>} element -reference for more information about declaring your service in the manifest.

      - -

      Just like an activity, a service can define intent filters that allow other components to -invoke the service using implicit intents. By declaring intent filters, components -from any application installed on the user's device can potentially start your service if your -service declares an intent filter that matches the intent another application passes to {@link -android.content.Context#startService startService()}.

      - -

      If you plan on using your service only locally (other applications do not use it), then you -don't need to (and should not) supply any intent filters. Without any intent filters, you must -start the service using an intent that explicitly names the service class. More information -about starting a service is discussed below.

      - -

      Additionally, you can ensure that your service is private to your application only if -you include the {@code android:exported} -attribute and set it to {@code "false"}. This is effective even if your service supplies intent -filters.

      - -

      For more information about creating intent filters for your service, see the Intents and Intent Filters -document.

      - - - -

      Creating a Started Service

      - - - -

      A started service is one that another component starts by calling {@link -android.content.Context#startService startService()}, resulting in a call to the service's -{@link android.app.Service#onStartCommand onStartCommand()} method.

      - -

      When a service is started, it has a lifecycle that's independent of the -component that started it and the service can run in the background indefinitely, even if -the component that started it is destroyed. As such, the service should stop itself when its job -is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it -by calling {@link android.content.Context#stopService stopService()}.

      - -

      An application component such as an activity can start the service by calling {@link -android.content.Context#startService startService()} and passing an {@link android.content.Intent} -that specifies the service and includes any data for the service to use. The service receives -this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand -onStartCommand()} method.

      - -

      For instance, suppose an activity needs to save some data to an online database. The activity can -start a companion service and deliver it the data to save by passing an intent to {@link -android.content.Context#startService startService()}. The service receives the intent in {@link -android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the -database transaction. When the transaction is done, the service stops itself and it is -destroyed.

      - -

      Caution: A services runs in the same process as the application -in which it is declared and in the main thread of that application, by default. So, if your service -performs intensive or blocking operations while the user interacts with an activity from the same -application, the service will slow down activity performance. To avoid impacting application -performance, you should start a new thread inside the service.

      - -

      Traditionally, there are two classes you can extend to create a started service:

      -
      -
      {@link android.app.Service}
      -
      This is the base class for all services. When you extend this class, it's important that -you create a new thread in which to do all the service's work, because the service uses your -application's main thread, by default, which could slow the performance of any activity your -application is running.
      -
      {@link android.app.IntentService}
      -
      This is a subclass of {@link android.app.Service} that uses a worker thread to handle all -start requests, one at a time. This is the best option if you don't require that your service -handle multiple requests simultaneously. All you need to do is implement {@link -android.app.IntentService#onHandleIntent onHandleIntent()}, which receives the intent for each -start request so you can do the background work.
      -
      - -

      The following sections describe how you can implement your service using either one for these -classes.

      - - -

      Extending the IntentService class

      - -

      Because most started services don't need to handle multiple requests simultaneously -(which can actually be a dangerous multi-threading scenario), it's probably best if you -implement your service using the {@link android.app.IntentService} class.

      - -

      The {@link android.app.IntentService} does the following:

      - -
        -
      • Creates a default worker thread that executes all intents delivered to {@link -android.app.Service#onStartCommand onStartCommand()} separate from your application's main -thread.
      • -
      • Creates a work queue that passes one intent at a time to your {@link -android.app.IntentService#onHandleIntent onHandleIntent()} implementation, so you never have to -worry about multi-threading.
      • -
      • Stops the service after all start requests have been handled, so you never have to call -{@link android.app.Service#stopSelf}.
      • -
      • Provides default implementation of {@link android.app.IntentService#onBind onBind()} that -returns null.
      • -
      • Provides a default implementation of {@link android.app.IntentService#onStartCommand -onStartCommand()} that sends the intent to the work queue and then to your {@link -android.app.IntentService#onHandleIntent onHandleIntent()} implementation.
      • -
      - -

      All this adds up to the fact that all you need to do is implement {@link -android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the -client. (Though, you also need to provide a small constructor for the service.)

      - -

      Here's an example implementation of {@link android.app.IntentService}:

      - -
      -public class HelloIntentService extends IntentService {
      -
      -  /** 
      -   * A constructor is required, and must call the super {@link android.app.IntentService#IntentService}
      -   * constructor with a name for the worker thread.
      -   */
      -  public HelloIntentService() {
      -      super("HelloIntentService");
      -  }
      -
      -  /**
      -   * The IntentService calls this method from the default worker thread with
      -   * the intent that started the service. When this method returns, IntentService
      -   * stops the service, as appropriate.
      -   */
      -  @Override
      -  protected void onHandleIntent(Intent intent) {
      -      // Normally we would do some work here, like download a file.
      -      // For our sample, we just sleep for 5 seconds.
      -      long endTime = System.currentTimeMillis() + 5*1000;
      -      while (System.currentTimeMillis() < endTime) {
      -          synchronized (this) {
      -              try {
      -                  wait(endTime - System.currentTimeMillis());
      -              } catch (Exception e) {
      -              }
      -          }
      -      }
      -  }
      -}
      -
      - -

      That's all you need: a constructor and an implementation of {@link -android.app.IntentService#onHandleIntent onHandleIntent()}.

      - -

      If you decide to also override other callback methods, such as {@link -android.app.IntentService#onCreate onCreate()}, {@link -android.app.IntentService#onStartCommand onStartCommand()}, or {@link -android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so -that the {@link android.app.IntentService} can properly handle the life of the worker thread.

      - -

      For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return -the default implementation (which is how the intent gets delivered to {@link -android.app.IntentService#onHandleIntent onHandleIntent()}):

      - -
      -@Override
      -public int onStartCommand(Intent intent, int flags, int startId) {
      -    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
      -    return super.onStartCommand(intent,flags,startId);
      -}
      -
      - -

      Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method -from which you don't need to call the super class is {@link android.app.IntentService#onBind -onBind()} (but you only need to implement that if your service allows binding).

      - -

      In the next section, you'll see how the same kind of service is implemented when extending -the base {@link android.app.Service} class, which is a lot more code, but which might be -appropriate if you need to handle simultaneous start requests.

      - - -

      Extending the Service class

      - -

      As you saw in the previous section, using {@link android.app.IntentService} makes your -implementation of a started service very simple. If, however, you require your service to -perform multi-threading (instead of processing start requests through a work queue), then you -can extend the {@link android.app.Service} class to handle each intent.

      - -

      For comparison, the following example code is an implementation of the {@link -android.app.Service} class that performs the exact same work as the example above using {@link -android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the -job and processes only one request at a time.

      - -
      -public class HelloService extends Service {
      -  private Looper mServiceLooper;
      -  private ServiceHandler mServiceHandler;
      -
      -  // Handler that receives messages from the thread
      -  private final class ServiceHandler extends Handler {
      -      public ServiceHandler(Looper looper) {
      -          super(looper);
      -      }
      -      @Override
      -      public void handleMessage(Message msg) {
      -          // Normally we would do some work here, like download a file.
      -          // For our sample, we just sleep for 5 seconds.
      -          long endTime = System.currentTimeMillis() + 5*1000;
      -          while (System.currentTimeMillis() < endTime) {
      -              synchronized (this) {
      -                  try {
      -                      wait(endTime - System.currentTimeMillis());
      -                  } catch (Exception e) {
      -                  }
      -              }
      -          }
      -          // Stop the service using the startId, so that we don't stop
      -          // the service in the middle of handling another job
      -          stopSelf(msg.arg1);
      -      }
      -  }
      -
      -  @Override
      -  public void onCreate() {
      -    // Start up the thread running the service.  Note that we create a
      -    // separate thread because the service normally runs in the process's
      -    // main thread, which we don't want to block.  We also make it
      -    // background priority so CPU-intensive work will not disrupt our UI.
      -    HandlerThread thread = new HandlerThread("ServiceStartArguments",
      -            Process.THREAD_PRIORITY_BACKGROUND);
      -    thread.start();
      -    
      -    // Get the HandlerThread's Looper and use it for our Handler 
      -    mServiceLooper = thread.getLooper();
      -    mServiceHandler = new ServiceHandler(mServiceLooper);
      -  }
      -
      -  @Override
      -  public int onStartCommand(Intent intent, int flags, int startId) {
      -      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
      -
      -      // For each start request, send a message to start a job and deliver the
      -      // start ID so we know which request we're stopping when we finish the job
      -      Message msg = mServiceHandler.obtainMessage();
      -      msg.arg1 = startId;
      -      mServiceHandler.sendMessage(msg);
      -      
      -      // If we get killed, after returning from here, restart
      -      return START_STICKY;
      -  }
      -
      -  @Override
      -  public IBinder onBind(Intent intent) {
      -      // We don't provide binding, so return null
      -      return null;
      -  }
      -  
      -  @Override
      -  public void onDestroy() {
      -    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
      -  }
      -}
      -
      - -

      As you can see, it's a lot more work than using {@link android.app.IntentService}.

      - -

      However, because you handle each call to {@link android.app.Service#onStartCommand -onStartCommand()} yourself, you can perform multiple requests simultaneously. That's not what -this example does, but if that's what you want, then you can create a new thread for each -request and run them right away (instead of waiting for the previous request to finish).

      - -

      Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an -integer. The integer is a value that describes how the system should continue the service in the -event that the system kills it (as discussed above, the default implementation for {@link -android.app.IntentService} handles this for you, though you are able to modify it). The return value -from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following -constants:

      - -
      -
      {@link android.app.Service#START_NOT_STICKY}
      -
      If the system kills the service after {@link android.app.Service#onStartCommand -onStartCommand()} returns, do not recreate the service, unless there are pending -intents to deliver. This is the safest option to avoid running your service when not necessary -and when your application can simply restart any unfinished jobs.
      -
      {@link android.app.Service#START_STICKY}
      -
      If the system kills the service after {@link android.app.Service#onStartCommand -onStartCommand()} returns, recreate the service and call {@link -android.app.Service#onStartCommand onStartCommand()}, but do not redeliver the last intent. -Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a -null intent, unless there were pending intents to start the service, in which case, -those intents are delivered. This is suitable for media players (or similar services) that are not -executing commands, but running indefinitely and waiting for a job.
      -
      {@link android.app.Service#START_REDELIVER_INTENT}
      -
      If the system kills the service after {@link android.app.Service#onStartCommand -onStartCommand()} returns, recreate the service and call {@link -android.app.Service#onStartCommand onStartCommand()} with the last intent that was delivered to the -service. Any pending intents are delivered in turn. This is suitable for services that are -actively performing a job that should be immediately resumed, such as downloading a file.
      -
      -

      For more details about these return values, see the linked reference documentation for each -constant.

      - - - -

      Starting a Service

      - -

      You can start a service from an activity or other application component by passing an -{@link android.content.Intent} (specifying the service to start) to {@link -android.content.Context#startService startService()}. The Android system calls the service's {@link -android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link -android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand -onStartCommand()} directly.)

      - -

      For example, an activity can start the example service in the previous section ({@code -HelloSevice}) using an explicit intent with {@link android.content.Context#startService -startService()}:

      - -
      -Intent intent = new Intent(this, HelloService.class);
      -startService(intent);
      -
      - -

      The {@link android.content.Context#startService startService()} method returns immediately and -the Android system calls the service's {@link android.app.Service#onStartCommand -onStartCommand()} method. If the service is not already running, the system first calls {@link -android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand -onStartCommand()}.

      - -

      If the service does not also provide binding, the intent delivered with {@link -android.content.Context#startService startService()} is the only mode of communication between the -application component and the service. However, if you want the service to send a result back, then -the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast -(with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service -in the {@link android.content.Intent} that starts the service. The service can then use the -broadcast to deliver a result.

      - -

      Multiple requests to start the service result in multiple corresponding calls to the service's -{@link android.app.Service#onStartCommand onStartCommand()}. However, only one request to stop -the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link -android.content.Context#stopService stopService()}) is required to stop it.

      - - -

      Stopping a service

      - -

      A started service must manage its own lifecycle. That is, the system does not stop or -destroy the service unless it must recover system memory and the service -continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So, -the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another -component can stop it by calling {@link android.content.Context#stopService stopService()}.

      - -

      Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link -android.content.Context#stopService stopService()}, the system destroys the service as soon as -possible.

      - -

      However, if your service handles multiple requests to {@link -android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the -service when you're done processing a start request, because you might have since received a new -start request (stopping at the end of the first request would terminate the second one). To avoid -this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to -stop the service is always based on the most recent start request. That is, when you call {@link -android.app.Service#stopSelf(int)}, you pass the ID of the start request (the startId -delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request -corresponds. Then if the service received a new start request before you were able to call {@link -android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.

      - -

      Caution: It's important that your application stops its services -when it's done working, to avoid wasting system resources and consuming battery power. If necessary, -other components can stop the service by calling {@link -android.content.Context#stopService stopService()}. Even if you enable binding for the service, -you must always stop the service yourself if it ever received a call to {@link -android.app.Service#onStartCommand onStartCommand()}.

      - -

      For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.

      - - - -

      Creating a Bound Service

      - -

      A bound service is one that allows application components to bind to it by calling {@link -android.content.Context#bindService bindService()} in order to create a long-standing connection -(and generally does not allow components to start it by calling {@link -android.content.Context#startService startService()}).

      - -

      You should create a bound service when you want to interact with the service from activities -and other components in your application or to expose some of your application's functionality to -other applications, through interprocess communication (IPC).

      - -

      To create a bound service, you must implement the {@link -android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that -defines the interface for communication with the service. Other application components can then call -{@link android.content.Context#bindService bindService()} to retrieve the interface and -begin calling methods on the service. The service lives only to serve the application component that -is bound to it, so when there are no components bound to the service, the system destroys it -(you do not need to stop a bound service in the way you must when the service is started -through {@link android.app.Service#onStartCommand onStartCommand()}).

      - -

      To create a bound service, the first thing you must do is define the interface that specifies -how a client can communicate with the service. This interface between the service -and a client must be an implementation of {@link android.os.IBinder} and is what your service must -return from the {@link android.app.Service#onBind -onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin -interacting with the service through that interface.

      - -

      Multiple clients can bind to the service at once. When a client is done interacting with the -service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once -there are no clients bound to the service, the system destroys the service.

      - -

      There are multiple ways to implement a bound service and the implementation is more -complicated than a started service, so the bound service discussion appears in a separate -document about Bound Services.

      - - - -

      Sending Notifications to the User

      - -

      Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.

      - -

      A toast notification is a message that appears on the surface of the current window for a -moment then disappears, while a status bar notification provides an icon in the status bar with a -message, which the user can select in order to take an action (such as start an activity).

      - -

      Usually, a status bar notification is the best technique when some background work has completed -(such as a file completed -downloading) and the user can now act on it. When the user selects the notification from the -expanded view, the notification can start an activity (such as to view the downloaded file).

      - -

      See the Toast Notifications or Status Bar Notifications -developer guides for more information.

      - - - -

      Running a Service in the Foreground

      - -

      A foreground service is a service that's considered to be something the -user is actively aware of and thus not a candidate for the system to kill when low on memory. A -foreground service must provide a notification for the status bar, which is placed under the -"Ongoing" heading, which means that the notification cannot be dismissed unless the service is -either stopped or removed from the foreground.

      - -

      For example, a music player that plays music from a service should be set to run in the -foreground, because the user is explicitly aware -of its operation. The notification in the status bar might indicate the current song and allow -the user to launch an activity to interact with the music player.

      - -

      To request that your service run in the foreground, call {@link -android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer -that uniquely identifies the notification and the {@link -android.app.Notification} for the status bar. For example:

      - -
      -Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
      -        System.currentTimeMillis());
      -Intent notificationIntent = new Intent(this, ExampleActivity.class);
      -PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
      -notification.setLatestEventInfo(this, getText(R.string.notification_title),
      -        getText(R.string.notification_message), pendingIntent);
      -startForeground(ONGOING_NOTIFICATION, notification);
      -
      - - -

      To remove the service from the foreground, call {@link -android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating -whether to remove the status bar notification as well. This method does not stop the -service. However, if you stop the service while it's still running in the foreground, then the -notification is also removed.

      - -

      Note: The methods {@link -android.app.Service#startForeground startForeground()} and {@link -android.app.Service#stopForeground stopForeground()} were introduced in Android 2.0 (API Level -5). In order to run your service in the foreground on older versions of the platform, you must -use the previous {@code setForeground()} method—see the {@link -android.app.Service#startForeground startForeground()} documentation for information about how -to provide backward compatibility.

      - -

      For more information about notifications, see Creating Status Bar -Notifications.

      - - - -

      Managing the Lifecycle of a Service

      - -

      The lifecycle of a service is much simpler than that of an activity. However, it's even more important -that you pay close attention to how your service is created and destroyed, because a service -can run in the background without the user being aware.

      - -

      The service lifecycle—from when it's created to when it's destroyed—can follow two -different paths:

      - -
        -
      • A started service -

        The service is created when another component calls {@link -android.content.Context#startService startService()}. The service then runs indefinitely and must -stop itself by calling {@link -android.app.Service#stopSelf() stopSelf()}. Another component can also stop the -service by calling {@link android.content.Context#stopService -stopService()}. When the service is stopped, the system destroys it..

      • - -
      • A bound service -

        The service is created when another component (a client) calls {@link -android.content.Context#bindService bindService()}. The client then communicates with the service -through an {@link android.os.IBinder} interface. The client can close the connection by calling -{@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to -the same service and when all of them unbind, the system destroys the service. (The service -does not need to stop itself.)

      • -
      - -

      These two paths are not entirely separate. That is, you can bind to a service that was already -started with {@link android.content.Context#startService startService()}. For example, a background -music service could be started by calling {@link android.content.Context#startService -startService()} with an {@link android.content.Intent} that identifies the music to play. Later, -possibly when the user wants to exercise some control over the player or get information about the -current song, an activity can bind to the service by calling {@link -android.content.Context#bindService bindService()}. In cases like this, {@link -android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf -stopSelf()} does not actually stop the service until all clients unbind.

      - - -

      Implementing the lifecycle callbacks

      - -

      Like an activity, a service has lifecycle callback methods that you can implement to monitor -changes in the service's state and perform work at the appropriate times. The following skeleton -service demonstrates each of the lifecycle methods:

      - - -
      - -

      Figure 2. The service lifecycle. The diagram on the left -shows the lifecycle when the service is created with {@link android.content.Context#startService -startService()} and the diagram on the right shows the lifecycle when the service is created -with {@link android.content.Context#bindService bindService()}.

      -
      - -
      -public class ExampleService extends Service {
      -    int mStartMode;       // indicates how to behave if the service is killed
      -    IBinder mBinder;      // interface for clients that bind
      -    boolean mAllowRebind; // indicates whether onRebind should be used
      -
      -    @Override
      -    public void {@link android.app.Service#onCreate onCreate}() {
      -        // The service is being created
      -    }
      -    @Override
      -    public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) {
      -        // The service is starting, due to a call to {@link android.content.Context#startService startService()}
      -        return mStartMode;
      -    }
      -    @Override
      -    public IBinder {@link android.app.Service#onBind onBind}(Intent intent) {
      -        // A client is binding to the service with {@link android.content.Context#bindService bindService()}
      -        return mBinder;
      -    }
      -    @Override
      -    public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) {
      -        // All clients have unbound with {@link android.content.Context#unbindService unbindService()}
      -        return mAllowRebind;
      -    }
      -    @Override
      -    public void {@link android.app.Service#onRebind onRebind}(Intent intent) {
      -        // A client is binding to the service with {@link android.content.Context#bindService bindService()},
      -        // after onUnbind() has already been called
      -    }
      -    @Override
      -    public void {@link android.app.Service#onDestroy onDestroy}() {
      -        // The service is no longer used and is being destroyed
      -    }
      -}
      -
      - -

      Note: Unlike the activity lifecycle callback methods, you are -not required to call the superclass implementation of these callback methods.

      - -

      By implementing these methods, you can monitor two nested loops of the service's lifecycle:

      - -
        -
      • The entire lifetime of a service happens between the time {@link -android.app.Service#onCreate onCreate()} is called and the time {@link -android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in -{@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link -android.app.Service#onDestroy onDestroy()}. For example, a -music playback service could create the thread where the music will be played in {@link -android.app.Service#onCreate onCreate()}, then stop the thread in {@link -android.app.Service#onDestroy onDestroy()}. - -

        The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy -onDestroy()} methods are called for all services, whether -they're created by {@link android.content.Context#startService startService()} or {@link -android.content.Context#bindService bindService()}.

      • - -
      • The active lifetime of a service begins with a call to either {@link -android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}. -Each method is handed the {@link -android.content.Intent} that was passed to either {@link android.content.Context#startService -startService()} or {@link android.content.Context#bindService bindService()}, respectively. -

        If the service is started, the active lifetime ends the same time that the entire lifetime -ends (the service is still active even after {@link android.app.Service#onStartCommand -onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link -android.app.Service#onUnbind onUnbind()} returns.

        -
      • -
      - -

      Note: Although a started service is stopped by a call to -either {@link android.app.Service#stopSelf stopSelf()} or {@link -android.content.Context#stopService stopService()}, there is not a respective callback for the -service (there's no {@code onStop()} callback). So, unless the service is bound to a client, -the system destroys it when the service is stopped—{@link -android.app.Service#onDestroy onDestroy()} is the only callback received.

      - -

      Figure 2 illustrates the typical callback methods for a service. Although the figure separates -services that are created by {@link android.content.Context#startService startService()} from those -created by {@link android.content.Context#bindService bindService()}, keep -in mind that any service, no matter how it's started, can potentially allow clients to bind to it. -So, a service that was initially started with {@link android.app.Service#onStartCommand -onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) -can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls -{@link android.content.Context#bindService bindService()}).

      - -

      For more information about creating a service that provides binding, see the Bound Services document, -which includes more information about the {@link android.app.Service#onRebind onRebind()} -callback method in the section about Managing the Lifecycle of -a Bound Service.

      - - - diff --git a/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd b/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd deleted file mode 100644 index 0880614ae646..000000000000 --- a/docs/html/guide/topics/fundamentals/tasks-and-back-stack.jd +++ /dev/null @@ -1,596 +0,0 @@ -page.title=Tasks and Back Stack -parent.title=Activities -parent.link=activities.html -@jd:body - -
      -
      -

      Quickview

      -
        -
      • All activities belong to a task
      • -
      • A task contains a collection of activities in the order in which the user interacts with -them
      • -
      • Tasks can move to the background and retain the state of each activity in order for users -to perform other tasks without losing their work
      • -
      - -

      In this document

      -
        -
      1. Saving Activity State
      2. -
      3. Managing Tasks -
          -
        1. Defining launch modes
        2. -
        3. Handling affinities
        4. -
        5. Clearing the back stack
        6. -
        7. Starting a task
        8. -
        -
      4. -
      - -

      Articles

      -
        -
      1. Multitasking the Android Way
      2. -
      - -

      See also

      -
        -
      1. Android Design: -Navigation
      2. -
      3. Application Lifecycle video
      4. -
      5. {@code <activity>} manifest -element
      6. -
      -
      -
      - - -

      An application usually contains multiple activities. Each activity -should be designed around a specific kind of action the user can perform and can start other -activities. For example, an email application might have one activity to show a list of new email. -When the user selects an email, a new activity opens to view that email.

      - -

      An activity can even start activities that exist in other applications on the device. For -example, if your application wants to send an email, you can define an intent to perform a "send" -action and include some data, such as an email address and a message. An activity from another -application that declares itself to handle this kind of intent then opens. In this case, the intent -is to send an email, so an email application's "compose" activity starts (if multiple activities -support the same intent, then the system lets the user select which one to use). When the email is -sent, your activity resumes and it seems as if the email activity was part of your application. Even -though the activities may be from different applications, Android maintains this seamless user -experience by keeping both activities in the same task.

      - -

      A task is a collection of activities that users interact with -when performing a certain job. The activities are arranged in a stack (the "back stack"), in the -order in which each activity is opened.

      - - - -

      The device Home screen is the starting place for most tasks. When the user touches an icon in the -application -launcher (or a shortcut on the Home screen), that application's task comes to the foreground. If no -task exists for the application (the application has not been used recently), then a new task -is created and the "main" activity for that application opens as the root activity in the stack.

      - -

      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 -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 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.

      - - -

      Figure 1. A representation of how each new activity in a -task adds an item to the back stack. When the user presses the Back button, the current -activity is -destroyed and the previous activity resumes.

      - - -

      If the user continues to press Back, 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.

      - -
      -

      Figure 2. Two tasks: Task B receives user interaction -in the foreground, while Task A is in the background, waiting to be resumed.

      -
      -
      -

      Figure 3. A single activity is instantiated multiple times.

      -
      - -

      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 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 -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 -that application, the user returns Home again and selects the application that originally -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 button to reveal recent tasks -and selecting -one). This is an example of multitasking on Android.

      - -

      Note: Multiple tasks can be held in the background at once. -However, if the user is running many background tasks at the same time, the system might begin -destroying background activities in order to recover memory, causing the activity states to be lost. -See the following section about Activity state.

      - -

      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 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 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 Managing Tasks.

      - - -

      To summarize the default behavior for activities and tasks:

      - -
        -
      • 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 button while in Activity B, Activity A resumes with its state -restored.
      • -
      • When the user leaves a task by pressing the Home 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.
      • -
      • If the user presses the Back 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 -does not retain the activity's state.
      • -
      • Activities can be instantiated multiple times, even from other tasks.
      • -
      - - -
      -

      Navigation Design

      -

      For more about how app navigation works on Android, read Android Design's Navigation guide.

      -
      - - -

      Saving Activity State

      - -

      As discussed above, the system's default behavior preserves the state of an activity when it is -stopped. This way, when users navigate back to a previous activity, its user interface appears -the way they left it. However, you can—and should—proactively retain -the state of your activities using callback methods, in case the activity is destroyed and must -be recreated.

      - -

      When the system stops one of your activities (such as when a new activity starts or the task -moves to the background), the system might destroy that activity completely if it needs to recover -system memory. When this happens, information about the activity state is lost. If this happens, the -system still -knows that the activity has a place in the back stack, but when the activity is brought to the -top of the stack the system must recreate it (rather than resume it). In order to -avoid losing the user's work, you should proactively retain it by implementing the {@link -android.app.Activity#onSaveInstanceState onSaveInstanceState()} callback -methods in your activity.

      - -

      For more information about how to save your activity state, see the Activities -document.

      - - - -

      Managing Tasks

      - -

      The way Android manages tasks and the back stack, as described above—by placing all -activities started in succession in the same task and in a "last in, first out" stack—works -great for most applications and you shouldn't have to worry about how your activities are associated -with tasks or how they exist in the back stack. However, you might decide that you want to interrupt -the normal behavior. Perhaps you want an activity in your application to begin a new task when it is -started (instead of being placed within the current task); or, when you start an activity, you want -to bring forward an existing instance of it (instead of creating a new -instance on top of the back stack); or, you want your back stack to be cleared of all -activities except for the root activity when the user leaves the task.

      - -

      You can do these things and more, with attributes in the -{@code -<activity>} manifest element and with flags in the intent that you pass to {@link -android.app.Activity#startActivity startActivity()}.

      - -

      In this regard, the the principal {@code <activity>} -attributes you can use are:

      - - - -

      And the principal intent flags you can use are:

      - -
        -
      • {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}
      • -
      • {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}
      • -
      • {@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}
      • -
      - -

      In the following sections, you'll see how you can use these manifest attributes and intent -flags to define how activities are associated with tasks and how the behave in the back stack.

      - - -

      Caution: 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 button. -Be sure -to test for navigation behaviors that might conflict with the user's expected behavior.

      - - -

      Defining launch modes

      - -

      Launch modes allow you to define how a new instance of an activity is associated with the -current task. You can define different launch modes in two ways:

      -
        -
      • Using the manifest file -

        When you declare an activity in your manifest file, you can specify how the activity -should associate with tasks when it starts.

      • -
      • Using Intent flags -

        When you call {@link android.app.Activity#startActivity startActivity()}, -you can include a flag in the {@link android.content.Intent} that declares how (or -whether) the new activity should associate with the current task.

      • -
      - -

      As such, if Activity A starts Activity B, Activity B can define in its manifest how it -should associate with the current task (if at all) and Activity A can also request how Activity -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).

      - -

      Note: 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.

      - - -

      Using the manifest file

      - -

      When declaring an activity in your manifest file, you can specify how the activity should -associate with a task using the {@code <activity>} -element's {@code -launchMode} attribute.

      - -

      The {@code -launchMode} attribute specifies an instruction on how the activity should be launched into a -task. There are four different launch modes you can assign to the -launchMode -attribute:

      - -
      -
      {@code "standard"} (the default mode)
      -
      Default. The system creates a new instance of the activity in the task from -which it was started and routes the intent to it. The activity can be instantiated multiple times, -each instance can belong to different tasks, and one task can have multiple instances.
      -
      {@code "singleTop"}
      -
      If an instance of the activity already exists at the top of the current task, the system -routes the intent to that instance through a call to its {@link -android.app.Activity#onNewIntent onNewIntent()} method, rather than creating a new instance of the -activity. The activity can be instantiated multiple times, each instance can -belong to different tasks, and one task can have multiple instances (but only if the the -activity at the top of the back stack is not an existing instance of the activity). -

      For example, suppose a task's back stack consists of root activity A with activities B, C, -and D on top (the stack is A-B-C-D; D is on top). An intent arrives for an activity of type D. -If D has the default {@code "standard"} launch mode, a new instance of the class is launched and the -stack becomes A-B-C-D-D. However, if D's launch mode is {@code "singleTop"}, the existing instance -of D receives the intent through {@link -android.app.Activity#onNewIntent onNewIntent()}, because it's at the top of the stack—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"}.

      -

      Note: When a new instance of an activity is created, -the user can press the Back button to return to the previous activity. But when an existing -instance of -an activity handles a new intent, the user cannot press the Back button to return to the -state of -the activity before the new intent arrived in {@link android.app.Activity#onNewIntent -onNewIntent()}.

      -
      - -
      {@code "singleTask"}
      -
      The system creates a new task and instantiates the activity at the root of the new task. -However, if an instance of the activity already exists in a separate task, the system routes the -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. -

      Note: Although the activity starts in a new task, the -Back button still returns the user to the previous activity.

      -
      {@code "singleInstance"}.
      -
      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; -any activities started by this one open in a separate task.
      -
      - - -

      As another example, the Android Browser application declares that the web browser activity should -always open in its own task—by specifying the {@code singleTask} launch mode in the {@code <activity>} element. -This means that if your application issues an -intent to open the Android Browser, its activity is not placed in the same -task as your application. Instead, either a new task starts for the Browser or, if the Browser -already has a task running in the background, that task is brought forward to handle the new -intent.

      - -

      Regardless of whether an activity starts in a new task or in the same task as the activity that -started it, the Back 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.

      - - -

      Figure 4. 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, then the entire back stack also comes -forward, on top of the current task.

      - -

      For more information about using launch modes in the manifest file, see the -<activity> -element documentation, where the {@code launchMode} attribute and the accepted values are -discussed more.

      - -

      Note: The behaviors that you specify for your activity with the {@code launchMode} attribute -can be overridden by flags included with the intent that start your activity, as discussed in the -next section.

      - - - -

      Using Intent flags

      - -

      When starting an activity, you can modify the default association of an activity to its task -by including flags in the intent that you deliver to {@link -android.app.Activity#startActivity startActivity()}. The flags you can use to modify the -default behavior are:

      - -

      -

      {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}
      -
      Start the activity in a new task. If a task is already running for the activity you are now -starting, that task is brought to the foreground with its last state restored and the activity -receives the new intent in {@link android.app.Activity#onNewIntent onNewIntent()}. -

      This produces the same behavior as the {@code "singleTask"} {@code launchMode} value, -discussed in the previous section.

      -
      {@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}
      -
      If the activity being started is the current activity (at the top of the back stack), then -the existing instance receives a call to {@link android.app.Activity#onNewIntent onNewIntent()}, -instead of creating a new instance of the activity. -

      This produces the same behavior as the {@code "singleTop"} {@code launchMode} value, -discussed in the previous section.

      -
      {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP}
      -
      If the activity being started is already running in the current task, then instead -of launching a new instance of that activity, all of the other activities on top of it are -destroyed and this intent is delivered to the resumed instance of the activity (now on top), -through {@link android.app.Activity#onNewIntent onNewIntent()}). -

      There is no value for the {@code launchMode} -attribute that produces this behavior.

      -

      {@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction with {@code -FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are a way of locating an existing activity -in another task and putting it in a position where it can respond to the intent.

      -

      Note: If the launch mode of the designated activity is {@code -"standard"}, it too is removed from the stack and a new instance is launched in its place to handle -the incoming intent. That's because a new instance is always created for a new intent when the -launch mode is {@code "standard"}.

      -
      - - - - - - -

      Handling affinities

      - -

      The affinity indicates which task an activity prefers to belong to. By default, all the -activities from the same application have an affinity for each other. So, by default, all -activities in the same application prefer to be in the same task. However, you can modify -the default affinity for an activity. Activities defined in -different applications can share an affinity, or activities defined in the same application can be -assigned different task affinities.

      - -

      You can modify the affinity for any given activity with the {@code taskAffinity} attribute -of the {@code <activity>} -element.

      - -

      The {@code taskAffinity} -attribute takes a string value, which must be unique from the default package name -declared in the {@code -<manifest>} element, because the system uses that name to identify the default task -affinity for the application.

      - -

      The affinity comes into play in two circumstances:

      -
        -
      • When the intent that launches an activity contains the {@link -android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag. - -

        A new activity is, by default, launched into the task of the activity -that called {@link android.app.Activity#startActivity startActivity()}. It's pushed onto the same -back stack as the caller. However, if the intent passed to {@link -android.app.Activity#startActivity startActivity()} contains the {@link -android.content.Intent#FLAG_ACTIVITY_NEW_TASK} -flag, the system looks for a different task to house the new activity. Often, it's a new task. -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.

        - -

        If this flag causes an activity to begin a new task and the user presses the Home 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 -android.app.Activity#startActivity startActivity()}. If you have an activity that can be invoked by -an external entity that might use this flag, take care that the user has a independent way to get -back to the task that's started, such as with a launcher icon (the root activity of the task -has a {@link android.content.Intent#CATEGORY_LAUNCHER} intent filter; see the Starting a task section below).

        -
      • - -
      • When an activity has its {@code -allowTaskReparenting} attribute set to {@code "true"}. -

        In this case, the activity can move from the task it starts to the task it has an affinity -for, when that task comes to the foreground.

        -

        For example, suppose that an activity that reports weather conditions in selected cities is -defined as part of a travel application. It has the same affinity as other activities in the same -application (the default application affinity) and it allows re-parenting with this attribute. -When one of your activities starts the weather reporter activity, it initially belongs to the same -task as your activity. However, when the travel application's task comes to the foreground, the -weather reporter activity is reassigned to that task and displayed within it.

        -
      • -
      - -

      Tip: If an {@code .apk} file contains more than one "application" -from the user's point of view, you probably want to use the {@code taskAffinity} -attribute to assign different affinities to the activities associated with each "application".

      - - - -

      Clearing the back stack

      - -

      If the user leaves a task for a long time, the system clears the task of all activities except -the root activity. When the user returns to the task again, only the root activity is restored. -The system behaves this way, because, after an extended amount of time, users likely have abandoned -what they were doing before and are returning to the task to begin something new.

      - -

      There are some activity attributes that you can use to modify this behavior:

      - -
      -
      alwaysRetainTaskState -
      -
      If this attribute is set to {@code "true"} in the root activity of a task, -the default behavior just described does not happen. -The task retains all activities in its stack even after a long period.
      - -
      clearTaskOnLaunch
      -
      If this attribute is set to {@code "true"} in the root activity of a task, -the stack is cleared down to the root activity whenever the user leaves the task -and returns to it. In other words, it's the opposite of {@code -alwaysRetainTaskState}. The user always returns to the task in its -initial state, even after a leaving the task for only a moment.
      - -
      finishOnTaskLaunch -
      -
      This attribute is like {@code clearTaskOnLaunch}, -but it operates on a -single activity, not an entire task. It can also cause any activity to go -away, including the root activity. When it's set to {@code "true"}, the -activity remains part of the task only for the current session. If the user -leaves and then returns to the task, it is no longer present.
      -
      - - - - -

      Starting a task

      - -

      You can set up an activity as the entry point for a task by giving it an intent filter with -{@code "android.intent.action.MAIN"} as the specified action and {@code -"android.intent.category.LAUNCHER"} as the specified category. For example:

      - -
      -<activity ... >
      -    <intent-filter ... >
      -        <action android:name="android.intent.action.MAIN" />
      -        <category android:name="android.intent.category.LAUNCHER" />
      -    </intent-filter>
      -    ...
      -</activity>
      -
      - -

      An intent filter of this kind causes an icon and label for the -activity to be displayed in the application launcher, giving users a way to launch the activity and -to return to the task that it creates any time after it has been launched. -

      - -

      This second ability is important: Users must be able to leave a task and then come back to it -later using this activity launcher. For this reason, the two launch -modes that mark activities as always initiating a task, {@code "singleTask"} and "{@code -"singleInstance"}, should be used only when the activity has an {@link -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 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. -

      - -

      For those cases where you don't want the user to be able to return to an activity, set the - <activity> element's -{@code -finishOnTaskLaunch} to {@code "true"} (see Clearing the stack).

      - - - - diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd index 5cf1a59b2232..d842cb9e611d 100644 --- a/docs/html/guide/topics/graphics/2d-graphics.jd +++ b/docs/html/guide/topics/graphics/2d-graphics.jd @@ -476,7 +476,7 @@ allowed. do.

      -

      The Draw 9-patch tool offers +

      The Draw 9-patch tool offers an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor. It even raises warnings if the region you've defined for the stretchable area is at risk of producing drawing artifacts as a result of the pixel replication. diff --git a/docs/html/guide/topics/graphics/animation.jd b/docs/html/guide/topics/graphics/animation.jd deleted file mode 100644 index 561369d2fe86..000000000000 --- a/docs/html/guide/topics/graphics/animation.jd +++ /dev/null @@ -1,64 +0,0 @@ -page.title=Animation -@jd:body - -

      - -

      The Android framework provides two animation systems: property animation - (introduced in Android 3.0) and view animation. Both animation systems are viable options, - but the property animation system, in general, is the preferred method to use, because it - is more flexible and offers more features. In addition to these two systems, you can utilize Drawable -animation, which allows you to load drawable resources and display them one frame after -another.

      - -

      The view animation system provides the capability to only animate {@link android.view.View} -objects, so if you wanted to animate non-{@link android.view.View} objects, you have to implement -your own code to do so. The view animation system is also constrained in the fact that it only -exposes a few aspects of a {@link android.view.View} object to animate, such as the scaling and -rotation of a View but not the background color, for instance.

      - -

      Another disadvantage of the view animation system is that it only modified where the - View was drawn, and not the actual View itself. For instance, if you animated a button to move - across the screen, the button draws correctly, but the actual location where you can click the - button does not change, so you have to implement your own logic to handle this.

      - -

      With the property animation system, these constraints are completely removed, and you can animate - any property of any object (Views and non-Views) and the object itself is actually modified. - The property animation system is also more robust in the way it carries out animation. At - a high level, you assign animators to the properties that you want to animate, such as color, - position, or size and can define aspects of the animation such as interpolation and - synchronization of multiple animators.

      - -

      The view animation system, however, takes less time to setup and requires less code to write. - If view animation accomplishes everything that you need to do, or if your existing code already - works the way you want, there is no need to use the property animation system. It also might - make sense to use both animation systems for different situations if the use case arises.

      - -
      -
      Property -Animation
      -
      Introduced in Android 3.0 (API level 11), the property animation system lets you -animate properties of any object, including ones that are not rendered to the screen. The system is -extensible and lets you animate properties of custom types as well.
      - -
      View -Animation
      -
      View Animation is the older system and can only be used for Views. It is relatively easy to -setup and offers enough capabilities to meet many application's needs.
      -
      - -
      Drawable -Animation
      -
      Drawable animation involves displaying {@link android.graphics.drawable.Drawable} resources one -after another, like a roll of film. This method of animation is useful if you want to animate -things that are easier to represent with Drawable resources, such as a progression of bitmaps.
      diff --git a/docs/html/guide/topics/graphics/index.jd b/docs/html/guide/topics/graphics/index.jd index ab623c269100..17f630994952 100644 --- a/docs/html/guide/topics/graphics/index.jd +++ b/docs/html/guide/topics/graphics/index.jd @@ -1,51 +1,49 @@ -page.title=Graphics -@jd:body - - - -

      When writing an application, it's important to consider exactly what your graphical demands will be. -Varying graphical tasks are best accomplished with varying techniques. For example, graphics and animations -for a rather static application should be implemented much differently than graphics and animations -for an interactive game. Here, we'll discuss a few of the options you have for drawing graphics -on Android and which tasks they're best suited for. -

      +page.title=Animation and Graphics +page.landing=true +page.landing.intro=Make your apps look and perform their best using Android's powerful graphics features such as OpenGL, hardware acceleration, and built-in UI animations. +page.landing.image= -
      -
      Canvas and -Drawables
      -
      Android provides a set of {@link android.view.View} widgets that provide general functionality -for a wide array of user interfaces. You can also extend these widgets to modify the way they -look or behave. In addition, you can do your own custom 2D rendering using the various drawing -methods contained in the {@link android.graphics.Canvas} class or create {@link -android.graphics.drawable.Drawable} objects for things such as textured buttons or frame-by-frame -animations.
      +@jd:body -
      Hardware -Acceleration
      -
      Beginning in Android 3.0, you can hardware accelerate the majority of -the drawing done by the Canvas APIs to further increase their performance.
      +
      -
      OpenGL
      -
      Android supports OpenGL ES 1.0 and 2.0, with Android framework APIs as well as natively -with the Native Development Kit (NDK). Using the framework APIs is desireable when you want to add a -few graphical enhancements to your application that are not supported with the Canvas APIs, or if -you desire platform independence and don't demand high performance. There is a performance hit in -using the framework APIs compared to the NDK, so for many graphic intensive applications such as -games, using the NDK is beneficial (It is important to note though that you can still get adequate -performance using the framework APIs. For example, the Google Body app is developed entirely -using the framework APIs). OpenGL with the NDK is also useful if you have a lot of native -code that you want to port over to Android. For more information about using the NDK, read the -docs in the docs/ directory of the NDK -download.
      -
      + + +
    \ No newline at end of file diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd index a786d4282d6f..a9fedb708228 100644 --- a/docs/html/guide/topics/graphics/opengl.jd +++ b/docs/html/guide/topics/graphics/opengl.jd @@ -20,6 +20,7 @@ parent.link=index.html
  • Projection and camera in ES 2.0
  • +
  • Shape Faces and Winding
  • OpenGL Versions and Device Compatibility
    1. Texture compression support
    2. @@ -33,11 +34,6 @@ parent.link=index.html
    3. {@link android.opengl.GLSurfaceView}
    4. {@link android.opengl.GLSurfaceView.Renderer}
    -

    Related tutorials

    -
      -
    1. OpenGL ES 1.0
    2. -
    3. OpenGL ES 2.0
    4. -

    Related samples

    1. GLSurfaceViewActivity
    2. @@ -48,8 +44,8 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics

    See also

      -
    1. Introducing -GLSurfaceView
    2. +
    3. + Displaying Graphics with OpenGL ES
    4. OpenGL ES
    5. OpenGL ES 1.x Specification
    6. OpenGL ES 2.x specification
    7. @@ -73,7 +69,7 @@ OpenGL ES 2.0 API specification.

      Android supports OpenGL both through its framework API and the Native Development Kit (NDK). This topic focuses on the Android framework interfaces. For more information about the -NDK, see the Android NDK. +NDK, see the Android NDK.

      There are two foundational classes in the Android framework that let you create and manipulate graphics with the OpenGL ES API: {@link android.opengl.GLSurfaceView} and {@link @@ -389,6 +385,43 @@ objects to be rendered by OpenGL. href="{@docRoot}resources/tutorials/opengl/opengl-es20.html#projection-and-views">OpenGL ES 2.0 tutorial.

      +

      Shape Faces and Winding

      + +

      In OpenGL, the face of a shape is a surface defined by three or more points in three-dimensional +space. A set of three or more three-dimensional points (called vertices in OpenGL) have a front face +and a back face. How do you know which face is front and which is the back? Good question. The +answer has to do with winding, or, the direction in which you define the points of a shape.

      + + +

      + Figure 1. Illustration of a coordinate list which translates into a +counterclockwise drawing order.

      + +

      In this example, the points of the triangle are defined in an order such that they are drawn in a +counterclockwise direction. The order in which these coordinates are drawn defines the winding +direction for the shape. By default, in OpenGL, the face which is drawn counterclockwise is the +front face. The triangle shown in Figure 1 is defined so that you are looking at the front face of +the shape (as interpreted by OpenGL) and the other side is the back face.

      + +

      Why is it important to know which face of a shape is the front face? The answer has to do with a +commonly used feature of OpenGL, called face culling. Face culling is an option for the OpenGL +environment which allows the rendering pipeline to ignore (not calculate or draw) the back face of a +shape, saving time, memory and processing cycles:

      + +
      +// enable face culling feature
      +gl.glEnable(GL10.GL_CULL_FACE);
      +// specify which faces to not draw
      +gl.glCullFace(GL10.GL_BACK);
      +
      + +

      If you try to use the face culling feature without knowing which sides of your shapes are the +front and back, your OpenGL graphics are going to look a bit thin, or possibly not show up at all. +So, always define the coordinates of your OpenGL shapes in a counterclockwise drawing order.

      + +

      Note: It is possible to set an OpenGL environment to treat the +clockwise face as the front face, but doing so requires more code and is likely to confuse +experienced OpenGL developers when you ask them for help. So don’t do that.

      OpenGL Versions and Device Compatibility

      @@ -410,7 +443,8 @@ texture compression, see the CompressedTextureActivity code sample.

      -

      To check if the ETC1 format is supported on a device, call the {@link +

      The ETC format is supported by most Android devices, but it not guarranteed to be available. To +check if the ETC1 format is supported on a device, call the {@link android.opengl.ETC1Util#isETC1Supported() ETC1Util.isETC1Supported()} method.

      Note: The ETC1 texture compression format does not support textures with an diff --git a/docs/html/guide/topics/graphics/overview.jd b/docs/html/guide/topics/graphics/overview.jd new file mode 100644 index 000000000000..a53cd3f15936 --- /dev/null +++ b/docs/html/guide/topics/graphics/overview.jd @@ -0,0 +1,73 @@ +page.title=Animation and Graphics Overview +@jd:body + +

      Android provides a variety of powerful APIs for applying animation to UI elements and drawing custom + 2D and 3D graphics. The sections below provide an overview of the APIs and system capabilities available + and help you decide with approach is best for your needs.

      + +

      Animation

      + +

      The Android framework provides two animation systems: property animation + (introduced in Android 3.0) and view animation. Both animation systems are viable options, + but the property animation system, in general, is the preferred method to use, because it + is more flexible and offers more features. In addition to these two systems, you can utilize Drawable + animation, which allows you to load drawable resources and display them one frame after + another.

      + +
      +
      Property +Animation
      +
      Introduced in Android 3.0 (API level 11), the property animation system lets you +animate properties of any object, including ones that are not rendered to the screen. The system is +extensible and lets you animate properties of custom types as well.
      + +
      View +Animation
      +
      View Animation is the older system and can only be used for Views. It is relatively easy to +setup and offers enough capabilities to meet many application's needs.
      +
      + +
      Drawable +Animation
      +
      Drawable animation involves displaying {@link android.graphics.drawable.Drawable} resources one +after another, like a roll of film. This method of animation is useful if you want to animate +things that are easier to represent with Drawable resources, such as a progression of bitmaps.
      + +

      2D and 3D Graphics

      + +

      When writing an application, it's important to consider exactly what your graphical demands will be. +Varying graphical tasks are best accomplished with varying techniques. For example, graphics and animations +for a rather static application should be implemented much differently than graphics and animations +for an interactive game. Here, we'll discuss a few of the options you have for drawing graphics +on Android and which tasks they're best suited for. +

      + +
      +
      Canvas and +Drawables
      +
      Android provides a set of {@link android.view.View} widgets that provide general functionality +for a wide array of user interfaces. You can also extend these widgets to modify the way they +look or behave. In addition, you can do your own custom 2D rendering using the various drawing +methods contained in the {@link android.graphics.Canvas} class or create {@link +android.graphics.drawable.Drawable} objects for things such as textured buttons or frame-by-frame +animations.
      + +
      Hardware +Acceleration
      +
      Beginning in Android 3.0, you can hardware accelerate the majority of +the drawing done by the Canvas APIs to further increase their performance.
      + +
      OpenGL
      +
      Android supports OpenGL ES 1.0 and 2.0, with Android framework APIs as well as natively +with the Native Development Kit (NDK). Using the framework APIs is desireable when you want to add a +few graphical enhancements to your application that are not supported with the Canvas APIs, or if +you desire platform independence and don't demand high performance. There is a performance hit in +using the framework APIs compared to the NDK, so for many graphic intensive applications such as +games, using the NDK is beneficial (It is important to note though that you can still get adequate +performance using the framework APIs. For example, the Google Body app is developed entirely +using the framework APIs). OpenGL with the NDK is also useful if you have a lot of native +code that you want to port over to Android. For more information about using the NDK, read the +docs in the docs/ directory of the NDK +download.
      +
      + diff --git a/docs/html/guide/topics/graphics/prop-animation.jd b/docs/html/guide/topics/graphics/prop-animation.jd index be24788ea760..b733624a8727 100644 --- a/docs/html/guide/topics/graphics/prop-animation.jd +++ b/docs/html/guide/topics/graphics/prop-animation.jd @@ -166,6 +166,31 @@ parent.link=animation.html "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/animation/index.html">API Demos sample project provides many examples on how to use the property animation system.

      + +

      How Property Animation Differs from View Animation

      + +

      The view animation system provides the capability to only animate {@link android.view.View} + objects, so if you wanted to animate non-{@link android.view.View} objects, you have to implement + your own code to do so. The view animation system is also constrained in the fact that it only + exposes a few aspects of a {@link android.view.View} object to animate, such as the scaling and + rotation of a View but not the background color, for instance.

      + +

      Another disadvantage of the view animation system is that it only modified where the + View was drawn, and not the actual View itself. For instance, if you animated a button to move + across the screen, the button draws correctly, but the actual location where you can click the + button does not change, so you have to implement your own logic to handle this.

      + +

      With the property animation system, these constraints are completely removed, and you can animate + any property of any object (Views and non-Views) and the object itself is actually modified. + The property animation system is also more robust in the way it carries out animation. At + a high level, you assign animators to the properties that you want to animate, such as color, + position, or size and can define aspects of the animation such as interpolation and + synchronization of multiple animators.

      + +

      The view animation system, however, takes less time to setup and requires less code to write. + If view animation accomplishes everything that you need to do, or if your existing code already + works the way you want, there is no need to use the property animation system. It also might + make sense to use both animation systems for different situations if the use case arises.

      API Overview

      diff --git a/docs/html/guide/topics/graphics/renderscript/compute.jd b/docs/html/guide/topics/graphics/renderscript/compute.jd new file mode 100644 index 000000000000..e827f003f97d --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/compute.jd @@ -0,0 +1,253 @@ +page.title=Compute +parent.title=Renderscript +parent.link=index.html + +@jd:body + +
      +
      +

      In this document

      + +
        +
      1. + Creating a Compute Renderscript + +
          +
        1. Creating the Renderscript file
        2. + +
        3. Calling the Renderscript code
        4. +
        +
      2. +
      + +

      Related Samples

      + +
        +
      1. Hello + Compute
      2. + +
      3. Balls
      4. +
      +
      +
      + +

      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.

      + +

      Compute Renderscripts scale to the amount of +processing cores available on the device. This is enabled through a function named +rsForEach() (or the forEach_root() 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.

      + +

      Creating a Compute Renderscript

      + +

      Implementing a compute Renderscript creating a .rs file that contains +your Renderscript code and calling it at the Android framework level with the +forEach_root() or at the Renderscript runtime level with the +rsForEach() function. The following diagram describes how a typical compute +Renderscript is set up:

      + +

      Figure 1. Compute Renderscript overview

      + +

      The following sections describe how to create a simple compute Renderscript and use it in an +Android application. This example uses the HelloCompute Renderscript +sample that is provided in the SDK as a guide (some code has been modified from its original +form for simplicity).

      + +

      Creating the Renderscript file

      + +

      Your Renderscript code resides in .rs and .rsh files in the +<project_root>/src/ directory. This code contains the compute logic +and declares all necessary variables and pointers. +Every compute .rs file generally contains the following items:

      + +
        +
      • A pragma declaration (#pragma rs java_package_name(package.name)) + that declares the package name of the .java reflection of this Renderscript.
      • + +
      • A pragma declaration (#pragma version(1)) that declares the version of + Renderscript that you are using (1 is the only value for now).
      • + +
      • A root() function that is the main worker function. The root function is + called by the rsForEach function, which allows the Renderscript code to be called and + executed on multiple cores if they are available. The root() function must return + void and accept the following arguments: + +
          +
        • 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.
        • +
        + +

        The following arguments are optional, but both must be supplied if you choose to use + them:

        + +
          +
        • 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.
        • + +
        • The size of the user-defined data.
        • +
        +
      • + +
      • An optional init() function. This allows you to do any initialization + before the root() function runs, such as initializing variables. This + function runs once and is called automatically when the Renderscript starts, before anything + else in your Renderscript.
      • + +
      • Any variables, pointers, and structures that you wish to use in your Renderscript code (can + be declared in .rsh files if desired)
      • +
      + +

      The following code shows how the +mono.rs file is implemented:

      +
      +#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);
      +}
      +
      + +

      Calling the Renderscript code

      + +

      You can do Renderscript to Renderscript calls with rsForEach in situations +such as when a graphics Renderscript needs to do a lot of computational operations. The Renderscript +Balls sample shows how +this is setup. The balls.rs +graphics Renderscript calls the balls_physics.rs +compute Renderscript to calculate the location of the balls that are rendered to the screen.

      + +

      Another way to use a compute Renderscript is to call it from your Android framework code by +creating a Renderscript object by instantiating the (ScriptC_script_name) +class. This class contains a method, forEach_root(), that lets you invoke +rsForEach. 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 HelloCompute sample to see +how a simple Android application can utilize a compute Renderscript.

      + +

      To call a compute Renderscript at the Android framework level:

      + +
        +
      1. 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.
      2. + +
      3. Create an instance of the ScriptC_script_name class.
      4. + +
      5. Call forEach_root(), passing in the allocations, the + Renderscript, and any optional user-defined data. The output allocation will contain the output + of the compute Renderscript.
      6. +
      + +

      In the following example, taken from the HelloCompute sample, processes +a bitmap and outputs a black and white version of it. The +createScript() method carries out the steps described previously. This method the compute +Renderscript, mono.rs, 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:

      +
      +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);
      +  }
      +}
      +
      + +

      To call a compute Renderscript from another Renderscript file:

      +
        +
      1. 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.
      2. + +
      3. Call rsForEach(), passing in the allocations and any optional user-defined data. + The output allocation will contain the output of the compute Renderscript.
      4. +
      +

      The following example, taken from the Renderscript +Balls sample, demonstrates how to do make a script to script call:

      +
      +rs_script script;
      +rs_allocation in_allocation;
      +rs_allocation out_allocation;
      +UserData_t data;
      +...
      +rsForEach(script, in_allocation, out_allocation, &data, sizeof(data));
      +
      + +

      In this example, assume that the script and memory allocations have already been +allocated and bound at the Android framework level and that UserData_t is a struct +declared previously. Passing a pointer to a struct and the size of the struct to rsForEach +is optional, but useful if your compute Renderscript requires additional information other than +the necessary memory allocations.

      diff --git a/docs/html/guide/topics/graphics/renderscript/graphics.jd b/docs/html/guide/topics/graphics/renderscript/graphics.jd new file mode 100644 index 000000000000..58676ea99fe3 --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/graphics.jd @@ -0,0 +1,994 @@ +page.title=Graphics +parent.title=Renderscript +parent.link=index.html + +@jd:body + + + +

      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 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.

      + +

      Creating a Graphics Renderscript

      + +

      Renderscript applications require various layers of code, so it is useful to create the following + files to help keep your application organized:

      + +
      +
      The Renderscript .rs file
      + +
      This file contains the logic to do the graphics rendering.
      + +
      The Renderscript entry point .java class
      + +
      This class allows the view class to interact with the code defined in the .rs + file. This class contains a Renderscript object (instance of + ScriptC_renderscript_file), which allows your Android framework code to + 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.
      + +
      The view .java class
      + +
      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()} 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
      + +
      The activity .java class
      + +
      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.
      +
      +

      Figure 1 describes how these classes interact with one another in a graphics Renderscript:

      + + +

      Figure 1. Graphics Renderscript overview

      + + +

      The following sections describe how to create an application that uses a graphics Renderscript by using + the Renderscript Fountain + sample that is provided in the SDK as a guide (some code has been modified from its original + form for simplicity).

      + +

      Creating the Renderscript file

      + +

      Your Renderscript code resides in .rs and .rsh (headers) files in the + <project_root>/src/ directory. This code contains the logic to render your + graphics and declares all other necessary items such as variables, structs, + and pointers. Every graphics .rs file generally contains the following items:

      + +
        +
      • A pragma declaration (#pragma rs java_package_name(package.name)) that declares + the package name of the .java reflection of this Renderscript.
      • + +
      • A pragma declaration (#pragma version(1)) that declares the version of Renderscript that + you are using (1 is the only value for now).
      • + +
      • A #include "rs_graphics.rsh" declaration.
      • + +
      • A root() 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 0 (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. + +

        Note: 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 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.

        + +

        For more information on using the Renderscript graphics functions, see the Drawing section.

        +
      • + +
      • An init() function. This allows you to do initialization of your + Renderscript before the root() 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.
      • + +
      • Any variables, pointers, and structures that you wish to use in your Renderscript code (can + be declared in .rsh files if desired)
      • +
      + +

      The following code shows how the fountain.rs file is implemented:

      +
      +#pragma version(1)
      +
      +// Tell which java package name the reflected files should belong to
      +#pragma rs java_package_name(com.example.android.rs.fountain)
      +
      +//declare shader binding
      +#pragma stateFragment(parent)
      +
      +// header with graphics APIs, must include explicitly
      +#include "rs_graphics.rsh"
      +
      +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;
      +}
      +
      +// 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];
      +        }
      +    }
      +}
      +
      + +

      Creating the Renderscript entry point class

      + +

      When you create a Renderscript (.rs) file, it is helpful to create a + corresponding Android framework class that is an entry point into the .rs file. + The most important thing this class does is receive a {@link android.renderscript.RenderScriptGL} rendering context + object from the view class and binds the actual Renderscript + code to the rendering context. This notifies your view class of the code that it needs + to render graphics. +

      + +

      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:

      + +
        +
      • Create a Renderscript object + ScriptC_rs_filename. 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 Fountain + sample creates the Renderscript object: +
        +  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);
        +  
        +
      • +
      • Allocate any necessary memory and bind it to your Renderscript code via the Renderscript object.
      • +
      • Build any necessary meshes and bind them to the Renderscript code via the Renderscript object.
      • +
      • Create any necessary programs and bind them to the Renderscript code via the Renderscript object.
      • +
      + +

      The following code shows how the + FountainRS class is implemented:

      +
      +package com.example.android.rs.fountain;
      +
      +import android.content.res.Resources;
      +import android.renderscript.*;
      +import android.util.Log;
      +
      +public class FountainRS {
      +    public static final int PART_COUNT = 50000;
      +
      +    public FountainRS() {
      +    }
      +
      +    /**
      +     * 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;
      +
      +        /**
      +         * 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];
      +
      +    /**
      +     * Calls Renderscript functions (invoke_addParticles)
      +     * via the Renderscript object to add particles to render
      +     * based on where a user touches the screen.
      +     */
      +    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;
      +        }
      +
      +    }
      +}
      +
      + + +

      Creating the view class

      + + +

      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 FountainView class is implemented:

      +
      +package com.example.android.rs.fountain;
      +
      +import android.renderscript.RSTextureView;
      +import android.renderscript.RenderScriptGL;
      +import android.content.Context;
      +import android.view.MotionEvent;
      +
      +public class FountainView extends RSTextureView {
      +
      +    public FountainView(Context context) {
      +        super(context);
      +    }
      +    // Renderscript context
      +    private RenderScriptGL mRS;
      +    // Renderscript entry point object that calls Renderscript code
      +    private FountainRS mRender;
      +
      +    /**
      +     * Create Renderscript context and initialize Renderscript entry point
      +     */
      +    @Override
      +    protected void onAttachedToWindow() {
      +        super.onAttachedToWindow();
      +        android.util.Log.e("rs", "onAttachedToWindow");
      +        if (mRS == null) {
      +            RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
      +            mRS = createRenderScriptGL(sc);
      +            mRender = new FountainRS();
      +            mRender.init(mRS, getResources());
      +        }
      +    }
      +
      +    @Override
      +    protected void onDetachedFromWindow() {
      +        super.onDetachedFromWindow();
      +        android.util.Log.e("rs", "onDetachedFromWindow");
      +        if (mRS != null) {
      +            mRS = null;
      +            destroyRenderScriptGL();
      +        }
      +    }
      +
      +
      +    /**
      +     * Use callbacks to relay data to Renderscript entry point class
      +     */
      +    @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);
      +        }
      +        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;
      +    }
      +}
      +
      + +

      Creating the activity class

      + +

      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.

      + +

      The following code shows how the Fountain + sample declares its activity class:

      +
      +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;
      +
      +    private FountainView mView;
      +
      +    @Override
      +    public void onCreate(Bundle icicle) {
      +        super.onCreate(icicle);
      +
      +        // Create our Preview view and set it as 
      +        // the content of our activity
      +        mView = new FountainView(this);
      +        setContentView(mView);
      +    }
      +
      +    @Override
      +    protected void onResume() {
      +        Log.e("rs", "onResume");
      +
      +        // Ideally a game should implement onResume() and onPause()
      +        // to take appropriate action when the activity looses focus
      +        super.onResume();
      +        mView.resume();
      +    }
      +
      +    @Override
      +    protected void onPause() {
      +        Log.e("rs", "onPause");
      +
      +        // Ideally a game should implement onResume() and onPause()
      +        // to take appropriate action when the activity looses focus
      +        super.onPause();
      +        mView.pause();
      +
      +    }
      +
      +    static void log(String message) {
      +        if (LOG_ENABLED) {
      +            Log.v(LOG_TAG, message);
      +        }
      +    }
      +}
      +
      + +

      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 +Renderscript samples as a starting +point if this is your first time using Renderscript.

      + +

      Drawing

      +

      The following sections describe how to use the graphics functions to draw with Renderscript.

      + +

      Simple drawing

      + +

      The native Renderscript APIs provide a few convenient functions to easily draw a polygon or text to + the screen. You call these in your root() 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:

      + +
        +
      • rsgDrawRect(): Sets up a mesh and draws a rectangle to the screen. It uses the + top left vertex and bottom right vertex of the rectangle to draw.
      • + +
      • rsgDrawQuad(): Sets up a mesh and draws a quadrilateral to the screen.
      • + +
      • rsgDrawQuadTexCoords(): Sets up a mesh and draws a quadrilateral to the screen + using the provided coordinates of a texture.
      • + +
      • rsgDrawText(): Draws specified text to the screen. Use rsgFontColor() + to set the color of the text.
      • +
      + +

      Drawing with a mesh

      + +

      When you want to render complex scenes to the screen, instantiate a {@link + android.renderscript.Mesh} and draw it with rsgDrawMesh(). A {@link + android.renderscript.Mesh} is a collection of allocations that represent vertex data (positions, + 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:

      + +
        +
      • 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.
      • + +
      • 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 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.
      • + +
      • 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.
      • +
      + +

      To create a mesh using the {@link android.renderscript.Mesh.TriangleMeshBuilder}, you need to + supply it with a set of vertices and the indices for the vertices that comprise the triangle. For + example, the following code specifies three vertices, which are added to an internal array, + indexed in the order they were added. The call to {@link + android.renderscript.Mesh.TriangleMeshBuilder#addTriangle addTriangle()} draws the triangle with + vertex 0, 1, and 2 (the vertices are drawn counter-clockwise).

      +
      +int float2VtxSize = 2;
      +Mesh.TriangleMeshBuilder triangles = new Mesh.TriangleMeshBuilder(renderscriptGL,
      +float2VtxSize, Mesh.TriangleMeshBuilder.COLOR);
      +triangles.addVertex(300.f, 300.f);
      +triangles.addVertex(150.f, 450.f);
      +triangles.addVertex(450.f, 450.f);
      +triangles.addTriangle(0 , 1, 2);
      +Mesh smP = triangle.create(true);
      +script.set_mesh(smP);
      +
      + +

      To draw a mesh using the {@link android.renderscript.Mesh.AllocationBuilder}, you need to + supply it with one or more allocations that contain the vertex data:

      +
      +Allocation vertices;
      +
      +...
      +Mesh.AllocationBuilder triangle = new Mesh.AllocationBuilder(mRS);
      +smb.addVertexAllocation(vertices.getAllocation());
      +smb.addIndexSetType(Mesh.Primitive.TRIANGLE);
      +Mesh smP = smb.create();
      +script.set_mesh(smP);
      +
      + +

      In your Renderscript code, draw the built mesh to the screen:

      +
      +rs_mesh mesh;
      +...
      +
      +int root(){
      +...
      +rsgDrawMesh(mesh);
      +...
      +return 0; //specify a non zero, positive integer to specify the frame refresh.
      +          //0 refreshes the frame only when the mesh changes.
      +}
      +
      + +

      Programs

      + +

      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 that controls culling. The four programs mirror a + traditional graphical rendering pipeline:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Android Object TypeRenderscript Native TypeDescription
      {@link android.renderscript.ProgramVertex}rs_program_vertex +

      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:

      + +
        +
      • An {@link android.renderscript.Element} describing its varying inputs or attributes
      • + +
      • GLSL shader string that defines the body of the program
      • + +
      • a {@link android.renderscript.Type} that describes the layout of an + Allocation containing constant or uniform inputs
      • +
      + +

      Once the program is created, bind it to the {@link android.renderscript.RenderScriptGL} + graphics context by calling {@link android.renderscript.RenderScriptGL#bindProgramVertex + 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 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 {@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.

      + +

      To bind shader constants to the program, declare a struct that contains the necessary + shader constants in your 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 {@link android.renderscript.Allocation} to the program and the + Renderscript runtime sends the data that is contained in the struct 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.

      + +

      The {@link android.renderscript.ProgramVertexFixedFunction.Builder} class also + lets you build a simple vertex shader without writing GLSL code. +

      +
      {@link android.renderscript.ProgramFragment}rs_program_fragment +

      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, 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 {@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 rsgAllocationSyncAll(), 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 + inside the program vertex must provide it.

      + +

      To bind shader constructs to the program, declare a struct that contains the necessary + shader constants in your 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 {@link android.renderscript.Allocation} to the program and the + Renderscript runtime sends the data that is contained in the struct 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.

      + +

      The {@link android.renderscript.ProgramFragmentFixedFunction.Builder} class also + lets you build a simple fragment shader without writing GLSL code. +

      +
      {@link android.renderscript.ProgramStore}rs_program_storeThe 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.
      {@link android.renderscript.ProgramRaster}rs_program_rasterThe 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.
      + +

      The following example defines a vertex shader in GLSL and binds it to a Renderscript context object:

      +
      +    private RenderScriptGL glRenderer;      //rendering context
      +    private ScriptField_Point mPoints;      //vertices
      +    private ScriptField_VpConsts mVpConsts; //shader constants
      +
      +    ...
      +
      +     ProgramVertex.Builder sb = new ProgramVertex.Builder(glRenderer);
      +        String t =  "varying vec4 varColor;\n" +
      +                    "void main() {\n" +
      +                    "  vec4 pos = vec4(0.0, 0.0, 0.0, 1.0);\n" +
      +                    "  pos.xy = ATTRIB_position;\n" +
      +                    "  gl_Position = UNI_MVP * pos;\n" +
      +                    "  varColor = vec4(1.0, 1.0, 1.0, 1.0);\n" +
      +                    "  gl_PointSize = ATTRIB_size;\n" +
      +                    "}\n";
      +        sb.setShader(t);
      +        sb.addConstant(mVpConsts.getType());
      +        sb.addInput(mPoints.getElement());
      +        ProgramVertex pvs = sb.create();
      +        pvs.bindConstants(mVpConsts.getAllocation(), 0);
      +        glRenderer.bindProgramVertex(pvs);
      +
      + + +

      The + RsRenderStatesRS sample has many examples on how to create a shader without writing GLSL.

      + +

      Program bindings

      + +

      You can also declare four pragmas that control default program bindings to the {@link + android.renderscript.RenderScriptGL} context when the script is executing:

      + +
        +
      • stateVertex
      • + +
      • stateFragment
      • + +
      • stateRaster
      • + +
      • stateStore
      • +
      + +

      The possible values for each pragma are parent or default. Using + default binds the shaders to the graphical context with the system defaults.

      + +

      Using parent 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.

      + +

      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:

      +
      +#pragma stateVertex(parent)
      +#pragma stateStore(parent)
      +
      + +

      Defining a sampler

      + +

      A {@link android.renderscript.Sampler} object defines how data is extracted from textures. + 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.

      + +

      The + RsRenderStatesRS sample has many examples on how to create a sampler and bind it to a + Fragment program.

      + + + +

      Rendering to a Framebuffer Object

      + +

      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.

      + +

      In general, you need to do the following to render to a framebuffer object:

      + +
        +
      • 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.
      • + +
      • Tell the Renderscript runtime to render to the framebuffer object instead of the default + framebuffer by calling rsgBindColorTarget() and passing it the color buffer + allocation. If applicable, call rsgBindDepthTarget() passing in the depth buffer + allocation as well.
      • + +
      • Render your scene normally with the rsgDraw functions. The scene will be + rendered into the color buffer instead of the default onscreen framebuffer.
      • + +
      • When done, tell the Renderscript runtime stop rendering to the color buffer and back + to the default framebuffer by calling rsgClearAllRenderTargets().
      • + +
      • Create a fragment shader and bind a the color buffer to it as a texture.
      • + +
      • Render your scene to the default framebuffer. The texture will be used according + to the way you setup your fragment shader.
      • +
      + +

      The following example shows you how to render to a framebuffer object by modifying the +Fountain Renderscript sample. The end +result is the FountainFBO 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.

      + +
        +
      1. Modify fountain.rs and add the following global variables. This creates setter + methods when this file is reflected into a .java file, allowing you to allocate + memory in your Android framework code and binding it to the Renderscript runtime. +
        +//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;
        +
        +
      2. + +
      3. Modify the root function of fountain.rs to look like the following code. The + modifications are commented: +
        +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;
        +}
        +
        +
      4. + +
      5. In the FountainRS.java file, modify the init() method to look + like the following code. The modifications are commented: + +
        +/* 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);
        +}
        +
        + +

        Note: 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: + +

        +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);
        +
        +
        +

        +
      6. + +
      7. 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.
      8. +
      diff --git a/docs/html/guide/topics/graphics/renderscript/index.jd b/docs/html/guide/topics/graphics/renderscript/index.jd new file mode 100644 index 000000000000..b2d9f8461be3 --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/index.jd @@ -0,0 +1,804 @@ +page.title=Renderscript +@jd:body + + + +

      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:

      +
        +
      • 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.
      • + +
      • Performance: Renderscript provides similar performance to OpenGL with the NDK and also + provides a high performance compute API that is not offered by OpenGL.
      • + +
      • Usability: Renderscript simplifies development when possible, such as eliminating JNI glue code + and simplifying mesh setup.
      • +
      + +

      The main disadvantages are:

      + +
        +
      • 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.
      • + +
      • 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. +
      • +
      + + +

      For an example of Renderscript in action, install the Renderscript sample applications that + are shipped with the SDK in <sdk_root>/samples/android-11/RenderScript. + 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.

      + +

      Renderscript Overview

      +

      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).

      + +

      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 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.

      + + +

      Figure 1. Renderscript system overview

      + +

      When using Renderscript, there are three layers of APIs that enable communication between the + Renderscript runtime and Android framework code:

      + +
        +
      • The Renderscript runtime APIs allow you to do the computation or graphics rendering + that is required by your application.
      • + +
      • 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.
      • + +
      • 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.
      • +
      + +

      + +

      Renderscript Runtime Layer

      + +

      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. +

      +

      Note: 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.

      + +

      You define your Renderscript code in .rs + and .rsh files in the src/ directory of your Android project. The code + is compiled to intermediate bytecode by the + llvm 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 + llvm 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.

      + +

      Some key features of the Renderscript runtime libraries include:

      + +
        + +
      • Graphics rendering functions
      • + +
      • Memory allocation request features
      • + +
      • 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.
      • + +
      • Conversion routines for primitive data types and vectors, matrix routines, date and time + routines, and graphics routines.
      • + +
      • Data types and structures to support the Renderscript system such as Vector types for + defining two-, three-, or four-vectors.
      • + +
      • Logging functions
      • +
      + +

      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:

      + +
      #include "rs_graphics.rsh"
      + +

      Reflected Layer

      + +

      The reflected layer is a set of classes that the Android build tools generate to allow access + 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:

      + +
        +
      • Every .rs file that you create is generated into a class named + project_root/gen/package/name/ScriptC_renderscript_filename of +type {@link android.renderscript.ScriptC}. This file is the .java version of your +.rs file, which you can call from the Android framework. This class contains the +following items reflected from the .rs file: + +
          +
        • Non-static functions
        • + +
        • 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 const, then a set method is not +generated.

        • + +
        • Global pointers
        • +
        +
      • + +
      • A struct is reflected into its own class named + + project_root/gen/package/name/ScriptField_struct_name, which extends {@link + android.renderscript.Script.FieldBase}. This class represents an array of the + struct, which allows you to allocate memory for one or more instances of this + struct.
      • +
      + + +

      Functions

      +

      Functions are reflected into the script class itself, located in +project_root/gen/package/name/ScriptC_renderscript_filename. For +example, if you declare the following function in your Renderscript code:

      + +
      +void touch(float x, float y, float pressure, int id) {
      +    if (id >= 10) {
      +        return;
      +    }
      +
      +    touchPos[id].x = x;
      +    touchPos[id].y = y;
      +    touchPressure[id] = pressure;
      +}
      +
      + +

      then the following code is generated:

      + +
      +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);
      +}
      +
      +

      +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.

      + +

      +If you want the Renderscript code to send a value back to the Android framework, use the +rsSendToClient() +function. +

      + +

      Variables

      + +

      Variables of supported types are reflected into the script class itself, located in +project_root/gen/package/name/ScriptC_renderscript_filename. A set of accessor +methods are generated for each variable. For example, if you declare the following variable in +your Renderscript code:

      +
      uint32_t unsignedInteger = 1;
      + +

      then the following code is generated:

      + +
      +private long mExportVar_unsignedInteger;
      +public void set_unsignedInteger(long v){
      +    mExportVar_unsignedInteger = v;
      +    setVar(mExportVarIdx_unsignedInteger, v);
      +}
      +
      +public long get_unsignedInteger(){
      +    return mExportVar_unsignedInteger;
      +}
      +  
      + + +

      Structs

      +

      Structs are reflected into their own classes, located in + <project_root>/gen/com/example/renderscript/ScriptField_struct_name. This + class represents an array of the struct and allows you to allocate memory for a + specified number of structs. For example, if you declare the following struct:

      +
      +typedef struct Point {
      +    float2 position;
      +    float size;
      +} Point_t;
      +
      + +

      then the following code is generated in ScriptField_Point.java: +

      +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 = 12;
      +
      +        Float2 position;
      +        float size;
      +
      +        Item() {
      +            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), "position");
      +        eb.add(Element.F32(rs), "size");
      +        return eb.create();
      +    }
      +
      +    public  ScriptField_Point(RenderScript rs, int count) {
      +        mItemArray = null;
      +        mIOBuffer = null;
      +        mElement = createElement(rs);
      +        init(rs, count);
      +    }
      +
      +    public  ScriptField_Point(RenderScript rs, int count, int usages) {
      +        mItemArray = null;
      +        mIOBuffer = null;
      +        mElement = createElement(rs);
      +        init(rs, count, usages);
      +    }
      +
      +    private void copyToArray(Item i, int index) {
      +        if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count
      +        */);
      +        mIOBuffer.reset(index * Item.sizeof);
      +        mIOBuffer.addF32(i.position);
      +        mIOBuffer.addF32(i.size);
      +    }
      +
      +    public void set(Item i, int index, boolean copyNow) {
      +        if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */];
      +        mItemArray[index] = i;
      +        if (copyNow)  {
      +            copyToArray(i, index);
      +            mAllocation.setFromFieldPacker(index, mIOBuffer);
      +        }
      +    }
      +
      +    public Item get(int index) {
      +        if (mItemArray == null) return null;
      +        return mItemArray[index];
      +    }
      +
      +    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].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_position(int index) {
      +        if (mItemArray == null) return null;
      +        return mItemArray[index].position;
      +    }
      +
      +    public float get_size(int index) {
      +        if (mItemArray == null) return 0;
      +        return mItemArray[index].size;
      +    }
      +
      +    public void copyAll() {
      +        for (int ct = 0; ct < mItemArray.length; ct++) copyToArray(mItemArray[ct], ct);
      +        mAllocation.setFromFieldPacker(0, mIOBuffer);
      +    }
      +
      +    public void resize(int newSize) {
      +        if (mItemArray != null)  {
      +            int oldSize = mItemArray.length;
      +            int copySize = Math.min(oldSize, newSize);
      +            if (newSize == oldSize) return;
      +            Item ni[] = new Item[newSize];
      +            System.arraycopy(mItemArray, 0, ni, 0, copySize);
      +            mItemArray = ni;
      +        }
      +        mAllocation.resize(newSize);
      +        if (mIOBuffer != null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */);
      +    }
      +}
      +
      + +

      The generated code is provided to you as a convenience to allocate memory for structs requested +by the Renderscript runtime and to interact with structs +in memory. Each struct's class defines the following methods and constructors:

      + +
        +
      • Overloaded constructors that allow you to allocate memory. The + ScriptField_struct_name(RenderScript rs, int count) constructor allows + you to define the number of structures that you want to allocate memory for with the + count parameter. The ScriptField_struct_name(RenderScript rs, int + count, int usages) constructor defines an extra parameter, usages, that + lets you specify the memory space of this memory allocation. There are four memory space + possibilities: + +
          +
        • {@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.
        • + +
        • {@link android.renderscript.Allocation#USAGE_GRAPHICS_TEXTURE}: Allocates in the + texture memory space of the GPU.
        • + +
        • {@link android.renderscript.Allocation#USAGE_GRAPHICS_VERTEX}: Allocates in the vertex + memory space of the GPU.
        • + +
        • {@link android.renderscript.Allocation#USAGE_GRAPHICS_CONSTANTS}: Allocates in the + constants memory space of the GPU that is used by the various program objects.
        • +
        + +

        You can specify multiple memory spaces by using the bitwise OR 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:

        +
        +        ScriptField_Point touchPoints = new ScriptField_Point(glRenderer, 2,
        +        Allocation.USAGE_SCRIPT | Allocation.USAGE_GRAPHICS_VERTEX);
        +      
        + +

        If you modify the memory in one memory space and want to push the updates to the rest of + the memory spaces, call + rsgAllocationSyncAll() in your Renderscript code to + synchronize the memory.

        +
      • + +
      • A static nested class, Item, allows you to create an instance of the + struct, in the form of an object. This nested class is useful if it makes more sense to work + with the struct in your Android code. When you are done manipulating the object, + you can push the object to the allocated memory by calling set(Item i, int index, + boolean copyNow) and setting the Item to the desired position in +the array. The Renderscript runtime automatically has access to the newly written memory. + +
      • Accessor methods to get and set the values of each field in a struct. Each of these + accessor methods have an index parameter to specify the struct in + the array that you want to read or write to. Each setter method also has a +copyNow 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 + copyAll().
      • + +
      • The createElement() method creates a description of the struct in memory. This + description is used to allocate memory consisting of one or many elements.
      • + +
      • resize() works much like a realloc() in C, allowing you to +expand previously allocated memory, maintaining the current values that were previously +created.
      • + +
      • copyAll() 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 +copyNow boolean parameter that you can specify. Specifying + true synchronizes the memory when you call the method. If you specify false, + you can call copyAll() once, and it synchronizes memory for all the +properties that are not yet synchronized.
      • +
      + +

      Pointers

      +

      Pointers are reflected into the script class itself, located in +project_root/gen/package/name/ScriptC_renderscript_filename. You +can declare pointers to a struct or any of the supported Renderscript types, but a +struct cannot contain pointers or nested arrays. For example, if you declare the +following pointers to a struct and int32_t

      + +
      +typedef struct Point {
      +    float2 position;
      +    float size;
      +} Point_t;
      +
      +Point_t *touchPoints;
      +int32_t *intPointer;
      +
      +

      then the following code is generated in:

      + +
      +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;
      +}
      +  
      + +

      A get method and a special method named bind_pointer_name +(instead of a set() 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 .rs file). For more information, see Working +with Allocated Memory. +

      + + +

      Memory Allocation APIs

      + +

      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 malloc 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 Figure 1 +for more information on how memory allocation occurs. +

      + +

      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 malloc 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 +malloc call that can look like this:

      + +
      array = (int *)malloc(sizeof(int)*10);
      + +

      The malloc call can be broken up into two parts: the size of the memory being allocated (sizeof(int)), + 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 malloc itself.

      + +

      The {@link android.renderscript.Element} class represents the (sizeof(int)) portion + of the malloc 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.

      + +

      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 + Allocating and binding memory to the Renderscript section. + The following table describes the three memory management classes in more detail:

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      Android Object TypeDescription
      {@link android.renderscript.Element} +

      An element describes one cell of a memory allocation and can have two forms: basic or + complex.

      + +

      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.

      + +

      Complex elements contain a list of basic elements and are created from + structs that you declare in your Renderscript code. For instance an allocation + can contain multiple structs arranged in order in memory. Each struct is considered as its + own element, rather than each data type within that struct.

      +
      {@link android.renderscript.Type} +

      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.

      + +

      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.

      +
      {@link android.renderscript.Allocation} +

      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. +

      + +

      Allocation data is uploaded in one of two primary ways: type checked and type unchecked. + For simple arrays there are copyFrom() 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.

      +
      + +

      Working with Memory

      + +

      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 set method is +not generated.

      + + +

      Note: If you are using certain Renderscript structures that contain pointers, such as +rs_program_fragment and rs_allocation, you have to obtain an object of the +corresponding Android framework class first and then call the set 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. +

      + +

      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 .rs 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.

      + + + +

      Allocating and binding dynamic memory to the Renderscript

      + +

      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 bind method of the pointer to bind the allocated memory to the + Renderscript runtime.

      +

      The example below allocates memory for both a primitive type pointer, + intPointer, and a pointer to a struct, touchPoints. It also binds the memory to the + Renderscript:

      +
      +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);
      +
      +   ...
      +}
      +
      + +

      Reading and writing to memory

      +

      You can read and write to statically and dynamically allocated memory both at the Renderscript runtime + and Android framework layer.

      + +

      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 get +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 +rsSendToClient() function +to overcome this limitation. +

      +

      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.

      + +

      Reading and writing to global variables

      + +

      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.

      + +

      For example, given the following struct declared in a file named rsfile.rs:

      +
      +typedef struct Point {
      +    int x;
      +    int y;
      +} Point_t;
      +
      +Point_t point;
      +
      +
      +

      You can assign values to the struct like this directly in rsfile.rs. These values are not +propagated back to the Android framework level:

      +
      +point.x = 1;
      +point.y = 1;
      +
      + +

      You can assign values to the struct at the Android framework layer like this. These values are +propagated back to the Renderscript runtime level:

      +
      +ScriptC_rsfile mScript;
      +
      +...
      +
      +Item i = new ScriptField_Point.Item();
      +i.x = 1;
      +i.y = 1;
      +mScript.set_point(i);
      +
      + +

      You can read the values in your Renderscript code like this:

      + +
      +rsDebug("Printing out a Point", point.x, point.y);
      +
      + +

      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:

      + +
      +Log.i("TAGNAME", "Printing out a Point: " + mScript.get_point().x + " " + mScript.get_point().y);
      +System.out.println(point.get_x() + " " + point.get_y());
      +
      + +

      Reading and writing global pointers

      + +

      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 get and set 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.

      + +

      For example, given the following pointer to a struct in a file named rsfile.rs:

      +
      +typedef struct Point {
      +    int x;
      +    int y;
      +} Point_t;
      +
      +Point_t *point;
      +
      + +

      Assuming you already allocated memory at the Android framework layer, you can access values in +the struct as normal. Any changes you make to the struct via its pointer variable +are automatically available to the Android framework layer:

      + +
      +point[index].x = 1;
      +point[index].y = 1;
      +
      + +

      You can read and write values to the pointer at the Android framework layer as well: +

      +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);
      +
      + +

      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.

      diff --git a/docs/html/guide/topics/graphics/renderscript/reference.jd b/docs/html/guide/topics/graphics/renderscript/reference.jd new file mode 100644 index 000000000000..a0a9df2df8ab --- /dev/null +++ b/docs/html/guide/topics/graphics/renderscript/reference.jd @@ -0,0 +1,18 @@ +page.title=Runtime API Reference +@jd:body + + + + + diff --git a/docs/html/guide/topics/intents/index.html b/docs/html/guide/topics/intents/index.html deleted file mode 100644 index b831246ad7b6..000000000000 --- a/docs/html/guide/topics/intents/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - -Redirecting... - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/guide/topics/intents/intents-filters.jd b/docs/html/guide/topics/intents/intents-filters.jd deleted file mode 100644 index 3ad3c9374a81..000000000000 --- a/docs/html/guide/topics/intents/intents-filters.jd +++ /dev/null @@ -1,1055 +0,0 @@ -page.title=Intents and Intent Filters -@jd:body - -
      -
      - -

      In this document

      -
        -
      1. Intent Objects
      2. -
      3. Intent Resolution
      4. -
      5. Intent filters
      6. -
      7. Common cases
      8. -
      9. Using intent matching
      10. -
      11. Note Pad Example
      12. -
      - -

      Key classes

      -
        -
      1. {@link android.content.Intent}
      2. -
      3. {@link android.content.IntentFilter}
      4. -
      5. {@link android.content.BroadcastReceiver}
      6. -
      7. {@link android.content.pm.PackageManager}
      8. -
      - -
      -
      - - -

      -Three of the core components of an application — activities, services, and -broadcast receivers — are activated through messages, called intents. -Intent messaging is a facility for late run-time binding between components in the same -or different applications. The intent itself, an {@link android.content.Intent} -object, is a passive data structure holding an abstract description of an operation -to be performed — or, often in the case of broadcasts, a description of something -that has happened and is being announced. There are separate mechanisms for -delivering intents to each type of component: -

      - -
        -
      • An Intent object is passed to {@link android.content.Context#startActivity -Context.startActivity()} or {@link android.app.Activity#startActivityForResult -Activity.startActivityForResult()} to launch an activity or get an existing -activity to do something new. (It can also be passed to -{@link android.app.Activity#setResult(int, Intent) Activity.setResult()} -to return information to the activity that called {@code startActivityForResult()}.)
      • - -
      • An Intent object is passed to {@link android.content.Context#startService -Context.startService()} to initiate a service or deliver new instructions to an -ongoing service. Similarly, an intent can be passed to {@link -android.content.Context#bindService Context.bindService()} to establish a -connection between the calling component and a target service. It can optionally -initiate the service if it's not already running.

      • - -
      • Intent objects passed to any of the broadcast methods (such as {@link -android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()}, -{@link android.content.Context#sendOrderedBroadcast(Intent, String) -Context.sendOrderedBroadcast()}, or {@link -android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}) -are delivered to all interested broadcast receivers. Many kinds of broadcasts -originate in system code.

      • -
      - -

      -In each case, the Android system finds the appropriate activity, service, or set -of broadcast receivers to respond to the intent, instantiating them if necessary. -There is no overlap within these messaging systems: Broadcast intents are delivered -only to broadcast receivers, never to activities or services. An intent passed to -{@code startActivity()} is delivered only to an activity, never to a service or -broadcast receiver, and so on. -

      - -

      -This document begins with a description of Intent objects. It then describes the -rules Android uses to map intents to components — how it resolves which -component should receive an intent message. For intents that don't explicitly -name a target component, this process involves testing the Intent object against -intent filters associated with potential targets. -

      - - -

      Intent Objects

      - -

      -An {@link android.content.Intent} object is a bundle of information. It -contains information of interest to the component that receives the intent -(such as the action to be taken and the data to act on) plus information -of interest to the Android system (such as the category of component that -should handle the intent and instructions on how to launch a target activity). -Principally, it can contain the following: -

      - -
      - -
      Component name
      -
      The name of the component that should handle the intent. This field is -a {@link android.content.ComponentName} object — a combination of the -fully qualified class name of the target component (for example "{@code -com.example.project.app.FreneticActivity}") and the package name set -in the manifest file of the application where the component resides (for -example, "{@code com.example.project}"). The package part of the component -name and the package name set in the manifest do not necessarily have to match. - -

      -The component name is optional. If it is set, the Intent object is -delivered to an instance of the designated class. If it is not set, -Android uses other information in the Intent object to locate a suitable -target — see Intent Resolution, later in this -document. -

      - -

      -The component name is set by {@link android.content.Intent#setComponent -setComponent()}, {@link android.content.Intent#setClass -setClass()}, or {@link android.content.Intent#setClassName(String, String) -setClassName()} and read by {@link android.content.Intent#getComponent -getComponent()}. -

      -
      - -

      Action
      -
      A string naming the action to be performed — or, in the case of broadcast -intents, the action that took place and is being reported. The Intent class defines -a number of action constants, including these: -

      - - - - - - - - - - - - - - - -
      ConstantTarget componentAction
      {@code ACTION_CALL} - activity - Initiate a phone call. -
      {@code ACTION_EDIT} - activity - Display data for the user to edit. -
      {@code ACTION_MAIN} - activity - Start up as the initial activity of a task, with no data input and no returned output. -
      {@code ACTION_SYNC} - activity - Synchronize data on a server with data on the mobile device. -
      {@code ACTION_BATTERY_LOW} - broadcast receiver - A warning that the battery is low. -
      {@code ACTION_HEADSET_PLUG} - broadcast receiver - A headset has been plugged into the device, or unplugged from it. -
      {@code ACTION_SCREEN_ON} - broadcast receiver - The screen has been turned on. -
      {@code ACTION_TIMEZONE_CHANGED} - broadcast receiver - The setting for the time zone has changed. -
      - -

      -See the {@link android.content.Intent} class description for a list of -pre-defined constants for generic actions. Other actions are defined -elsewhere in the Android API. -You can also define your own action strings for activating the components -in your application. Those you invent should include the application -package as a prefix — for example: -"com.example.project.SHOW_COLOR". -

      - -

      -The action largely determines how the rest of the intent is structured -— particularly the data and -extras fields — -much as a method name determines a set of arguments and a return value. -For this reason, it's a good idea to use action names that are -as specific as possible, and to couple them tightly to the other fields of -the intent. In other words, instead of defining an action in isolation, -define an entire protocol for the Intent objects your components can handle. -

      - -

      -The action in an Intent object is set by the -{@link android.content.Intent#setAction setAction()} -method and read by -{@link android.content.Intent#getAction getAction()}. -

      -
      - -

      Data
      -
      The URI of the data to be acted on and the MIME type of that data. Different -actions are paired with different kinds of data specifications. For example, if -the action field is {@code ACTION_EDIT}, -the data field would contain the URI of the document to be displayed for editing. -If the action is {@code ACTION_CALL}, the data field would be a {@code tel:} URI -with the number to call. Similarly, if the action is {@code ACTION_VIEW} and the -data field is an {@code http:} URI, the receiving activity would be called upon -to download and display whatever data the URI refers to. - -

      -When matching an intent to a component that is capable of handling the data, -it's often important to know the type of data (its MIME type) in addition to its URI. -For example, a component able to display image data should not be called -upon to play an audio file. -

      - -

      -In many cases, the data type can be inferred from the URI — particularly -{@code content:} URIs, which indicate that the data is located on the device and -controlled by a content provider (see the -separate -discussion on content providers). But the type can also be explicitly set -in the Intent object. -The {@link android.content.Intent#setData setData()} method specifies -data only as a URI, {@link android.content.Intent#setType setType()} -specifies it only as a MIME type, and {@link -android.content.Intent#setDataAndType setDataAndType()} specifies it as both -a URI and a MIME type. The URI is read by {@link -android.content.Intent#getData getData()} and the type by {@link -android.content.Intent#getType getType()}. -

      -
      - -

      Category
      -
      A string containing additional information about the kind of component -that should handle the intent. Any number of category descriptions can be -placed in an Intent object. As it does for actions, the Intent class defines -several category constants, including these: - - - - - - - - - - - -
      ConstantMeaning
      {@code CATEGORY_BROWSABLE} - The target activity can be safely invoked by the browser to display data - referenced by a link — for example, an image or an e-mail message. -
      {@code CATEGORY_GADGET} - The activity can be embedded inside of another activity that hosts gadgets. -
      {@code CATEGORY_HOME} - The activity displays the home screen, the first screen the user sees when - the device is turned on or when the Home button is pressed. -
      {@code CATEGORY_LAUNCHER} - The activity can be the initial activity of a task and is listed in - the top-level application launcher. -
      {@code CATEGORY_PREFERENCE} - The target activity is a preference panel. -
      - -

      -See the {@link android.content.Intent} class description for the full list of -categories. -

      - -

      -The {@link android.content.Intent#addCategory addCategory()} method -places a category in an Intent object, {@link android.content.Intent#removeCategory -removeCategory()} deletes a category previously added, and {@link android.content.Intent#getCategories getCategories()} gets the set of all -categories currently in the object. -

      -
      - -

      Extras
      -
      Key-value pairs for additional information that should be delivered to the -component handling the intent. Just as some actions are paired with particular -kinds of data URIs, some are paired with particular extras. For example, an -{@code ACTION_TIMEZONE_CHANGED} intent has a "{@code time-zone}" extra that -identifies the new time zone, and {@code ACTION_HEADSET_PLUG} has a -"{@code state}" extra indicating whether the headset is now plugged in or -unplugged, as well as a "{@code name}" extra for the type of headset. -If you were to invent a {@code SHOW_COLOR} action, the color value would -be set in an extra key-value pair. - -

      -The Intent object has a series of {@code put...()} methods for inserting various -types of extra data and a similar set of {@code get...()} methods for reading -the data. These methods parallel those for {@link android.os.Bundle} objects. -In fact, the extras can be installed and read as a Bundle using the {@link -android.content.Intent#putExtras putExtras()} and {@link -android.content.Intent#getExtras getExtras()} methods. -

      -
      - -

      Flags
      -
      Flags of various sorts. Many instruct the Android system how to launch an -activity (for example, which task the activity should belong to) and how to treat -it after it's launched (for example, whether it belongs in the list of recent -activities). All these flags are defined in the Intent class. -
      - -
      - -

      -The Android system and the applications that come with the platform employ -Intent objects both to send out system-originated broadcasts and to activate -system-defined components. To see how to structure an intent to activate a -system component, consult the -list of intents -in the reference. -

      - - -

      Intent Resolution

      - -

      -Intents can be divided into two groups: -

      - -
        -
      • Explicit intents designate the target component by its -name (the component name field, mentioned earlier, -has a value set). Since component names would generally not be known to -developers of other applications, explicit intents are typically used -for application-internal messages — such as an activity starting -a subordinate service or launching a sister activity.
      • - -
      • Implicit intents do not name a target (the field for -the component name is blank). Implicit intents are often used to -activate components in other applications.

      • -
      - -

      -Android delivers an explicit intent to an instance of the designated -target class. Nothing in the Intent object other than the component -name matters for determining which component should get the intent. -

      - -

      -A different strategy is needed for implicit intents. In the absence of a -designated target, the Android system must find the best component (or -components) to handle the intent — a single activity or service to -perform the requested action or the set of broadcast receivers to respond -to the broadcast announcement. It does so by comparing the contents of -the Intent object to intent filters, structures associated with -components that can potentially receive intents. Filters advertise the -capabilities of a component and delimit the intents it can handle. They -open the component to the possibility of receiving implicit intents of -the advertised type. If a component does not have any intent filters, -it can receive only explicit intents. A component with filters can -receive both explicit and implicit intents. -

      - -

      -Only three aspects of an Intent object are consulted when the object -is tested against an intent filter: -

      - -

      action -
      data (both URI and data type) -
      category

      - -

      -The extras and flags play no part in resolving which component receives -an intent. -

      - - -

      Intent filters

      - -

      -To inform the system which implicit intents they can handle, activities, -services, and broadcast receivers can have one or more intent filters. -Each filter describes a capability of the component, a set of intents that -the component is willing to receive. It, in effect, filters in -intents of a desired type, while filtering out unwanted -intents — but only unwanted implicit intents (those that don't name -a target class). An explicit intent is always delivered to its target, -no matter what it contains; the filter is not consulted. But an implicit -intent is delivered to a component only if it can pass through one of the -component's filters. -

      - -

      -A component has separate filters for each job it can do, each face it can -present to the user. For example, the NoteEditor activity of the sample -Note Pad application has two filters — one for starting up with a -specific note that the user can view or edit, and another for starting -with a new, blank note that the user can fill in and save. (All of Note -Pad's filters are described in the Note Pad Example -section, later.) -

      - - - -

      -An intent filter is an instance of the {@link android.content.IntentFilter} class. -However, since the Android system must know about the capabilities of a component -before it can launch that component, intent filters are generally not set up in -Java code, but in the application's manifest file (AndroidManifest.xml) as -<intent-filter> -elements. (The one exception would be filters for -broadcast receivers that are registered dynamically by calling {@link android.content.Context#registerReceiver(BroadcastReceiver, IntentFilter, String, -Handler) Context.registerReceiver()}; they are directly created as -IntentFilter objects.) -

      - -

      -A filter has fields that parallel the action, data, and category fields of an -Intent object. An implicit intent is tested against the filter in all three areas. -To be delivered to the component that owns the filter, it must pass all three tests. -If it fails even one of them, the Android system won't deliver it to the -component — at least not on the basis of that filter. However, since a -component can have multiple intent filters, an intent that does not pass -through one of a component's filters might make it through on another. -

      - -

      -Each of the three tests is described in detail below: -

      - -
      - -
      Action test
      -
      An -<intent-filter> -element in the manifest file lists actions as -<action> -subelements. For example: - -
      <intent-filter . . . >
      -    <action android:name="com.example.project.SHOW_CURRENT" />
      -    <action android:name="com.example.project.SHOW_RECENT" />
      -    <action android:name="com.example.project.SHOW_PENDING" />
      -    . . .
      -</intent-filter>
      - -

      -As the example shows, while an Intent object names just a single action, -a filter may list more than one. The list cannot be empty; a filter must -contain at least one {@code <action>} element, or it -will block all intents. -

      - -

      -To pass this test, the action specified in the Intent object must match -one of the actions listed in the filter. If the object or the filter -does not specify an action, the results are as follows: -

      - -
        -
      • If the filter fails to list any actions, there is nothing for an -intent to match, so all intents fail the test. No intents can get -through the filter.
      • - -
      • On the other hand, an Intent object that doesn't specify an -action automatically passes the test — as long as the filter -contains at least one action.

      • -
      - -
      Category test
      -
      An -<intent-filter> -element also lists categories as subelements. For example: - -
      <intent-filter . . . >
      -    <category android:name="android.intent.category.DEFAULT" />
      -    <category android:name="android.intent.category.BROWSABLE" />
      -    . . .
      -</intent-filter>
      - -

      -Note that the constants described earlier for actions and categories are not -used in the manifest file. The full string values are used instead. For -instance, the "{@code android.intent.category.BROWSABLE}" string in the example -above corresponds to the {@code CATEGORY_BROWSABLE} constant mentioned earlier -in this document. Similarly, the string "{@code android.intent.action.EDIT}" -corresponds to the {@code ACTION_EDIT} constant. -

      - -

      -For an intent to pass the category test, every category in the Intent object -must match a category in the filter. The filter can list additional categories, -but it cannot omit any that are in the intent. -

      - -

      -In principle, therefore, an Intent object with no categories should always pass -this test, regardless of what's in the filter. That's mostly true. However, -with one exception, Android treats all implicit intents passed to {@link -android.content.Context#startActivity startActivity()} as if they contained -at least one category: "{@code android.intent.category.DEFAULT}" (the -{@code CATEGORY_DEFAULT} constant). -Therefore, activities that are willing to receive implicit intents must -include "{@code android.intent.category.DEFAULT}" in their intent filters. -(Filters with "{@code android.intent.action.MAIN}" and -"{@code android.intent.category.LAUNCHER}" settings are the exception. -They mark activities that begin new tasks and that are represented on the -launcher screen. They can include "{@code android.intent.category.DEFAULT}" -in the list of categories, but don't need to.) See Using -intent matching, later, for more on these filters.) -

      -
      - -
      Data test
      -
      Like the action and categories, the data specification for an intent filter -is contained in a subelement. And, as in those cases, the subelement can appear -multiple times, or not at all. For example: - -
      <intent-filter . . . >
      -    <data android:mimeType="video/mpeg" android:scheme="http" . . . /> 
      -    <data android:mimeType="audio/mpeg" android:scheme="http" . . . />
      -    . . .
      -</intent-filter>
      - -

      -Each -<data> -element can specify a URI and a data type (MIME media type). There are separate -attributes — {@code scheme}, {@code host}, {@code port}, -and {@code path} — for each part of the URI: -

      - -

      {@code scheme://host:port/path}

      - -

      -For example, in the following URI, -

      - -

      {@code content://com.example.project:200/folder/subfolder/etc}

      - -

      the scheme is "{@code content}", the host is "{@code com.example.project}", -the port is "{@code 200}", and the path is "{@code folder/subfolder/etc}". -The host and port together constitute the URI authority; if a host is -not specified, the port is ignored. -

      - -

      -Each of these attributes is optional, but they are not independent of each other: -For an authority to be meaningful, a scheme must also be specified. -For a path to be meaningful, both a scheme and an authority must be specified. -

      - -

      -When the URI in an Intent object is compared to a URI specification in a filter, -it's compared only to the parts of the URI actually mentioned in the filter. -For example, if a filter specifies only a scheme, all URIs with that scheme match -the filter. If a filter specifies a scheme and an authority but no path, all URIs -with the same scheme and authority match, regardless of their paths. If a filter -specifies a scheme, an authority, and a path, only URIs with the same scheme, -authority, and path match. However, a path specification in the filter can -contain wildcards to require only a partial match of the path. -

      - -

      -The {@code type} attribute of a {@code <data>} element specifies the MIME type -of the data. It's more common in filters than a URI. Both the Intent object and -the filter can use a "*" wildcard for the subtype field — for example, -"{@code text/*}" or "{@code audio/*}" — indicating any subtype matches. -

      - -

      -The data test compares both the URI and the data type in the Intent object to a URI -and data type specified in the filter. The rules are as follows: -

      - -
        -
      1. An Intent object that contains neither a URI nor a data type passes the -test only if the filter likewise does not specify any URIs or data types.
      2. - -
      3. An Intent object that contains a URI but no data type (and a type cannot -be inferred from the URI) passes the test only if its URI matches a URI in the -filter and the filter likewise does not specify a type. This will be the case -only for URIs like {@code mailto:} and {@code tel:} that do not refer to actual data.

      4. - -
      5. An Intent object that contains a data type but not a URI passes the test -only if the filter lists the same data type and similarly does not specify a URI.

      6. - -
      7. An Intent object that contains both a URI and a data type (or a data type -can be inferred from the URI) passes the data type part of the test only if its -type matches a type listed in the filter. It passes the URI part of the test -either if its URI matches a URI in the filter or if it has a {@code content:} -or {@code file:} URI and the filter does not specify a URI. In other words, -a component is presumed to support {@code content:} and {@code file:} data if -its filter lists only a data type.

      8. -
      -
      - -

      -If an intent can pass through the filters of more than one activity or service, -the user may be asked which component to activate. An exception is raised if -no target can be found. -

      - - -

      Common cases

      - -

      -The last rule shown above for the data test, rule (d), reflects the expectation -that components are able to get local data from a file or content provider. -Therefore, their filters can list just a data type and do not need to explicitly -name the {@code content:} and {@code file:} schemes. -This is a typical case. A {@code <data>} element like the following, -for example, tells Android that the component can get image data from a content -provider and display it: -

      - -
      <data android:mimeType="image/*" />
      - -

      -Since most available data is dispensed by content providers, filters that -specify a data type but not a URI are perhaps the most common. -

      - -

      -Another common configuration is filters with a scheme and a data type. For -example, a {@code <data>} element like the following tells Android that -the component can get video data from the network and display it: -

      - -
      <data android:scheme="http" android:type="video/*" />
      - -

      -Consider, for example, what the browser application does when -the user follows a link on a web page. It first tries to display the data -(as it could if the link was to an HTML page). If it can't display the data, -it puts together an implicit intent with the scheme and data type and tries -to start an activity that can do the job. If there are no takers, it asks the -download manager to download the data. That puts it under the control -of a content provider, so a potentially larger pool of activities -(those with filters that just name a data type) can respond. -

      - -

      -Most applications also have a way to start fresh, without a reference -to any particular data. Activities that can initiate applications -have filters with "{@code android.intent.action.MAIN}" specified as -the action. If they are to be represented in the application launcher, -they also specify the "{@code android.intent.category.LAUNCHER}" -category: -

      - -
      <intent-filter . . . >
      -    <action android:name="code android.intent.action.MAIN" />
      -    <category android:name="code android.intent.category.LAUNCHER" />
      -</intent-filter>
      - - -

      Using intent matching

      - -

      -Intents are matched against intent filters not only to discover a target -component to activate, but also to discover something about the set of -components on the device. For example, the Android system populates the -application launcher, the top-level screen that shows the applications -that are available for the user to launch, by finding all the activities - with intent filters that specify the "{@code android.intent.action.MAIN}" -action and "{@code android.intent.category.LAUNCHER}" category -(as illustrated in the previous section). It then displays the icons and -labels of those activities in the launcher. Similarly, it discovers the -home screen by looking for the activity with -"{@code android.intent.category.HOME}" in its filter. -

      - -

      -Your application can use intent matching is a similar way. -The {@link android.content.pm.PackageManager} has a set of {@code query...()} -methods that return all components that can accept a particular intent, and -a similar series of {@code resolve...()} methods that determine the best -component to respond to an intent. For example, -{@link android.content.pm.PackageManager#queryIntentActivities -queryIntentActivities()} returns a list of all activities that can perform -the intent passed as an argument, and {@link -android.content.pm.PackageManager#queryIntentServices -queryIntentServices()} returns a similar list of services. -Neither method activates the components; they just list the ones that -can respond. There's a similar method, -{@link android.content.pm.PackageManager#queryBroadcastReceivers -queryBroadcastReceivers()}, for broadcast receivers. -

      - -

      Note Pad Example

      - -

      -The Note Pad sample application enables users to browse through a list -of notes, view details about individual items in the list, edit the items, -and add a new item to the list. This section looks at the intent filters -declared in its manifest file. (If you're working offline in the SDK, you -can find all the source files for this sample application, including its -manifest file, at {@code <sdk>/samples/NotePad/index.html}. -If you're viewing the documentation online, the source files are in the -Tutorials and Sample Code -section here.) -

      - -

      -In its manifest file, the Note Pad application declares three activities, -each with at least one intent filter. It also declares a content provider -that manages the note data. Here is the manifest file in its entirety: -

      - -
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      -          package="com.example.android.notepad">
      -    <application android:icon="@drawable/app_notes"
      -                 android:label="@string/app_name" >
      -
      -        <provider android:name="NotePadProvider"
      -                  android:authorities="com.google.provider.NotePad" />
      -
      -        <activity android:name="NotesList" android:label="@string/title_notes_list">
      -            <intent-filter>
      -                <action android:name="android.intent.action.MAIN" />
      -                <category android:name="android.intent.category.LAUNCHER" />
      -            </intent-filter>
      -            <intent-filter>
      -                <action android:name="android.intent.action.VIEW" />
      -                <action android:name="android.intent.action.EDIT" />
      -                <action android:name="android.intent.action.PICK" />
      -                <category android:name="android.intent.category.DEFAULT" />
      -                <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
      -            </intent-filter>
      -            <intent-filter>
      -                <action android:name="android.intent.action.GET_CONTENT" />
      -                <category android:name="android.intent.category.DEFAULT" />
      -                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
      -            </intent-filter>
      -        </activity>
      -        
      -        <activity android:name="NoteEditor"
      -                  android:theme="@android:style/Theme.Light"
      -                  android:label="@string/title_note" >
      -            <intent-filter android:label="@string/resolve_edit">
      -                <action android:name="android.intent.action.VIEW" />
      -                <action android:name="android.intent.action.EDIT" />
      -                <action android:name="com.android.notepad.action.EDIT_NOTE" />
      -                <category android:name="android.intent.category.DEFAULT" />
      -                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
      -            </intent-filter>
      -            <intent-filter>
      -                <action android:name="android.intent.action.INSERT" />
      -                <category android:name="android.intent.category.DEFAULT" />
      -                <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
      -            </intent-filter>
      -        </activity>
      -        
      -        <activity android:name="TitleEditor" 
      -                  android:label="@string/title_edit_title"
      -                  android:theme="@android:style/Theme.Dialog">
      -            <intent-filter android:label="@string/resolve_title">
      -                <action android:name="com.android.notepad.action.EDIT_TITLE" />
      -                <category android:name="android.intent.category.DEFAULT" />
      -                <category android:name="android.intent.category.ALTERNATIVE" />
      -                <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
      -                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
      -            </intent-filter>
      -        </activity>
      -        
      -    </application>
      -</manifest>
      - -

      -The first activity, NotesList, is -distinguished from the other activities by the fact that it operates -on a directory of notes (the note list) rather than on a single note. -It would generally serve as the initial user interface into the -application. It can do three things as described by its three intent -filters: -

      - -
        -
      1. <intent-filter>
        -    <action android:name="android.intent.action.MAIN" />
        -    <category android:name="android.intent.category.LAUNCHER" />
        -</intent-filter>
        - -

        -This filter declares the main entry point into the Note Pad application. -The standard {@code MAIN} action is an entry point that does not require -any other information in the Intent (no data specification, for example), -and the {@code LAUNCHER} category says that this entry point should be -listed in the application launcher. -

      2. - -
      3. <intent-filter>
        -    <action android:name="android.intent.action.VIEW" />
        -    <action android:name="android.intent.action.EDIT" />
        -    <action android:name="android.intent.action.PICK" />
        -    <category android:name="android.intent.category.DEFAULT" />
        -    <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
        -</intent-filter>
        - -

        -This filter declares the things that the activity can do on a directory -of notes. It can allow the user to view or edit the directory (via -the {@code VIEW} and {@code EDIT} actions), or to pick a particular note -from the directory (via the {@code PICK} action). -

        - -

        -The {@code mimeType} attribute of the -<data> -element specifies the kind of data that these actions operate on. It -indicates that the activity can get a Cursor over zero or more items -({@code vnd.android.cursor.dir}) from a content provider that holds -Note Pad data ({@code vnd.google.note}). The Intent object that launches -the activity would include a {@code content:} URI specifying the exact -data of this type that the activity should open. -

        - -

        -Note also the {@code DEFAULT} category supplied in this filter. It's -there because the {@link android.content.Context#startActivity -Context.startActivity()} and -{@link android.app.Activity#startActivityForResult -Activity.startActivityForResult()} methods treat all intents -as if they contained the {@code DEFAULT} category — with just -two exceptions: -

        - -
          -
        • Intents that explicitly name the target activity
        • -
        • Intents consisting of the {@code MAIN} action and {@code LAUNCHER} -category
        • -
        - -

        -Therefore, the {@code DEFAULT} category is required for all -filters — except for those with the {@code MAIN} action and -{@code LAUNCHER} category. (Intent filters are not consulted for -explicit intents.) -

      4. - -
      5. <intent-filter>
        -    <action android:name="android.intent.action.GET_CONTENT" />
        -    <category android:name="android.intent.category.DEFAULT" />
        -    <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
        -</intent-filter>
        - -

        -This filter describes the activity's ability to return a note selected by -the user without requiring any specification of the directory the user should -choose from. The {@code GET_CONTENT} action is similar to the {@code PICK} -action. In both cases, the activity returns the URI for a note selected by -the user. (In each case, it's returned to the activity that called -{@link android.app.Activity#startActivityForResult -startActivityForResult()} to start the NoteList activity.) Here, -however, the caller specifies the type of data desired instead of the -directory of data the user will be picking from. -

        - -

        -The data type, vnd.android.cursor.item/vnd.google.note, -indicates the type of data the activity can return — a URI for -a single note. From the returned URI, the caller can get a Cursor for -exactly one item ({@code vnd.android.cursor.item}) from the content -provider that holds Note Pad data ({@code vnd.google.note}). -

        - -

        -In other words, for the {@code PICK} action in the previous filter, -the data type indicates the type of data the activity could display to the -user. For the {@code GET_CONTENT} filter, it indicates the type of data -the activity can return to the caller. -

      6. -
      - -

      -Given these capabilities, the following intents will resolve to the -NotesList activity: -

      - -
      -
      action: android.intent.action.MAIN
      -
      Launches the activity with no data specified.
      - -
      action: android.intent.action.MAIN -
      category: android.intent.category.LAUNCHER
      -
      Launches the activity with no data selected specified. -This is the actual intent used by the Launcher to populate its top-level -list. All activities with filters that match this action and category -are added to the list.
      - -
      action: android.intent.action.VIEW -
      data: content://com.google.provider.NotePad/notes
      -
      Asks the activity to display a list of all the notes under -content://com.google.provider.NotePad/notes. The user can then -browse through the list and get information about the items in it.
      - -
      action: android.intent.action.PICK -
      data: content://com.google.provider.NotePad/notes
      -
      Asks the activity to display a list of the notes under -content://com.google.provider.NotePad/notes. -The user can then pick a note from the list, and the activity will return -the URI for that item back to the activity that started the NoteList activity.
      - -
      action: android.intent.action.GET_CONTENT -
      data type: vnd.android.cursor.item/vnd.google.note
      -
      Asks the activity to supply a single item of Note Pad data.
      -
      - -

      -The second activity, NoteEditor, shows -users a single note entry and allows them to edit it. It can do two things -as described by its two intent filters: - -

        -
      1. <intent-filter android:label="@string/resolve_edit">
        -    <action android:name="android.intent.action.VIEW" />
        -    <action android:name="android.intent.action.EDIT" />
        -    <action android:name="com.android.notepad.action.EDIT_NOTE" />
        -    <category android:name="android.intent.category.DEFAULT" />
        -    <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
        -</intent-filter>
        - -

        -The first, primary, purpose of this activity is to enable the user to -interact with a single note — to either {@code VIEW} the note or -{@code EDIT} it. (The {@code EDIT_NOTE} category is a synonym for -{@code EDIT}.) The intent would contain the URI for data matching the -MIME type vnd.android.cursor.item/vnd.google.note — -that is, the URI for a single, specific note. It would typically be a -URI that was returned by the {@code PICK} or {@code GET_CONTENT} -actions of the NoteList activity. -

        - -

        -As before, this filter lists the {@code DEFAULT} category so that the -activity can be launched by intents that don't explicitly specify the -NoteEditor class. -

      2. - -
      3. <intent-filter>
        -    <action android:name="android.intent.action.INSERT" />
        -    <category android:name="android.intent.category.DEFAULT" />
        -    <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
        -</intent-filter>
        - -

        -The secondary purpose of this activity is to enable the user to create a new -note, which it will {@code INSERT} into an existing directory of notes. The -intent would contain the URI for data matching the MIME type -vnd.android.cursor.dir/vnd.google.note — that -is, the URI for the directory where the note should be placed. -

      4. -
      - -

      -Given these capabilities, the following intents will resolve to the -NoteEditor activity: -

      - -
      -
      action: android.intent.action.VIEW -
      data: content://com.google.provider.NotePad/notes/ID
      -
      Asks the activity to display the content of the note identified -by {@code ID}. (For details on how {@code content:} URIs -specify individual members of a group, see -Content Providers.) - -
      action: android.intent.action.EDIT -
      data: content://com.google.provider.NotePad/notes/ID
      -
      Asks the activity to display the content of the note identified -by {@code ID}, and to let the user edit it. If the user -saves the changes, the activity updates the data for the note in the -content provider.
      - -
      action: android.intent.action.INSERT -
      data: content://com.google.provider.NotePad/notes
      -
      Asks the activity to create a new, empty note in the notes list at -content://com.google.provider.NotePad/notes -and allow the user to edit it. If the user saves the note, its URI -is returned to the caller. -
      -
      - -

      The last activity, TitleEditor, -enables the user to edit the title of a note. This could be implemented -by directly invoking the activity (by explicitly setting its component -name in the Intent), without using an intent filter. But here we take -the opportunity to show how to publish alternative operations on existing -data: -

      - -
      <intent-filter android:label="@string/resolve_title">
      -    <action android:name="com.android.notepad.action.EDIT_TITLE" />
      -    <category android:name="android.intent.category.DEFAULT" />
      -    <category android:name="android.intent.category.ALTERNATIVE" />
      -    <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
      -    <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
      -</intent-filter>
      - -

      -The single intent filter for this activity uses a custom action called -"com.android.notepad.action.EDIT_TITLE". It must be invoked on -a specific note (data type vnd.android.cursor.item/vnd.google.note), -like the previous {@code VIEW} and {@code EDIT} actions. However, here the -activity displays the title contained in the note data, not the content of -the note itself. -

      - -

      -In addition to supporting the usual {@code DEFAULT} category, the title -editor also supports two other standard categories: -{@link android.content.Intent#CATEGORY_ALTERNATIVE ALTERNATIVE} -and {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE -SELECTED_ALTERNATIVE}. -These categories identify activities that can be presented to users in -a menu of options (much as the {@code LAUNCHER} category identifies -activities that should be presented to user in the application launcher). -Note that the filter also supplies an explicit label (via -android:label="@string/resolve_title") to better control -what users see when presented with this activity as an alternative -action to the data they are currently viewing. (For more information -on these categories and building options menus, see the -{@link android.content.pm.PackageManager#queryIntentActivityOptions -PackageManager.queryIntentActivityOptions()} and -{@link android.view.Menu#addIntentOptions Menu.addIntentOptions()} -methods.) -

      - -

      -Given these capabilities, the following intent will resolve to the -TitleEditor activity: -

      - -
      -
      action: com.android.notepad.action.EDIT_TITLE -
      data: content://com.google.provider.NotePad/notes/ID
      -
      Asks the activity to display the title associated with note ID, and -allow the user to edit the title.
      -
      - - - - - - - - - - - diff --git a/docs/html/guide/topics/location/index.jd b/docs/html/guide/topics/location/index.jd index 8a2e9cdb2bae..54c034d9cd13 100644 --- a/docs/html/guide/topics/location/index.jd +++ b/docs/html/guide/topics/location/index.jd @@ -13,8 +13,7 @@ device's location and bearing and register for updates

      Topics

        -
      1. Obtaining User -Location
      2. +
      3. Location Strategies

      See Also

      @@ -58,8 +57,7 @@ comes within a given proximity (specified by radius in meters) of a given lat/lo

      For more information, read the guide to Obtaining User -Location.

      +href="{@docRoot}guide/topics/location/strategies.html">Location Strategies.

      Google Maps External Library

      @@ -98,8 +96,8 @@ Google APIs add-on, visit

      href="http://code.google.com/android/add-ons/google-apis">http://code.google.com/android/add-ons/google-apis

      For your convenience, the Google APIs add-on is also available as a downloadable component from -the Android SDK Manager (see Adding SDK -Components).

      +the Android SDK Manager (see Exploring the +SDK).

      Note: In order to display Google Maps data in a MapView, you must register with the Google Maps service and obtain a Maps API diff --git a/docs/html/guide/topics/location/obtaining-user-location.jd b/docs/html/guide/topics/location/obtaining-user-location.jd deleted file mode 100644 index 3b450f0d403a..000000000000 --- a/docs/html/guide/topics/location/obtaining-user-location.jd +++ /dev/null @@ -1,454 +0,0 @@ -page.title=Obtaining User Location -parent.title=Location and Maps -parent.link=index.html -@jd:body - -

      -
      - -

      Quickview

      -
        -
      • The Network Location Provider provides good location data without using GPS
      • -
      • Obtaining user location can consume a lot of battery, so be careful how -long you listen for updates
      • -
      -

      In this document

      -
        -
      1. Challenges in Determining User Location
      2. -
      3. Requesting Location Updates -
          -
        1. Requesting User Permissions
        2. -
        -
      4. -
      5. Defining a Model for the Best Performance -
          -
        1. Flow for obtaining user location
        2. -
        3. Deciding when to start listening for updates
        4. -
        5. Getting a fast fix with the last known location
        6. -
        7. Deciding when to stop listening for updates
        8. -
        9. Maintaining a current best estimate
        10. -
        11. Adjusting the model to save battery and data exchange
        12. -
        -
      6. -
      7. Providing Mock Location Data
      8. -
      -

      Key classes

      -
        -
      1. {@link android.location.LocationManager}
      2. -
      3. {@link android.location.LocationListener}
      4. -
      -
      -
      - -

      Knowing where the user is allows your application to be smarter and deliver -better information to the user. When developing a location-aware application for Android, you can -utilize GPS and Android's Network Location Provider to acquire the user location. Although -GPS is most accurate, it only works outdoors, it quickly consumes battery power, and doesn't return -the location as quickly as users want. Android's Network Location Provider determines user location -using cell tower and Wi-Fi signals, providing location information in a way that -works indoors and outdoors, responds faster, and uses less battery power. To obtain the user -location in your application, you can use both GPS and the Network Location Provider, or just -one.

      - - -

      Challenges in Determining User Location

      - -

      Obtaining user location from a mobile device can be complicated. There are several reasons -why a location reading (regardless of the source) can contain errors and be inaccurate. -Some sources of error in the user location include:

      - -
        -
      • Multitude of location sources -

        GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use -and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency.

        -
      • -
      • User movement -

        Because the user location changes, you must account for movement by re-estimating user -location every so often.

        -
      • -
      • Varying accuracy -

        Location estimates coming from each location source are not consistent in their -accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest -location from another or same source.

        -
      • -
      - -

      These problems can make it difficult to obtain a reliable user location reading. This -document provides information to help you meet these challenges to obtain a reliable location -reading. It also provides ideas that you can use in your -application to provide the user with an accurate and responsive geo-location experience.

      - - -

      Requesting Location Updates

      - -

      Before addressing some of the location errors described above, here is an introduction to -how you can obtain user location on Android.

      - -

      Getting user location in Android works by means of callback. You indicate that you'd -like to receive location updates from the {@link android.location.LocationManager} ("Location -Manager") by calling {@link android.location.LocationManager#requestLocationUpdates -requestLocationUpdates()}, passing it a -{@link android.location.LocationListener}. Your {@link android.location.LocationListener} must -implement several callback methods that the Location Manager calls when the user location -changes or when the status of the service changes.

      - -

      For example, the following code shows how to define a {@link android.location.LocationListener} -and request location updates: -

      - -
      -// Acquire a reference to the system Location Manager
      -LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
      -
      -// Define a listener that responds to location updates
      -LocationListener locationListener = new LocationListener() {
      -    public void onLocationChanged(Location location) {
      -      // Called when a new location is found by the network location provider.
      -      makeUseOfNewLocation(location);
      -    }
      -
      -    public void onStatusChanged(String provider, int status, Bundle extras) {}
      -
      -    public void onProviderEnabled(String provider) {}
      -
      -    public void onProviderDisabled(String provider) {}
      -  };
      -
      -// Register the listener with the Location Manager to receive location updates
      -locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
      -
      - -

      The first parameter in {@link -android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} is the type of -location provider to use (in this case, the Network Location Provider for cell tower and Wi-Fi -based location). You can control the frequency at which your listener receives updates -with the second and third parameter—the second is the minimum time interval between -notifications and the third is the minimum change in distance between notifications—setting -both to zero requests location notifications as frequently as possible. The last parameter is your -{@link android.location.LocationListener}, which receives callbacks for location updates.

      - -

      To request location updates from the GPS provider, -substitute GPS_PROVIDER for NETWORK_PROVIDER. You can also request -location updates from both the GPS and the Network Location Provider by calling {@link -android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} twice—once -for NETWORK_PROVIDER and once for GPS_PROVIDER.

      - - -

      Requesting User Permissions

      - -

      In order to receive location updates from NETWORK_PROVIDER or -GPS_PROVIDER, you must request user permission by declaring either the {@code -ACCESS_COARSE_LOCATION} or {@code ACCESS_FINE_LOCATION} permission, respectively, in your Android -manifest file. For example:

      - -
      -<manifest ... >
      -    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      -    ...
      -</manifest>
      -
      - -

      Without these permissions, your application will fail at runtime when requesting -location updates.

      - -

      Note: If you are using both NETWORK_PROVIDER and -GPS_PROVIDER, then you need to request only the {@code ACCESS_FINE_LOCATION} -permission, because it includes permission for both providers. (Permission for {@code -ACCESS_COARSE_LOCATION} includes permission only for NETWORK_PROVIDER.)

      - - -

      Defining a Model for the Best Performance

      - -

      Location-based applications are now commonplace, but due to the less than optimal -accuracy, user movement, the multitude of methods to obtain the location, and the desire to conserve -battery, getting user location is complicated. To overcome the obstacles of obtaining a good user -location while preserving battery power, you must define a consistent model that specifies how your -application obtains the user location. This model includes when you start and stop listening for -updates and when to use cached location data.

      - - -

      Flow for obtaining user location

      - -

      Here's the typical flow of procedures for obtaining the user location:

      - -
        -
      1. Start application.
      2. -
      3. Sometime later, start listening for updates from desired location providers.
      4. -
      5. Maintain a "current best estimate" of location by filtering out new, but less accurate -fixes.
      6. -
      7. Stop listening for location updates.
      8. -
      9. Take advantage of the last best location estimate.
      10. -
      - -

      Figure 1 demonstrates this model in a timeline that visualizes the period in which an -application is listening for location updates and the events that occur during that time.

      - - -

      Figure 1. A timeline representing the window in which an -application listens for location updates.

      - -

      This model of a window—during which location updates are received—frames many of -the decisions you need to make when adding location-based services to your application.

      - - -

      Deciding when to start listening for updates

      - -

      You might want to start listening for location updates as soon as your application starts, or -only after users activate a certain feature. Be aware that long windows of listening for location -fixes can consume a lot of battery power, but short periods might not allow for sufficient -accuracy.

      - -

      As demonstrated above, you can begin listening for updates by calling {@link -android.location.LocationManager#requestLocationUpdates requestLocationUpdates()}:

      - -
      -LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
      -// Or, use GPS location data:
      -// LocationProvider locationProvider = LocationManager.GPS_PROVIDER;
      -
      -locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
      -
      - - -

      Getting a fast fix with the last known location

      - -

      The time it takes for your location listener to receive the first location fix is often too -long for users wait. Until a more accurate location is provided to your location listener, you -should utilize a cached location by calling {@link -android.location.LocationManager#getLastKnownLocation}:

      -
      -LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
      -// Or use LocationManager.GPS_PROVIDER
      -
      -Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
      -
      - - -

      Deciding when to stop listening for updates

      - -

      The logic of deciding when new fixes are no longer necessary might range from very simple to -very complex depending on your application. A short gap between when the location is acquired and -when the location is used, improves the accuracy of the estimate. Always beware that listening for a -long time consumes a lot of battery power, so as soon as you have the information you need, you -should stop -listening for updates by calling {@link android.location.LocationManager#removeUpdates}:

      -
      -// Remove the listener you previously added
      -locationManager.removeUpdates(locationListener);
      -
      - - -

      Maintaining a current best estimate

      - -

      You might expect that the most recent location fix is the most accurate. -However, because the accuracy of a location fix varies, the most recent fix is not always the best. -You should include logic for choosing location fixes based on several criteria. The criteria also -varies depending on the use-cases of the application and field testing.

      - -

      Here are a few steps you can take to validate the accuracy of a location fix:

      -
        -
      • Check if the location retrieved is significantly newer than the previous estimate.
      • -
      • Check if the accuracy claimed by the location is better or worse than the previous -estimate.
      • -
      • Check which provider the new location is from and determine if you trust it more.
      • -
      - -

      An elaborate example of this logic can look something like this:

      - -
      -private static final int TWO_MINUTES = 1000 * 60 * 2;
      -
      -/** Determines whether one Location reading is better than the current Location fix
      -  * @param location  The new Location that you want to evaluate
      -  * @param currentBestLocation  The current Location fix, to which you want to compare the new one
      -  */
      -protected boolean isBetterLocation(Location location, Location currentBestLocation) {
      -    if (currentBestLocation == null) {
      -        // A new location is always better than no location
      -        return true;
      -    }
      -
      -    // Check whether the new location fix is newer or older
      -    long timeDelta = location.getTime() - currentBestLocation.getTime();
      -    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
      -    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
      -    boolean isNewer = timeDelta > 0;
      -
      -    // If it's been more than two minutes since the current location, use the new location
      -    // because the user has likely moved
      -    if (isSignificantlyNewer) {
      -        return true;
      -    // If the new location is more than two minutes older, it must be worse
      -    } else if (isSignificantlyOlder) {
      -        return false;
      -    }
      -
      -    // Check whether the new location fix is more or less accurate
      -    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
      -    boolean isLessAccurate = accuracyDelta > 0;
      -    boolean isMoreAccurate = accuracyDelta < 0;
      -    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
      -
      -    // Check if the old and new location are from the same provider
      -    boolean isFromSameProvider = isSameProvider(location.getProvider(),
      -            currentBestLocation.getProvider());
      -
      -    // Determine location quality using a combination of timeliness and accuracy
      -    if (isMoreAccurate) {
      -        return true;
      -    } else if (isNewer && !isLessAccurate) {
      -        return true;
      -    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
      -        return true;
      -    }
      -    return false;
      -}
      -
      -/** Checks whether two providers are the same */
      -private boolean isSameProvider(String provider1, String provider2) {
      -    if (provider1 == null) {
      -      return provider2 == null;
      -    }
      -    return provider1.equals(provider2);
      -}
      -
      - - -

      Adjusting the model to save battery and data exchange

      - -

      As you test your application, you might find that your model for providing good location and -good performance needs some adjustment. Here are some things you might change to find a good -balance between the two.

      - -

      Reduce the size of the window

      - -

      A smaller window in which you listen for location updates means less interaction with GPS and -network location services, thus, preserving battery life. But it also allows for fewer locations -from which to choose a best estimate.

      - -

      Set the location providers to return updates less frequently

      - -

      Reducing the rate at which new updates appear during the window can also improve battery -efficiency, but at the cost of accuracy. The value of the trade-off depends on how your -application is used. You can reduce the rate of updates by increasing the parameters in {@link -android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} that specify the -interval time and minimum distance change.

      - -

      Restrict a set of providers

      - -

      Depending on the environment where your application is used or the desired level of accuracy, -you might choose to use only the Network Location Provider or only GPS, instead of both. Interacting -with only one of the services reduces battery usage at a potential cost of accuracy.

      - - -

      Common application cases

      - -

      There are many reasons you might want to obtain the user location in your application. Below -are a couple scenarios in which you can use the user location to enrich your application. Each -scenario also describes good practices for when you should start and stop listening for the -location, in order to get a good reading and help preserve battery life.

      - - -

      Tagging user-created content with a location

      - -

      You might be creating an application where user-created content is tagged with a location. -Think of users sharing their local experiences, posting a review for a restaurant, or recording some -content that can be augmented with their current location. A model of how this -interaction might happen, with respect to the location services, is visualized in figure 2.

      - - -

      Figure 2. A timeline representing the window in which -the user location is obtained and listening stops when the user consumes the current location.

      - -

      This lines up with the previous model of how user location is obtained in code (figure 1). For -best location accuracy, you might choose to start listening for location updates when users begin -creating -the content or even when the application starts, then stop listening for updates when content is -ready to be posted or recorded. You might need to consider how long a typical task of creating the -content takes and judge if this duration allows for efficient collection of a location estimate.

      - - -

      Helping the user decide on where to go

      - -

      You might be creating an application that attempts to provide users with a set -of options about where to go. For example, you're looking to provide a list of nearby restaurants, -stores, and entertainment and the order of recommendations changes depending on the user -location.

      - -

      To accommodate such a flow, you might choose to:

      -
        -
      • Rearrange recommendations when a new best estimate is obtained
      • -
      • Stop listening for updates if the order of recommendations has stabilized
      • -
      - -

      This kind of model is visualized in figure 3.

      - - -

      Figure 3. A timeline representing the window in which a -dynamic set of data is updated each time the user location updates.

      - - - - -

      Providing Mock Location Data

      - -

      As you develop your application, you'll certainly need to test how well your model for obtaining -user location works. This is most easily done using a real Android-powered device. If, however, you -don't have a device, you can still test your location-based features by mocking location data in -the Android emulator. There are three different ways to send your application mock location -data: using Eclipse, DDMS, or the "geo" command in the emulator console.

      - -

      Note: Providing mock location data is injected as GPS location -data, so you must request location updates from GPS_PROVIDER in order for mock location -data to work.

      - -

      Using Eclipse

      - -

      Select Window > Show View > Other > Emulator Control.

      - -

      In the Emulator Control panel, enter GPS coordinates under Location Controls as individual -lat/long coordinates, with a GPX file for route playback, or a KML file for multiple place marks. -(Be sure that you have a device selected in the Devices panel—available from Window -> Show View > Other > Devices.)

      - - -

      Using DDMS

      - -

      With the DDMS tool, you can simulate location data a few different ways:

      -
        -
      • Manually send individual longitude/latitude coordinates to the device.
      • -
      • Use a GPX file describing a route for playback to the device.
      • -
      • Use a KML file describing individual place marks for sequenced playback to the device.
      • -
      - -

      For more information on using DDMS to spoof location data, see -Using DDMS. - - -

      Using the "geo" command in the emulator console

      - -

      To send mock location data from the command line:

      - -
        -
      1. Launch your application in the Android emulator and open a terminal/console in your SDK's -/tools directory.
      2. -
      3. Connect to the emulator console: -
        telnet localhost <console-port>
      4. -
      5. Send the location data:

        -
        • geo fix to send a fixed geo-location. -

          This command accepts a longitude and latitude in decimal degrees, and - an optional altitude in meters. For example:

          -
          geo fix -121.45356 46.51119 4392
          -
        • -
        • geo nmea to send an NMEA 0183 sentence. -

          This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit - data). - For example:

          -
          geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
          -
        • -
        -
      6. -
      - -

      For information about how to connect to the emulator console, see -Using the Emulator Console.

      diff --git a/docs/html/guide/topics/location/strategies.jd b/docs/html/guide/topics/location/strategies.jd new file mode 100644 index 000000000000..f7909536f2f8 --- /dev/null +++ b/docs/html/guide/topics/location/strategies.jd @@ -0,0 +1,454 @@ +page.title=Location Strategies +parent.title=Location and Maps +parent.link=index.html +@jd:body + +
      +
      + +

      Quickview

      +
        +
      • The Network Location Provider provides good location data without using GPS
      • +
      • Obtaining user location can consume a lot of battery, so be careful how +long you listen for updates
      • +
      +

      In this document

      +
        +
      1. Challenges in Determining User Location
      2. +
      3. Requesting Location Updates +
          +
        1. Requesting User Permissions
        2. +
        +
      4. +
      5. Defining a Model for the Best Performance +
          +
        1. Flow for obtaining user location
        2. +
        3. Deciding when to start listening for updates
        4. +
        5. Getting a fast fix with the last known location
        6. +
        7. Deciding when to stop listening for updates
        8. +
        9. Maintaining a current best estimate
        10. +
        11. Adjusting the model to save battery and data exchange
        12. +
        +
      6. +
      7. Providing Mock Location Data
      8. +
      +

      Key classes

      +
        +
      1. {@link android.location.LocationManager}
      2. +
      3. {@link android.location.LocationListener}
      4. +
      +
      +
      + +

      Knowing where the user is allows your application to be smarter and deliver +better information to the user. When developing a location-aware application for Android, you can +utilize GPS and Android's Network Location Provider to acquire the user location. Although +GPS is most accurate, it only works outdoors, it quickly consumes battery power, and doesn't return +the location as quickly as users want. Android's Network Location Provider determines user location +using cell tower and Wi-Fi signals, providing location information in a way that +works indoors and outdoors, responds faster, and uses less battery power. To obtain the user +location in your application, you can use both GPS and the Network Location Provider, or just +one.

      + + +

      Challenges in Determining User Location

      + +

      Obtaining user location from a mobile device can be complicated. There are several reasons +why a location reading (regardless of the source) can contain errors and be inaccurate. +Some sources of error in the user location include:

      + +
        +
      • Multitude of location sources +

        GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use +and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency.

        +
      • +
      • User movement +

        Because the user location changes, you must account for movement by re-estimating user +location every so often.

        +
      • +
      • Varying accuracy +

        Location estimates coming from each location source are not consistent in their +accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest +location from another or same source.

        +
      • +
      + +

      These problems can make it difficult to obtain a reliable user location reading. This +document provides information to help you meet these challenges to obtain a reliable location +reading. It also provides ideas that you can use in your +application to provide the user with an accurate and responsive geo-location experience.

      + + +

      Requesting Location Updates

      + +

      Before addressing some of the location errors described above, here is an introduction to +how you can obtain user location on Android.

      + +

      Getting user location in Android works by means of callback. You indicate that you'd +like to receive location updates from the {@link android.location.LocationManager} ("Location +Manager") by calling {@link android.location.LocationManager#requestLocationUpdates +requestLocationUpdates()}, passing it a +{@link android.location.LocationListener}. Your {@link android.location.LocationListener} must +implement several callback methods that the Location Manager calls when the user location +changes or when the status of the service changes.

      + +

      For example, the following code shows how to define a {@link android.location.LocationListener} +and request location updates: +

      + +
      +// Acquire a reference to the system Location Manager
      +LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
      +
      +// Define a listener that responds to location updates
      +LocationListener locationListener = new LocationListener() {
      +    public void onLocationChanged(Location location) {
      +      // Called when a new location is found by the network location provider.
      +      makeUseOfNewLocation(location);
      +    }
      +
      +    public void onStatusChanged(String provider, int status, Bundle extras) {}
      +
      +    public void onProviderEnabled(String provider) {}
      +
      +    public void onProviderDisabled(String provider) {}
      +  };
      +
      +// Register the listener with the Location Manager to receive location updates
      +locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
      +
      + +

      The first parameter in {@link +android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} is the type of +location provider to use (in this case, the Network Location Provider for cell tower and Wi-Fi +based location). You can control the frequency at which your listener receives updates +with the second and third parameter—the second is the minimum time interval between +notifications and the third is the minimum change in distance between notifications—setting +both to zero requests location notifications as frequently as possible. The last parameter is your +{@link android.location.LocationListener}, which receives callbacks for location updates.

      + +

      To request location updates from the GPS provider, +substitute GPS_PROVIDER for NETWORK_PROVIDER. You can also request +location updates from both the GPS and the Network Location Provider by calling {@link +android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} twice—once +for NETWORK_PROVIDER and once for GPS_PROVIDER.

      + + +

      Requesting User Permissions

      + +

      In order to receive location updates from NETWORK_PROVIDER or +GPS_PROVIDER, you must request user permission by declaring either the {@code +ACCESS_COARSE_LOCATION} or {@code ACCESS_FINE_LOCATION} permission, respectively, in your Android +manifest file. For example:

      + +
      +<manifest ... >
      +    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      +    ...
      +</manifest>
      +
      + +

      Without these permissions, your application will fail at runtime when requesting +location updates.

      + +

      Note: If you are using both NETWORK_PROVIDER and +GPS_PROVIDER, then you need to request only the {@code ACCESS_FINE_LOCATION} +permission, because it includes permission for both providers. (Permission for {@code +ACCESS_COARSE_LOCATION} includes permission only for NETWORK_PROVIDER.)

      + + +

      Defining a Model for the Best Performance

      + +

      Location-based applications are now commonplace, but due to the less than optimal +accuracy, user movement, the multitude of methods to obtain the location, and the desire to conserve +battery, getting user location is complicated. To overcome the obstacles of obtaining a good user +location while preserving battery power, you must define a consistent model that specifies how your +application obtains the user location. This model includes when you start and stop listening for +updates and when to use cached location data.

      + + +

      Flow for obtaining user location

      + +

      Here's the typical flow of procedures for obtaining the user location:

      + +
        +
      1. Start application.
      2. +
      3. Sometime later, start listening for updates from desired location providers.
      4. +
      5. Maintain a "current best estimate" of location by filtering out new, but less accurate +fixes.
      6. +
      7. Stop listening for location updates.
      8. +
      9. Take advantage of the last best location estimate.
      10. +
      + +

      Figure 1 demonstrates this model in a timeline that visualizes the period in which an +application is listening for location updates and the events that occur during that time.

      + + +

      Figure 1. A timeline representing the window in which an +application listens for location updates.

      + +

      This model of a window—during which location updates are received—frames many of +the decisions you need to make when adding location-based services to your application.

      + + +

      Deciding when to start listening for updates

      + +

      You might want to start listening for location updates as soon as your application starts, or +only after users activate a certain feature. Be aware that long windows of listening for location +fixes can consume a lot of battery power, but short periods might not allow for sufficient +accuracy.

      + +

      As demonstrated above, you can begin listening for updates by calling {@link +android.location.LocationManager#requestLocationUpdates requestLocationUpdates()}:

      + +
      +LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
      +// Or, use GPS location data:
      +// LocationProvider locationProvider = LocationManager.GPS_PROVIDER;
      +
      +locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
      +
      + + +

      Getting a fast fix with the last known location

      + +

      The time it takes for your location listener to receive the first location fix is often too +long for users wait. Until a more accurate location is provided to your location listener, you +should utilize a cached location by calling {@link +android.location.LocationManager#getLastKnownLocation}:

      +
      +LocationProvider locationProvider = LocationManager.NETWORK_PROVIDER;
      +// Or use LocationManager.GPS_PROVIDER
      +
      +Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
      +
      + + +

      Deciding when to stop listening for updates

      + +

      The logic of deciding when new fixes are no longer necessary might range from very simple to +very complex depending on your application. A short gap between when the location is acquired and +when the location is used, improves the accuracy of the estimate. Always beware that listening for a +long time consumes a lot of battery power, so as soon as you have the information you need, you +should stop +listening for updates by calling {@link android.location.LocationManager#removeUpdates}:

      +
      +// Remove the listener you previously added
      +locationManager.removeUpdates(locationListener);
      +
      + + +

      Maintaining a current best estimate

      + +

      You might expect that the most recent location fix is the most accurate. +However, because the accuracy of a location fix varies, the most recent fix is not always the best. +You should include logic for choosing location fixes based on several criteria. The criteria also +varies depending on the use-cases of the application and field testing.

      + +

      Here are a few steps you can take to validate the accuracy of a location fix:

      +
        +
      • Check if the location retrieved is significantly newer than the previous estimate.
      • +
      • Check if the accuracy claimed by the location is better or worse than the previous +estimate.
      • +
      • Check which provider the new location is from and determine if you trust it more.
      • +
      + +

      An elaborate example of this logic can look something like this:

      + +
      +private static final int TWO_MINUTES = 1000 * 60 * 2;
      +
      +/** Determines whether one Location reading is better than the current Location fix
      +  * @param location  The new Location that you want to evaluate
      +  * @param currentBestLocation  The current Location fix, to which you want to compare the new one
      +  */
      +protected boolean isBetterLocation(Location location, Location currentBestLocation) {
      +    if (currentBestLocation == null) {
      +        // A new location is always better than no location
      +        return true;
      +    }
      +
      +    // Check whether the new location fix is newer or older
      +    long timeDelta = location.getTime() - currentBestLocation.getTime();
      +    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
      +    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
      +    boolean isNewer = timeDelta > 0;
      +
      +    // If it's been more than two minutes since the current location, use the new location
      +    // because the user has likely moved
      +    if (isSignificantlyNewer) {
      +        return true;
      +    // If the new location is more than two minutes older, it must be worse
      +    } else if (isSignificantlyOlder) {
      +        return false;
      +    }
      +
      +    // Check whether the new location fix is more or less accurate
      +    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
      +    boolean isLessAccurate = accuracyDelta > 0;
      +    boolean isMoreAccurate = accuracyDelta < 0;
      +    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
      +
      +    // Check if the old and new location are from the same provider
      +    boolean isFromSameProvider = isSameProvider(location.getProvider(),
      +            currentBestLocation.getProvider());
      +
      +    // Determine location quality using a combination of timeliness and accuracy
      +    if (isMoreAccurate) {
      +        return true;
      +    } else if (isNewer && !isLessAccurate) {
      +        return true;
      +    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
      +        return true;
      +    }
      +    return false;
      +}
      +
      +/** Checks whether two providers are the same */
      +private boolean isSameProvider(String provider1, String provider2) {
      +    if (provider1 == null) {
      +      return provider2 == null;
      +    }
      +    return provider1.equals(provider2);
      +}
      +
      + + +

      Adjusting the model to save battery and data exchange

      + +

      As you test your application, you might find that your model for providing good location and +good performance needs some adjustment. Here are some things you might change to find a good +balance between the two.

      + +

      Reduce the size of the window

      + +

      A smaller window in which you listen for location updates means less interaction with GPS and +network location services, thus, preserving battery life. But it also allows for fewer locations +from which to choose a best estimate.

      + +

      Set the location providers to return updates less frequently

      + +

      Reducing the rate at which new updates appear during the window can also improve battery +efficiency, but at the cost of accuracy. The value of the trade-off depends on how your +application is used. You can reduce the rate of updates by increasing the parameters in {@link +android.location.LocationManager#requestLocationUpdates requestLocationUpdates()} that specify the +interval time and minimum distance change.

      + +

      Restrict a set of providers

      + +

      Depending on the environment where your application is used or the desired level of accuracy, +you might choose to use only the Network Location Provider or only GPS, instead of both. Interacting +with only one of the services reduces battery usage at a potential cost of accuracy.

      + + +

      Common application cases

      + +

      There are many reasons you might want to obtain the user location in your application. Below +are a couple scenarios in which you can use the user location to enrich your application. Each +scenario also describes good practices for when you should start and stop listening for the +location, in order to get a good reading and help preserve battery life.

      + + +

      Tagging user-created content with a location

      + +

      You might be creating an application where user-created content is tagged with a location. +Think of users sharing their local experiences, posting a review for a restaurant, or recording some +content that can be augmented with their current location. A model of how this +interaction might happen, with respect to the location services, is visualized in figure 2.

      + + +

      Figure 2. A timeline representing the window in which +the user location is obtained and listening stops when the user consumes the current location.

      + +

      This lines up with the previous model of how user location is obtained in code (figure 1). For +best location accuracy, you might choose to start listening for location updates when users begin +creating +the content or even when the application starts, then stop listening for updates when content is +ready to be posted or recorded. You might need to consider how long a typical task of creating the +content takes and judge if this duration allows for efficient collection of a location estimate.

      + + +

      Helping the user decide on where to go

      + +

      You might be creating an application that attempts to provide users with a set +of options about where to go. For example, you're looking to provide a list of nearby restaurants, +stores, and entertainment and the order of recommendations changes depending on the user +location.

      + +

      To accommodate such a flow, you might choose to:

      +
        +
      • Rearrange recommendations when a new best estimate is obtained
      • +
      • Stop listening for updates if the order of recommendations has stabilized
      • +
      + +

      This kind of model is visualized in figure 3.

      + + +

      Figure 3. A timeline representing the window in which a +dynamic set of data is updated each time the user location updates.

      + + + + +

      Providing Mock Location Data

      + +

      As you develop your application, you'll certainly need to test how well your model for obtaining +user location works. This is most easily done using a real Android-powered device. If, however, you +don't have a device, you can still test your location-based features by mocking location data in +the Android emulator. There are three different ways to send your application mock location +data: using Eclipse, DDMS, or the "geo" command in the emulator console.

      + +

      Note: Providing mock location data is injected as GPS location +data, so you must request location updates from GPS_PROVIDER in order for mock location +data to work.

      + +

      Using Eclipse

      + +

      Select Window > Show View > Other > Emulator Control.

      + +

      In the Emulator Control panel, enter GPS coordinates under Location Controls as individual +lat/long coordinates, with a GPX file for route playback, or a KML file for multiple place marks. +(Be sure that you have a device selected in the Devices panel—available from Window +> Show View > Other > Devices.)

      + + +

      Using DDMS

      + +

      With the DDMS tool, you can simulate location data a few different ways:

      +
        +
      • Manually send individual longitude/latitude coordinates to the device.
      • +
      • Use a GPX file describing a route for playback to the device.
      • +
      • Use a KML file describing individual place marks for sequenced playback to the device.
      • +
      + +

      For more information on using DDMS to spoof location data, see +Using DDMS. + + +

      Using the "geo" command in the emulator console

      + +

      To send mock location data from the command line:

      + +
        +
      1. Launch your application in the Android emulator and open a terminal/console in your SDK's +/tools directory.
      2. +
      3. Connect to the emulator console: +
        telnet localhost <console-port>
      4. +
      5. Send the location data:

        +
        • geo fix to send a fixed geo-location. +

          This command accepts a longitude and latitude in decimal degrees, and + an optional altitude in meters. For example:

          +
          geo fix -121.45356 46.51119 4392
          +
        • +
        • geo nmea to send an NMEA 0183 sentence. +

          This command accepts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit + data). + For example:

          +
          geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
          +
        • +
        +
      6. +
      + +

      For information about how to connect to the emulator console, see +Using the Emulator Console.

      diff --git a/docs/html/guide/topics/manifest/action-element.jd b/docs/html/guide/topics/manifest/action-element.jd index 8ad94cdc1d50..037d0dc75d3d 100644 --- a/docs/html/guide/topics/manifest/action-element.jd +++ b/docs/html/guide/topics/manifest/action-element.jd @@ -16,7 +16,7 @@ parent.link=manifest-intro.html An <intent-filter> element must contain one or more {@code <action>} elements. If it doesn't contain any, no Intent objects will get through the filter. See -Intents and +Intents and Intent Filters for details on intent filters and the role of action specifications within a filter. diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd index 9dc124be4f3e..88f226c7e61b 100644 --- a/docs/html/guide/topics/manifest/activity-element.jd +++ b/docs/html/guide/topics/manifest/activity-element.jd @@ -508,7 +508,7 @@ other activities and tasks using the Back button.

      For more information on launch modes and their interaction with Intent flags, see the -Tasks and Back Stack +Tasks and Back Stack document.

      diff --git a/docs/html/guide/topics/manifest/category-element.jd b/docs/html/guide/topics/manifest/category-element.jd index f392c0a30f52..41a2cfdedb71 100644 --- a/docs/html/guide/topics/manifest/category-element.jd +++ b/docs/html/guide/topics/manifest/category-element.jd @@ -12,7 +12,7 @@ parent.link=manifest-intro.html
      description:
      Adds a category name to an intent filter. See -Intents and +Intents and Intent Filters for details on intent filters and the role of category specifications within a filter.
      diff --git a/docs/html/guide/topics/manifest/compatible-screens-element.jd b/docs/html/guide/topics/manifest/compatible-screens-element.jd index a27c31624de2..bb004fbef46c 100644 --- a/docs/html/guide/topics/manifest/compatible-screens-element.jd +++ b/docs/html/guide/topics/manifest/compatible-screens-element.jd @@ -54,7 +54,7 @@ href="{@docRoot}guide/topics/manifest/supports-screens-element.html">{@code <supports-screens>} element to declare whether the system should resize your application for different screen sizes.

      -

      Also see the Filters on Google Play +

      Also see the Filters on Google Play document for more information about how Google Play filters applications using this and other manifest elements.

      @@ -138,5 +138,5 @@ entry looks like if your application is compatible with only small and normal sc
      see also:
      Supporting Multiple Screens
      -
      Filters on Google Play
      +
      Filters on Google Play
      diff --git a/docs/html/guide/topics/manifest/data-element.jd b/docs/html/guide/topics/manifest/data-element.jd index 9b0d0df6ae06..8fd91deae6a2 100644 --- a/docs/html/guide/topics/manifest/data-element.jd +++ b/docs/html/guide/topics/manifest/data-element.jd @@ -62,7 +62,7 @@ options. None of its attributes have default values.

      Information on how intent filters work, including the rules for how Intent objects are matched against filters, can be found in another document, -Intents and +Intents and Intent Filters. See also the Intent Filters section in the introduction. diff --git a/docs/html/guide/topics/manifest/intent-filter-element.jd b/docs/html/guide/topics/manifest/intent-filter-element.jd index d2934005f47b..f90541cafd17 100644 --- a/docs/html/guide/topics/manifest/intent-filter-element.jd +++ b/docs/html/guide/topics/manifest/intent-filter-element.jd @@ -41,7 +41,7 @@ Most of the contents of the filter are described by its

      For a more detailed discussion of filters, see the separate -Intents +Intents and Intent Filters document, as well as the Intents Filters section in the introduction. diff --git a/docs/html/guide/topics/manifest/manifest-element.jd b/docs/html/guide/topics/manifest/manifest-element.jd index 98968d739f12..a3d4a955e396 100644 --- a/docs/html/guide/topics/manifest/manifest-element.jd +++ b/docs/html/guide/topics/manifest/manifest-element.jd @@ -152,7 +152,7 @@ either internal or external storage through the system settings.

      Caution: 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 Application Licensing instead, + Play's Application Licensing instead, your application can be installed to internal or external storage, including SD cards.

      Note: By default, your application will be installed on the diff --git a/docs/html/guide/topics/manifest/manifest-intro.jd b/docs/html/guide/topics/manifest/manifest-intro.jd index 0f2030556587..a130f7d9761e 100644 --- a/docs/html/guide/topics/manifest/manifest-intro.jd +++ b/docs/html/guide/topics/manifest/manifest-intro.jd @@ -345,7 +345,7 @@ filters.

      For information on how Intent objects are tested against intent filters, see a separate document, -Intents +Intents and Intent Filters.

      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 ebdd0b10917a..6dfc59e0b800 100644 --- a/docs/html/guide/topics/manifest/supports-gl-texture-element.jd +++ b/docs/html/guide/topics/manifest/supports-gl-texture-element.jd @@ -141,7 +141,7 @@ and others.
      see also:
      diff --git a/docs/html/guide/topics/manifest/uses-feature-element.jd b/docs/html/guide/topics/manifest/uses-feature-element.jd index 5f0a501c3670..f60529513cfc 100644 --- a/docs/html/guide/topics/manifest/uses-feature-element.jd +++ b/docs/html/guide/topics/manifest/uses-feature-element.jd @@ -207,7 +207,7 @@ can check at run-time whether a higher level of OpenGL ES is available.)

    8. {@link android.content.pm.FeatureInfo}
    9. {@link android.content.pm.ConfigurationInfo}
    10. <uses-permission>
    11. -
    12. Filters on Google Play
    13. +
    14. Filters on Google Play
    15. @@ -501,7 +501,7 @@ If you are using SDK Tools r8 or higher, you can find aapt in the

      Note: You must use the version of aapt that is provided for the latest Platform-Tools component available. If you do not have the latest Platform-Tools component, download it using the Android SDK Manager. +href="{@docRoot}sdk/exploring.html">Android SDK Manager.

    16. Run aapt using this syntax:
    diff --git a/docs/html/guide/topics/manifest/uses-library-element.jd b/docs/html/guide/topics/manifest/uses-library-element.jd index 2f8eb508c270..3ad8ddb5589a 100644 --- a/docs/html/guide/topics/manifest/uses-library-element.jd +++ b/docs/html/guide/topics/manifest/uses-library-element.jd @@ -46,7 +46,7 @@ parent.link=manifest-intro.html
    Google Play filters applications based on the libraries installed on the user's device. For more information about filtering, see the topic - Filters on Google Play. + Filters on Google Play.

    diff --git a/docs/html/guide/topics/manifest/uses-sdk-element.jd b/docs/html/guide/topics/manifest/uses-sdk-element.jd index 8fa39d156914..29dcb56b8b74 100644 --- a/docs/html/guide/topics/manifest/uses-sdk-element.jd +++ b/docs/html/guide/topics/manifest/uses-sdk-element.jd @@ -3,6 +3,29 @@ parent.title=The AndroidManifest.xml File parent.link=manifest-intro.html @jd:body + +

    +
    syntax:
    @@ -25,9 +48,8 @@ The API Level is always a single integer. You cannot derive the API Level from
     its associated Android version number (for example, it is not the same as the
     major version or the sum of the major and minor versions).

    -

    For more information, read about -Android API Levels and -Versioning Your Applications. +

    Also read the document about +Versioning Your Applications.

  • @@ -156,3 +178,403 @@ download.
    API Level 1
    + + + + + + + + + + +

    What is API Level?

    + +

    API Level is an integer value that uniquely identifies the framework API +revision offered by a version of the Android platform.

    + +

    The Android platform provides a framework API that applications can use to +interact with the underlying Android system. The framework API consists of:

    + + + +

    Each successive version of the Android platform can include updates to the +Android application framework API that it delivers.

    + +

    Updates to the framework API are designed so that the new API remains +compatible with earlier versions of the API. That is, most changes in the API +are additive and introduce new or replacement functionality. As parts of the API +are upgraded, the older replaced parts are deprecated but are not removed, so +that existing applications can still use them. In a very small number of cases, +parts of the API may be modified or removed, although typically such changes are +only needed to ensure API robustness and application or system security. All +other API parts from earlier revisions are carried forward without +modification.

    + +

    The framework API that an Android platform delivers is specified using an +integer identifier called "API Level". Each Android platform version supports +exactly one API Level, although support is implicit for all earlier API Levels +(down to API Level 1). The initial release of the Android platform provided +API Level 1 and subsequent releases have incremented the API Level.

    + +

    The following table specifies the API Level supported by each version of the +Android platform.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Platform VersionAPI LevelVERSION_CODENotes
    Android 4.0.315{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1}Platform +Highlights
    Android 4.0, 4.0.1, 4.0.214{@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}
    Android 3.213{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2}
    Android 3.1.x12{@link android.os.Build.VERSION_CODES#HONEYCOMB_MR1}Platform Highlights
    Android 3.0.x11{@link android.os.Build.VERSION_CODES#HONEYCOMB}Platform Highlights
    Android 2.3.4
    Android 2.3.3
    10{@link android.os.Build.VERSION_CODES#GINGERBREAD_MR1}Platform +Highlights
    Android 2.3.2
    Android 2.3.1
    Android +2.3
    9{@link android.os.Build.VERSION_CODES#GINGERBREAD}
    Android 2.2.x8{@link android.os.Build.VERSION_CODES#FROYO}Platform Highlights
    Android 2.1.x7{@link android.os.Build.VERSION_CODES#ECLAIR_MR1}Platform +Highlights
    Android 2.0.16{@link android.os.Build.VERSION_CODES#ECLAIR_0_1}
    Android 2.05{@link android.os.Build.VERSION_CODES#ECLAIR}
    Android 1.64{@link android.os.Build.VERSION_CODES#DONUT}Platform Highlights
    Android 1.53{@link android.os.Build.VERSION_CODES#CUPCAKE}Platform Highlights
    Android 1.12{@link android.os.Build.VERSION_CODES#BASE_1_1}
    Android 1.01{@link android.os.Build.VERSION_CODES#BASE}
    + + +

    Uses of API Level in Android

    + +

    The API Level identifier serves a key role in ensuring the best possible +experience for users and application developers: + +

    + +

    Each Android platform version stores its API Level identifier internally, in +the Android system itself.

    + +

    Applications can use a manifest element provided by the framework API — +<uses-sdk> — to describe the minimum and maximum API +Levels under which they are able to run, as well as the preferred API Level that +they are designed to support. The element offers three key attributes:

    + + + +

    For example, to specify the minimum system API Level that an application +requires in order to run, the application would include in its manifest a +<uses-sdk> element with a android:minSdkVersion +attribute. The value of android:minSdkVersion would be the integer +corresponding to the API Level of the earliest version of the Android platform +under which the application can run.

    + +

    When the user attempts to install an application, or when revalidating an +appplication after a system update, the Android system first checks the +<uses-sdk> attributes in the application's manifest and +compares the values against its own internal API Level. The system allows the +installation to begin only if these conditions are met:

    + + + +

    When declared in an application's manifest, a <uses-sdk> +element might look like this:

    + +
    <manifest>
    +  <uses-sdk android:minSdkVersion="5" />
    +  ...
    +</manifest>
    + +

    The principal reason that an application would declare an API Level in +android:minSdkVersion is to tell the Android system that it is +using APIs that were introduced in the API Level specified. If the +application were to be somehow installed on a platform with a lower API Level, +then it would crash at run-time when it tried to access APIs that don't exist. +The system prevents such an outcome by not allowing the application to be +installed if the lowest API Level it requires is higher than that of the +platform version on the target device.

    + +

    For example, the {@link android.appwidget} package was introduced with API +Level 3. If an application uses that API, it must declare a +android:minSdkVersion attribute with a value of "3". The +application will then be installable on platforms such as Android 1.5 (API Level +3) and Android 1.6 (API Level 4), but not on the Android 1.1 (API Level 2) and +Android 1.0 platforms (API Level 1).

    + +

    For more information about how to specify an application's API Level +requirements, see the <uses-sdk> + section of the manifest file documentation.

    + + +

    Development Considerations

    + +

    The sections below provide information related to API level that you should +consider when developing your application.

    + +

    Application forward compatibility

    + +

    Android applications are generally forward-compatible with new versions of +the Android platform.

    + +

    Because almost all changes to the framework API are additive, an Android +application developed using any given version of the API (as specified by its +API Level) is forward-compatible with later versions of the Android platform and +higher API levels. The application should be able to run on all later versions +of the Android platform, except in isolated cases where the application uses a +part of the API that is later removed for some reason.

    + +

    Forward compatibility is important because many Android-powered devices +receive over-the-air (OTA) system updates. The user may install your +application and use it successfully, then later receive an OTA update to a new +version of the Android platform. Once the update is installed, your application +will run in a new run-time version of the environment, but one that has the API +and system capabilities that your application depends on.

    + +

    In some cases, changes below the API, such those in the underlying +system itself, may affect your application when it is run in the new +environment. For that reason it's important for you, as the application +developer, to understand how the application will look and behave in each system +environment. To help you test your application on various versions of the Android +platform, the Android SDK includes multiple platforms that you can download. +Each platform includes a compatible system image that you can run in an AVD, to +test your application.

    + +

    Application backward compatibility

    + +

    Android applications are not necessarily backward compatible with versions of +the Android platform older than the version against which they were compiled. +

    + +

    Each new version of the Android platform can include new framework APIs, such +as those that give applications access to new platform capabilities or replace +existing API parts. The new APIs are accessible to applications when running on +the new platform and, as mentioned above, also when running on later versions of +the platform, as specified by API Level. Conversely, because earlier versions of +the platform do not include the new APIs, applications that use the new APIs are +unable to run on those platforms.

    + +

    Although it's unlikely that an Android-powered device would be downgraded to +a previous version of the platform, it's important to realize that there are +likely to be many devices in the field that run earlier versions of the +platform. Even among devices that receive OTA updates, some might lag and +might not receive an update for a significant amount of time.

    + +

    Selecting a platform version and API Level

    + +

    When you are developing your application, you will need to choose +the platform version against which you will compile the application. In +general, you should compile your application against the lowest possible +version of the platform that your application can support. + +

    You can determine the lowest possible platform version by compiling the +application against successively lower build targets. After you determine the +lowest version, you should create an AVD using the corresponding platform +version (and API Level) and fully test your application. Make sure to declare a +android:minSdkVersion attribute in the application's manifest and +set its value to the API Level of the platform version.

    + +

    Declaring a minimum API Level

    + +

    If you build an application that uses APIs or system features introduced in +the latest platform version, you should set the +android:minSdkVersion attribute to the API Level of the latest +platform version. This ensures that users will only be able to install your +application if their devices are running a compatible version of the Android +platform. In turn, this ensures that your application can function properly on +their devices.

    + +

    If your application uses APIs introduced in the latest platform version but +does not declare a android:minSdkVersion attribute, then +it will run properly on devices running the latest version of the platform, but +not on devices running earlier versions of the platform. In the latter +case, the application will crash at runtime when it tries to use APIs that don't +exist on the earlier versions.

    + +

    Testing against higher API Levels

    + +

    After compiling your application, you should make sure to test it on the +platform specified in the application's android:minSdkVersion +attribute. To do so, create an AVD that uses the platform version required by +your application. Additionally, to ensure forward-compatibility, you should run +and test the application on all platforms that use a higher API Level than that +used by your application.

    + +

    The Android SDK includes multiple platform versions that you can use, +including the latest version, and provides an updater tool that you can use to +download other platform versions as necessary.

    + +

    To access the updater, use the android command-line tool, +located in the <sdk>/tools directory. You can launch the SDK updater by +executing android sdk. You can +also simply double-click the android.bat (Windows) or android (OS X/Linux) file. +In ADT, you can also access the updater by selecting +Window > Android SDK +Manager.

    + +

    To run your application against different platform versions in the emulator, +create an AVD for each platform version that you want to test. For more +information about AVDs, see Creating and Managing Virtual Devices. If +you are using a physical device for testing, ensure that you know the API Level +of the Android platform it runs. See the table at the top of this document for +a list of platform versions and their API Levels.

    + +

    Using a Provisional API Level

    + +

    In some cases, an "Early Look" Android SDK platform may be available. To let +you begin developing on the platform although the APIs may not be final, the +platform's API Level integer will not be specified. You must instead use the +platform's provisional API Level in your application manifest, in order +to build applications against the platform. A provisional API Level is not an +integer, but a string matching the codename of the unreleased platform version. +The provisional API Level will be specified in the release notes for the Early +Look SDK release notes and is case-sensitive.

    + +

    The use of a provisional API Level is designed to protect developers and +device users from inadvertently publishing or installing applications based on +the Early Look framework API, which may not run properly on actual devices +running the final system image.

    + +

    The provisional API Level will only be valid while using the Early Look SDK +and can only be used to run applications in the emulator. An application using +the provisional API Level can never be installed on an Android device. At the +final release of the platform, you must replace any instances of the provisional +API Level in your application manifest with the final platform's actual API +Level integer.

    + + +

    Filtering the Reference Documentation by API Level

    + +

    Reference documentation pages on the Android Developers site offer a "Filter +by API Level" control in the top-right area of each page. You can use the +control to show documentation only for parts of the API that are actually +accessible to your application, based on the API Level that it specifies in +the android:minSdkVersion attribute of its manifest file.

    + +

    To use filtering, select the checkbox to enable filtering, just below the +page search box. Then set the "Filter by API Level" control to the same API +Level as specified by your application. Notice that APIs introduced in a later +API Level are then grayed out and their content is masked, since they would not +be accessible to your application.

    + +

    Filtering by API Level in the documentation does not provide a view +of what is new or introduced in each API Level — it simply provides a way +to view the entire API associated with a given API Level, while excluding API +elements introduced in later API Levels.

    + +

    If you decide that you don't want to filter the API documentation, just +disable the feature using the checkbox. By default, API Level filtering is +disabled, so that you can view the full framework API, regardless of API Level. +

    + +

    Also note that the reference documentation for individual API elements +specifies the API Level at which each element was introduced. The API Level +for packages and classes is specified as "Since <api level>" at the +top-right corner of the content area on each documentation page. The API Level +for class members is specified in their detailed description headers, +at the right margin.

    + + + + + + + + + diff --git a/docs/html/guide/topics/media/camera.jd b/docs/html/guide/topics/media/camera.jd index 7d72491ef109..a63270a77ead 100644 --- a/docs/html/guide/topics/media/camera.jd +++ b/docs/html/guide/topics/media/camera.jd @@ -162,8 +162,7 @@ information, you must request location permission: <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    For more information about getting user location, see -Obtaining User -Location.

    +Location Strategies.

    diff --git a/docs/html/guide/topics/media/index.jd b/docs/html/guide/topics/media/index.jd index 0e0412a10d52..a750c9a8809f 100644 --- a/docs/html/guide/topics/media/index.jd +++ b/docs/html/guide/topics/media/index.jd @@ -1,63 +1,56 @@ -page.title=Multimedia and Camera +page.title=Media and Camera +page.landing=true +page.landing.intro=Add video, audio, and photo capabilities to your app with Android's robust APIs for playing and recording media. +page.landing.image= + @jd:body -
    -
    - -

    Topics

    -
      -
    1. Media Playback
    2. -
    3. JetPlayer
    4. -
    5. Camera
    6. -
    7. Audio Capture
    8. -
    - -

    Key classes

    -
      -
    1. {@link android.media.MediaPlayer}
    2. -
    3. {@link android.media.JetPlayer}
    4. -
    5. {@link android.hardware.Camera}
    6. -
    7. {@link android.media.MediaRecorder}
    8. -
    9. {@link android.media.AudioManager}
    10. -
    11. {@link android.media.SoundPool}
    12. -
    - -

    See also

    -
      -
    1. -
    2. Android Supported Media Formats
    3. -
    4. JetCreator User -Manual
    5. -
    - -
    -
    - -

    The Android multimedia framework includes support for capturing and playing audio, video and -images in a variety of common media types, so that you can easily integrate them into your -applications. You can play audio or video from media files stored in your application's resources, -from standalone files in the file system, or from a data stream arriving over a -network connection, all using the {@link android.media.MediaPlayer} or {@link -android.media.JetPlayer} APIs. You can also record audio, video and take pictures using the {@link -android.media.MediaRecorder} and {@link android.hardware.Camera} APIs if supported by the device -hardware.

    - -

    The following topics show you how to use the Android framework to implement multimedia capture -and playback.

    - -
    -
    Media Playback -
    -
    How to play audio and video in your application.
    - -
    JetPlayer
    -
    How to play interactive audio and video in your application using content created with -JetCreator.
    - -
    Camera
    -
    How to use a device camera to take pictures or video in your application.
    - -
    Audio -Capture
    -
    How to record sound in your application.
    -
    \ No newline at end of file + \ No newline at end of file diff --git a/docs/html/guide/topics/media/mediaplayer.jd b/docs/html/guide/topics/media/mediaplayer.jd index 002d113ea31a..45a58a7b5c4a 100644 --- a/docs/html/guide/topics/media/mediaplayer.jd +++ b/docs/html/guide/topics/media/mediaplayer.jd @@ -457,7 +457,7 @@ stopForeground(true);

    For more information, see the documentation about Services and +href="{@docRoot}guide/components/services.html#Foreground">Services and Status Bar Notifications.

    diff --git a/docs/html/guide/topics/network/sip.jd b/docs/html/guide/topics/network/sip.jd deleted file mode 100644 index 600da78ffcfb..000000000000 --- a/docs/html/guide/topics/network/sip.jd +++ /dev/null @@ -1,490 +0,0 @@ -page.title=Session Initiation Protocol -@jd:body -
    -
    -

    In this document

    -
      - -
    1. Requirements and Limitations
    2. -
    3. Classes and Interfaces
    4. -
    5. Creating the Manifest
    6. -
    7. Creating a SIP Manager
    8. -
    9. Registering with a SIP Server
    10. -
    11. Making an Audio Call
    12. -
    13. Receiving Calls
    14. -
    15. Testing SIP Applications
    16. -
    - -

    Key classes

    -
      -
    1. {@link android.net.sip.SipManager}
    2. -
    3. {@link android.net.sip.SipProfile}
    4. -
    5. {@link android.net.sip.SipAudioCall}
    6. - -
    - -

    Related samples

    -
      -
    1. SipDemo
    2. -
    -
    -
    - -

    Android provides an API that supports the Session Initiation Protocol (SIP). -This lets you add SIP-based internet telephony features to your applications. -Android includes a full SIP protocol stack and integrated call management -services that let applications easily set up outgoing and incoming voice calls, -without having to manage sessions, transport-level communication, or audio -record or playback directly.

    - -

    Here are examples of the types of applications that might use the SIP API:

    - -

    Requirements and Limitations

    -

    Here are the requirements for developing a SIP application:

    - - - -

    SIP API Classes and Interfaces

    - -

    Here is a summary of the classes and one interface -(SipRegistrationListener) that are included in the Android SIP -API:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Class/InterfaceDescription
    {@link android.net.sip.SipAudioCall}Handles an Internet audio call over SIP.
    {@link android.net.sip.SipAudioCall.Listener}Listener for events relating to a SIP call, such as when a call is being -received ("on ringing") or a call is outgoing ("on calling").
    {@link android.net.sip.SipErrorCode}Defines error codes returned during SIP actions.
    {@link android.net.sip.SipManager}Provides APIs for SIP tasks, such as initiating SIP connections, and provides access -to related SIP services.
    {@link android.net.sip.SipProfile}Defines a SIP profile, including a SIP account, domain and server information. -
    {@link android.net.sip.SipProfile.Builder}Helper class for creating a SipProfile.
    {@link android.net.sip.SipSession}Represents a SIP session that is associated with a SIP dialog or a standalone transaction -not within a dialog.
    {@link android.net.sip.SipSession.Listener}Listener for events relating to a SIP session, such as when a session is being registered -("on registering") or a call is outgoing ("on calling").
    {@link android.net.sip.SipSession.State}Defines SIP session states, such as "registering", "outgoing call", and "in call".
    {@link android.net.sip.SipRegistrationListener}An interface that is a listener for SIP registration events.
    - -

    Creating the Manifest

    - -

    If you are developing an application that uses the SIP API, remember that the -feature is supported only on Android 2.3 (API level 9) and higher versions of -the platform. Also, among devices running Android 2.3 (API level 9) or higher, -not all devices will offer SIP support.

    - -

    To use SIP, add the following permissions to your application's manifest:

    - - -

    To ensure that your application can only be installed on devices that are -capable of supporting SIP, add the following to your application's -manifest:

    - - - -

    To control how your application is filtered from devices that do not support -SIP (for example, on Google Play), add the following to your application's -manifest:

    - - -

    If your application is designed to receive calls, you must also define a receiver ({@link android.content.BroadcastReceiver} subclass) in the application's manifest:

    - - -

    Here are excerpts from the SipDemo manifest:

    - - - -
    <?xml version="1.0" encoding="utf-8"?>
    -<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    -          package="com.example.android.sip">
    -  ...
    -     <receiver android:name=".IncomingCallReceiver" android:label="Call Receiver"/>
    -  ...
    -  <uses-sdk android:minSdkVersion="9" />
    -  <uses-permission android:name="android.permission.USE_SIP" />
    -  <uses-permission android:name="android.permission.INTERNET" />
    -  ...
    -  <uses-feature android:name="android.hardware.sip.voip" android:required="true" />
    -  <uses-feature android:name="android.hardware.wifi" android:required="true" />
    -  <uses-feature android:name="android.hardware.microphone" android:required="true" />
    -</manifest>
    -
    - - -

    Creating a SipManager

    - -

    To use the SIP API, your application must create a {@link -android.net.sip.SipManager} object. The {@link android.net.sip.SipManager} takes -care of the following in your application:

    - - -

    You instantiate a new {@link android.net.sip.SipManager} as follows:

    -
    public SipManager mSipManager = null;
    -...
    -if(mSipManager == null) {
    -    mSipManager = SipManager.newInstance(this);
    -}
    -

    Registering with a SIP Server

    - -

    A typical Android SIP application involves one or more users, each of whom -has a SIP account. In an Android SIP application, each SIP account is -represented by a {@link android.net.sip.SipProfile} object.

    - -

    A {@link android.net.sip.SipProfile} defines a SIP profile, including a SIP -account, and domain and server information. The profile associated with the SIP -account on the device running the application is called the local -profile. The profile that the session is connected to is called the -peer profile. When your SIP application logs into the SIP server with -the local {@link android.net.sip.SipProfile}, this effectively registers the -device as the location to send SIP calls to for your SIP address.

    - -

    This section shows how to create a {@link android.net.sip.SipProfile}, -register it with a SIP server, and track registration events.

    - -

    You create a {@link android.net.sip.SipProfile} object as follows:

    -
    -public SipProfile mSipProfile = null;
    -...
    -
    -SipProfile.Builder builder = new SipProfile.Builder(username, domain);
    -builder.setPassword(password);
    -mSipProfile = builder.build();
    - -

    The following code excerpt opens the local profile for making calls and/or -receiving generic SIP calls. The caller can make subsequent calls through -mSipManager.makeAudioCall. This excerpt also sets the action -android.SipDemo.INCOMING_CALL, which will be used by an intent -filter when the device receives a call (see Setting up -an intent filter to receive calls). This is the registration step:

    - -
    Intent intent = new Intent();
    -intent.setAction("android.SipDemo.INCOMING_CALL");
    -PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
    -mSipManager.open(mSipProfile, pendingIntent, null);
    - -

    Finally, this code sets a SipRegistrationListener on the {@link -android.net.sip.SipManager}. This tracks whether the {@link -android.net.sip.SipProfile} was successfully registered with your SIP service -provider:
    -

    - -
    mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
    -
    -public void onRegistering(String localProfileUri) {
    -    updateStatus("Registering with SIP Server...");
    -}
    -
    -public void onRegistrationDone(String localProfileUri, long expiryTime) {
    -    updateStatus("Ready");
    -}
    -   
    -public void onRegistrationFailed(String localProfileUri, int errorCode,
    -    String errorMessage) {
    -    updateStatus("Registration failed.  Please check settings.");
    -}
    - - -

    When your application is done using a profile, it should close it to free -associated objects into memory and unregister the device from the server. For -example:

    - -
    public void closeLocalProfile() {
    -    if (mSipManager == null) {
    -       return;
    -    }
    -    try {
    -       if (mSipProfile != null) {
    -          mSipManager.close(mSipProfile.getUriString());
    -       }
    -     } catch (Exception ee) {
    -       Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
    -     }
    -}
    - -

    Making an Audio Call

    -

    To make an audio call, you must have the following in place:

    - - -

    To make an audio call, you should set up a {@link -android.net.sip.SipAudioCall.Listener}. Much of the client's interaction with -the SIP stack happens through listeners. In this snippet, you see how the {@link -android.net.sip.SipAudioCall.Listener} sets things up after the call is -established:

    - -
    -SipAudioCall.Listener listener = new SipAudioCall.Listener() {
    -  
    -   @Override
    -   public void onCallEstablished(SipAudioCall call) {
    -      call.startAudio();
    -      call.setSpeakerMode(true);
    -      call.toggleMute();
    -         ...
    -   }
    -   
    -   @Override
    -   public void onCallEnded(SipAudioCall call) {
    -      // Do something.
    -   }
    -};
    - -

    Once you've set up the {@link android.net.sip.SipAudioCall.Listener}, you can -make the call. The {@link android.net.sip.SipManager} method -makeAudioCall takes the following parameters:

    - - -

    For example:

    -
     call = mSipManager.makeAudioCall(mSipProfile.getUriString(), sipAddress, listener, 30);
    - -

    Receiving Calls

    - -

    To receive calls, a SIP application must include a subclass of {@link -android.content.BroadcastReceiver} that has the ability to respond to an intent -indicating that there is an incoming call. Thus, you must do the following in -your application:

    - - -

    Subclassing BroadcastReceiver

    - -

    To receive calls, your SIP application must subclass {@link -android.content.BroadcastReceiver}. The -Android system handles incoming SIP calls and broadcasts an "incoming -call" intent (as defined by the application) when it receives -a call. Here is the subclassed {@link android.content.BroadcastReceiver} -code from SipDemo. To see the full example, go to SipDemo sample, which -is included in the SDK samples. For information on downloading and installing -the SDK samples, see -Getting the Samples.

    - -
    /*** Listens for incoming SIP calls, intercepts and hands them off to WalkieTalkieActivity.
    - */
    -public class IncomingCallReceiver extends BroadcastReceiver {
    -    /**
    -     * Processes the incoming call, answers it, and hands it over to the
    -     * WalkieTalkieActivity.
    -     * @param context The context under which the receiver is running.
    -     * @param intent The intent being received.
    -     */
    -    @Override
    -    public void onReceive(Context context, Intent intent) {
    -        SipAudioCall incomingCall = null;
    -        try {
    -            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
    -                @Override
    -                public void onRinging(SipAudioCall call, SipProfile caller) {
    -                    try {
    -                        call.answerCall(30);
    -                    } catch (Exception e) {
    -                        e.printStackTrace();
    -                    }
    -                }
    -            };
    -            WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
    -            incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);
    -            incomingCall.answerCall(30);
    -            incomingCall.startAudio();
    -            incomingCall.setSpeakerMode(true);
    -            if(incomingCall.isMuted()) {
    -                incomingCall.toggleMute();
    -            }
    -            wtActivity.call = incomingCall;
    -            wtActivity.updateStatus(incomingCall);
    -        } catch (Exception e) {
    -            if (incomingCall != null) {
    -                incomingCall.close();
    -            }
    -        }
    -    }
    -}
    -
    - -

    Setting up an intent filter to receive calls

    - -

    When the SIP service receives a new call, it sends out an intent with the -action string provided by the application. In SipDemo, this action string is -android.SipDemo.INCOMING_CALL.

    -

    This code excerpt from SipDemo shows how the {@link -android.net.sip.SipProfile} object gets created with a pending intent based on -the action string android.SipDemo.INCOMING_CALL. The -PendingIntent object will perform a broadcast when the {@link -android.net.sip.SipProfile} receives a call:

    - -
    -public SipManager mSipManager = null;
    -public SipProfile mSipProfile = null;
    -...
    -
    -Intent intent = new Intent(); 
    -intent.setAction("android.SipDemo.INCOMING_CALL"); 
    -PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA); 
    -mSipManager.open(mSipProfile, pendingIntent, null);
    - -

    The broadcast will be intercepted by the intent filter, which will then fire -the receiver (IncomingCallReceiver). You can specify an intent -filter in your application's manifest file, or do it in code as in the SipDemo -sample application's onCreate() method -of the application's Activity:

    - -
    -public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
    -...
    -    public IncomingCallReceiver callReceiver;
    -    ...
    -
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -
    -       IntentFilter filter = new IntentFilter();
    -       filter.addAction("android.SipDemo.INCOMING_CALL");
    -       callReceiver = new IncomingCallReceiver();
    -       this.registerReceiver(callReceiver, filter);
    -       ...
    -    }
    -    ...
    -}
    -
    - - -

    Testing SIP Applications

    - -

    To test SIP applications, you need the following:

    - -

    To test a SIP application:

    -
      - -
    1. On your device, connect to wireless (Settings > Wireless & networks -> Wi-Fi > Wi-Fi settings)
    2. -
    3. Set up your mobile device for testing, as described in Developing on a Device.
    4. -
    5. Run your application on your mobile device, as described in Developing on a Device.
    6. - -
    7. If you are using Eclipse, you can view the application log output in Eclipse -using LogCat (Window > Show View > Other > Android > -LogCat).
    8. -
    - diff --git a/docs/html/guide/topics/nfc/advanced-nfc.jd b/docs/html/guide/topics/nfc/advanced-nfc.jd deleted file mode 100644 index b43b559678c7..000000000000 --- a/docs/html/guide/topics/nfc/advanced-nfc.jd +++ /dev/null @@ -1,300 +0,0 @@ -page.title=Advanced NFC -@jd:body - - - -

    This document describes advanced NFC topics, such as working with various tag technologies, -writing to NFC tags, and foreground dispatching, which allows an application in the foreground to -handle intents even when other applications filter for the same ones.

    - -

    Working with Supported Tag Technologies

    -

    When working with NFC tags and Android-powered devices, the main format you use to read -and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support -in parsing the message and delivering it in an {@link android.nfc.NdefMessage} when -possible. There are cases, however, when you scan a tag that does not contain -NDEF data or when the NDEF data could not be mapped to a MIME type or URI. -In these cases, you need to open communication directly with the tag and read and write to it with -your own protocol (in raw bytes). Android provides generic support for these use cases with the -{@link android.nfc.tech} package, which is described in Table 1. You can -use the {@link android.nfc.Tag#getTechList getTechList()} method to determine the technologies -supported by the tag and create the corresponding {@link android.nfc.tech.TagTechnology} -object with one of classes provided by {@link android.nfc.tech}

    - -

    -Table 1. Supported tag technologies

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ClassDescription
    {@link android.nfc.tech.TagTechnology}The interface that all tag technology classes must implement.
    {@link android.nfc.tech.NfcA}Provides access to NFC-A (ISO 14443-3A) properties and I/O operations.
    {@link android.nfc.tech.NfcB}Provides access to NFC-B (ISO 14443-3B) properties and I/O operations.
    {@link android.nfc.tech.NfcF}Provides access to NFC-F (JIS 6319-4) properties and I/O operations.
    {@link android.nfc.tech.NfcV}Provides access to NFC-V (ISO 15693) properties and I/O operations.
    {@link android.nfc.tech.IsoDep}Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations.
    {@link android.nfc.tech.Ndef}Provides access to NDEF data and operations on NFC tags that have been formatted as - NDEF.
    {@link android.nfc.tech.NdefFormatable}Provides a format operations for tags that may be NDEF formattable.
    -

    The following tag technlogies are not required to be supported by Android-powered devices.

    -

    -Table 2. Optional supported tag technologies

    - - - - - - - - - - - - - - - - - -
    ClassDescription
    {@link android.nfc.tech.MifareClassic}Provides access to MIFARE Classic properties and I/O operations, if this Android device - supports MIFARE.
    {@link android.nfc.tech.MifareUltralight}Provides access to MIFARE Ultralight properties and I/O operations, if this Android - device supports MIFARE.
    - -

    Working with tag technologies and the ACTION_TECH_DISCOVERED intent

    -

    When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, -the tag dispatch system tries to start an activity with the {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} -intent. The {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} is also used when a tag -with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag -directly if the tag dispatch system could not parse it for you. The basic steps when working with -tag technologies are as follows:

    - -
      -
    1. Filter for an {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent specifying the -tag technologies that you want to handle. See Filtering for NFC -intents for more information. In general, the tag dispatch system tries to start a {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent when an NDEF message -cannot be mapped to a MIME type or URI, or if the tag scanned did not contain NDEF data. For -more information on how this is determined, see The Tag Dispatch System.
    2. -
    3. When your application receives the intent, obtain the {@link android.nfc.Tag} object from -the intent: -
      Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    4. -
    5. Obtain an instance of a {@link android.nfc.tech.TagTechnology}, by calling one of the -get factory methods of the classes in the {@link android.nfc.tech} package. You can -enumerate the supported technologies of the tag by calling {@link android.nfc.Tag#getTechList -getTechList()} before calling a get factory method. For example, to obtain an instance -of {@link android.nfc.tech.MifareUltralight} from a {@link android.nfc.Tag}, do the following: - -
      -MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
      -
      -
    6. -
    - - - -

    Reading and writing to tags

    - -

    Reading and writing to an NFC tag involves obtaining the tag from the intent and -opening communication with the tag. You must define your own protocol stack to read and write data -to the tag. Keep in mind, however, that you can still read and write NDEF data when working -directly with a tag. It is up to you how you want to structure things. The -following example shows how to work with a MIFARE Ultralight tag.

    - -
    -package com.example.android.nfc;
    -
    -import android.nfc.Tag;
    -import android.nfc.tech.MifareUltralight;
    -import android.util.Log;
    -import java.io.IOException;
    -import java.nio.charset.Charset;
    -
    -public class MifareUltralightTagTester {
    -
    -    private static final String TAG = MifareUltralightTagTester.class.getSimpleName();
    -
    -    public void writeTag(Tag tag, String tagText) {
    -        MifareUltralight ultralight = MifareUltralight.get(tag);
    -        try {
    -            ultralight.connect();
    -            ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
    -            ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
    -            ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
    -            ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
    -        } catch (IOException e) {
    -            Log.e(TAG, "IOException while closing MifareUltralight...", e);
    -        } finally {
    -            try {
    -                ultralight.close();
    -            } catch (IOException e) {
    -                Log.e(TAG, "IOException while closing MifareUltralight...", e);
    -            }
    -        }
    -    }
    -
    -    public String readTag(Tag tag) {
    -        MifareUltralight mifare = MifareUltralight.get(tag);
    -        try {
    -            mifare.connect();
    -            byte[] payload = mifare.readPages(4);
    -            return new String(payload, Charset.forName("US-ASCII"));
    -        } catch (IOException e) {
    -            Log.e(TAG, "IOException while writing MifareUltralight
    -            message...", e);
    -        } finally {
    -            if (mifare != null) {
    -               try {
    -                   mifare.close();
    -               }
    -               catch (IOException e) {
    -                   Log.e(TAG, "Error closing tag...", e);
    -               }
    -            }
    -        }
    -        return null;
    -    }
    -}
    -
    - - - -

    Using the Foreground Dispatch System

    - -

    The foreground dispatch system allows an activity to intercept an intent and claim -priority over other activities that handle the same intent. Using this system involves - constructing a few data structures for the Android system to be able to send the appropriate - intents to your application. To enable the foreground dispatch system:

    - -
      -
    1. Add the following code in the onCreate() method of your activity: - -
        -
      1. Create a {@link android.app.PendingIntent} object so the Android system can populate it - with the details of the tag when it is scanned. -
        -PendingIntent pendingIntent = PendingIntent.getActivity(
        -    this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        -
        -
      2. - -
      3. Declare intent filters to handle the intents that you want to intercept. The foreground - dispatch system checks the specified intent filters with the intent that is received when - the device scans a tag. If it matches, then your application handles the intent. If it does - not match, the foreground dispatch system falls back to the intent dispatch system. - Specifying a null array of intent filters and technology filters, specifies - that you want to filter for all tags that fallback to the TAG_DISCOVERED - intent. The code snippet below handles all MIME types for NDEF_DISCOVERED. You - should only handle the ones that you need. -
        -IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        -    try {
        -        ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
        -                                       You should specify only the ones that you need. */
        -    }
        -    catch (MalformedMimeTypeException e) {
        -        throw new RuntimeException("fail", e);
        -    }
        -   intentFiltersArray = new IntentFilter[] {ndef, };
        -
        -
      4. - -
      5. Set up an array of tag technologies that your application wants to handle. Call the - Object.class.getName() method to obtain the class of the technology that you - want to support. -
        -techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
        -
        -
      6. -
      -
    2. - -
    3. Override the following activity lifecycle callbacks and add logic to enable and disable the - foreground dispatch when the activity loses ({@link android.app.Activity#onPause onPause()}) - and regains ({@link android.app.Activity#onResume onResume()}) focus. {@link - android.nfc.NfcAdapter#enableForegroundDispatch enableForegroundDispatch()} must be called from -the main thread and only when the activity is in the foreground (calling in {@link -android.app.Activity#onResume onResume()} guarantees this). You also need to implement the {@link - android.app.Activity#onNewIntent onNewIntent} callback to process the data from the scanned NFC - tag.
    4. - -
      -public void onPause() {
      -    super.onPause();
      -    mAdapter.disableForegroundDispatch(this);
      -}
      -
      -public void onResume() {
      -    super.onResume();
      -    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
      -}
      -
      -public void onNewIntent(Intent intent) {
      -    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      -    //do something with tagFromIntent
      -}
      -
      - -
    - -

    See the -ForegroundDispatch sample from API Demos for the complete sample.

    \ No newline at end of file diff --git a/docs/html/guide/topics/nfc/index.jd b/docs/html/guide/topics/nfc/index.jd deleted file mode 100644 index b86d72d418d0..000000000000 --- a/docs/html/guide/topics/nfc/index.jd +++ /dev/null @@ -1,33 +0,0 @@ -page.title=Near Field Communication -@jd:body - -

    Near Field Communication (NFC) is a set of short-range wireless technologies, typically - requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small - payloads of data between an NFC tag and an Android-powered device, or between two Android-powered - devices. - -

    Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with - one-time-programmable areas to make the card read-only. More complex tags offer math operations, - and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags - contain operating environments, allowing complex interactions with code executing on the tag. - The data stored in the tag can also be written in a variety of formats, but many of the Android - framework APIs are based around a NFC Forum standard - called NDEF (NFC Data Exchange Format).

    - -
    -
    NFC Basics
    -
    This document describes how Android handles discovered NFC tags and how it notifies -applications of data that is relevant to the application. It also goes over how to work with the -NDEF data in your applications and gives an overview of the framework APIs that support the basic -NFC feature set of Android.
    - -
    Advanced - NFC
    -
    This document goes over the APIs that enable use of the various tag technologies that - Android supports. When you are not working with NDEF data, or when you are working with NDEF - data that Android cannot fully understand, you have to manually read or write to the tag in raw - bytes using your own protocol stack. In these cases, Android provides support to detect - certain tag technologies and to open communication with the tag using your own protocol - stack.
    -
    -

    \ No newline at end of file diff --git a/docs/html/guide/topics/nfc/nfc.jd b/docs/html/guide/topics/nfc/nfc.jd deleted file mode 100644 index 834656a9d5f5..000000000000 --- a/docs/html/guide/topics/nfc/nfc.jd +++ /dev/null @@ -1,923 +0,0 @@ -page.title=NFC Basics -@jd:body - - - - -

    This document describes the basic NFC tasks you perform in Android. It explains how to send and -receive NFC data in the form of NDEF messages and describes the Android framework APIs that support -these features. For more advanced topics, including a discussion of working with non-NDEF data, -see Advanced NFC.

    - - -

    There are two major uses cases when working with NDEF data and Android:

    - - - - -

    Reading NDEF data from an NFC tag is handled with the tag dispatch -system, which analyzes discovered NFC tags, appropriately categorizes the data, and starts -an application that is interested in the categorized data. An application that wants to handle the -scanned NFC tag can declare an intent filter and -request to handle the data.

    - -

    The Android Beam™ feature allows a device to push an NDEF message onto -another device by physically tapping the devices together. This interaction provides an easier way -to send data than other wireless technologies like Bluetooth, because with NFC, no manual device -discovery or pairing is required. The connection is automatically started when two devices come -into range. Android Beam is available through a set of NFC APIs, so any application can transmit -information between devices. For example, the Contacts, Browser, and YouTube applications use -Android Beam to share contacts, web pages, and videos with other devices. -

    - - -

    The Tag Dispatch System

    - -

    Android-powered devices are usually looking for NFC tags when the screen -is unlocked, unless NFC is disabled in the device's Settings menu. -When an Android-powered device discovers an NFC tag, the desired behavior -is to have the most appropriate activity handle the intent without asking the user what application -to use. Because devices scan NFC tags at a very short range, it is likely that making users manually -select an activity would force them to move the device away from the tag and break the connection. -You should develop your activity to only handle the NFC tags that your activity cares about to -prevent the Activity Chooser from appearing.

    - -

    To help you with this goal, Android provides a special tag dispatch system that analyzes scanned -NFC tags, parses them, and tries to locate applications that are interested in the scanned data. It -does this by:

    - -
      -
    1. Parsing the NFC tag and figuring out the MIME type or a URI that identifies the data payload - in the tag.
    2. -
    3. Encapsulating the MIME type or URI and the payload into an intent. These first two - steps are described in How NFC tags are mapped to MIME types and URIs.
    4. -
    5. Starts an activity based on the intent. This is described in - How NFC Tags are Dispatched to Applications.
    6. -
    - -

    How NFC tags are mapped to MIME types and URIs

    -

    Before you begin writing your NFC applications, it is important to understand the different -types of NFC tags, how the tag dispatch system parses NFC tags, and the special work that the tag -dispatch system does when it detects an NDEF message. NFC tags come in a -wide array of technologies and can also have data written to them in many different ways. -Android has the most support for the NDEF standard, which is defined by the NFC Forum. -

    - -

    NDEF data is encapsulated inside a message ({@link android.nfc.NdefMessage}) that contains one -or more records ({@link android.nfc.NdefRecord}). Each NDEF record must be well-formed according to -the specification of the type of record that you want to create. Android -also supports other types of tags that do not contain NDEF data, which you can work with by using -the classes in the {@link android.nfc.tech} package. To learn more -about these technologies, see the Advanced -NFC topic. Working with these other types of tags involves -writing your own protocol stack to communicate with the tags, so we recommend using NDEF when -possible for ease of development and maximum support for Android-powered devices. -

    - -

    Note: -To download complete NDEF specifications, go to the NFC Forum Specification Download site and see -Creating common types of NDEF records for examples of how to -construct NDEF records.

    - -

    Now that you have some background in NFC tags, the following sections describe in more detail how -Android handles NDEF formatted tags. When an Android-powered device scans an NFC tag containing NDEF -formatted data, it parses the message and tries to figure out the data's MIME type or identifying -URI. To do this, the system reads the first {@link android.nfc.NdefRecord} inside the {@link -android.nfc.NdefMessage} to determine how to interpret the entire NDEF message (an NDEF message can -have multiple NDEF records). In a well-formed NDEF message, the first {@link android.nfc.NdefRecord} -contains the following fields: -

    -
    3-bit TNF (Type Name Format)
    -
    Indicates how to interpret the variable length type field. Valid values are described in -described in Table 1.
    - -
    Variable length type
    -
    Describes the type of the record. If using {@link android.nfc.NdefRecord#TNF_WELL_KNOWN}, use -this field to specify the Record Type Definition (RTD). Valid RTD values are described in Table 2.
    - -
    Variable length ID
    -
    A unique identifier for the record. This field is not used often, but -if you need to uniquely identify a tag, you can create an ID for it.
    - -
    Variable length payload
    -
    The actual data payload that you want to read or write. An NDEF -message can contain multiple NDEF records, so don't assume the full payload is in the first NDEF -record of the NDEF message.
    - -
    - -

    The tag dispatch system uses the TNF and type fields to try to map a MIME type or URI to the -NDEF message. If successful, it encapsulates that information inside of a {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with the actual payload. However, there -are cases when the tag dispatch system cannot determine the type of data based on the first NDEF -record. This happens when the NDEF data cannot be mapped to a MIME type or URI, or when the -NFC tag does not contain NDEF data to begin with. In such cases, a {@link -android.nfc.Tag} object that has information about the tag's technologies and the payload are -encapsulated inside of a {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent instead.

    - -

    -Table 1. describes how the tag dispatch system maps TNF and type -fields to MIME types or URIs. It also describes which TNFs cannot be mapped to a MIME type or URI. -In these cases, the tag dispatch system falls back to -{@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}. - -

    For example, if the tag dispatch system encounters a record of type {@link -android.nfc.NdefRecord#TNF_ABSOLUTE_URI}, it maps the variable length type field of that record -into a URI. The tag dispatch system encapsulates that URI in the data field of an {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with other information about the tag, -such as the payload. On the other hand, if it encounters a record of type {@link -android.nfc.NdefRecord#TNF_UNKNOWN}, it creates an intent that encapsulates the tag's technologies -instead.

    - - -

    - Table 1. Supported TNFs and their mappings

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Type Name Format (TNF)Mapping
    {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI}URI based on the type field.
    {@link android.nfc.NdefRecord#TNF_EMPTY}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE}URI based on the URN in the type field. The URN is encoded into the NDEF type field in - a shortened form: <domain_name>:<service_name>. - Android maps this to a URI in the form: - vnd.android.nfc://ext/<domain_name>:<service_name>.
    {@link android.nfc.NdefRecord#TNF_MIME_MEDIA}MIME type based on the type field.
    {@link android.nfc.NdefRecord#TNF_UNCHANGED}Invalid in the first record, so falls back to - {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#TNF_UNKNOWN}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#TNF_WELL_KNOWN}MIME type or URI depending on the Record Type Definition (RTD), which you set in the -type field. See Table 2. for more information on -available RTDs and their mappings.
    - -

    - Table 2. Supported RTDs for TNF_WELL_KNOWN and their -mappings

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Record Type Definition (RTD)Mapping
    {@link android.nfc.NdefRecord#RTD_ALTERNATIVE_CARRIER}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_HANDOVER_CARRIER}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_HANDOVER_REQUEST}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_HANDOVER_SELECT}Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
    {@link android.nfc.NdefRecord#RTD_SMART_POSTER}URI based on parsing the payload.
    {@link android.nfc.NdefRecord#RTD_TEXT}MIME type of text/plain.
    {@link android.nfc.NdefRecord#RTD_URI}URI based on payload.
    - -

    How NFC Tags are Dispatched to Applications

    - -

    When the tag dispatch system is done creating an intent that encapsulates the NFC tag and its -identifying information, it sends the intent to an interested application that -filters for the intent. If more than one application can handle the intent, the Activity Chooser -is presented so the user can select the Activity. The tag dispatch system defines three intents, -which are listed in order of highest to lowest priority:

    - -
      -
    1. - {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}: This intent is used to start an -Activity when a tag that contains an NDEF payload is scanned and is of a recognized type. This is -the highest priority intent, and the tag dispatch system tries to start an Activity with this -intent before any other intent, whenever possible. -
    2. - -
    3. {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}: If no activities register to -handle the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} -intent, the tag dispatch system tries to start an application with this intent. This -intent is also directly started (without starting {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} first) if the tag that is scanned -contains NDEF data that cannot be mapped to a MIME type or URI, or if the tag does not contain NDEF -data but is of a known tag technology. -
    4. - -
    5. {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}: This intent is started - if no activities handle the {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} - intents.
    6. -
    - -

    The basic way the tag dispatch system works is as follows:

    - -
      -
    1. Try to start an Activity with the intent that was created by the tag dispatch system -when parsing the NFC tag (either -{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}).
    2. -
    3. If no activities filter for that intent, try to start an Activity with the next - lowest priority intent (either {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}) until an application filters for the - intent or until the tag dispatch system tries all possible intents.
    4. -
    5. If no applications filter for any of the intents, do nothing.
    6. -
    - - - -

    Figure 1. Tag Dispatch System

    - - -

    Whenever possible, work with NDEF messages and the {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent, because it is the most specific out of -the three. This intent allows you to start your application at a more appropriate time than the -other two intents, giving the user a better experience.

    - -

    Requesting NFC Access in the Android Manifest

    - -

    Before you can access a device's NFC hardware and properly handle NFC intents, declare these - items in your AndroidManifest.xml file:

    - - - -

    Filtering for NFC Intents

    - -

    To start your application when an NFC tag that you want to handle is scanned, your application -can filter for one, two, or all three of the NFC intents in the Android manifest. However, you -usually want to filter for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent for the -most control of when your application starts. The {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent is a fallback for {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} when no applications filter for - {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or for when the payload is not -NDEF. Filtering for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is usually too general of a -category to filter on. Many applications will filter for {@link -android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} before {@link -android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, so your application has a low probability of -starting. {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is only available as a last resort -for applications to filter for in the cases where no other applications are installed to handle the -{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}intent.

    - -

    Because NFC tag deployments vary and are many times not under your control, this is not always -possible, which is why you can fallback to the other two intents when necessary. When you have -control over the types of tags and data written, it is recommended that you use NDEF to format your -tags. The following sections describe how to filter for each type of intent.

    - - -

    ACTION_NDEF_DISCOVERED

    -

    -To filter for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intents, declare the -intent filter along with the type of data that you want to filter for. The -following example filters for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} -intents with a MIME type of text/plain: -

    -
    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    -    <category android:name="android.intent.category.DEFAULT"/>
    -    <data android:mimeType="text/plain" />
    -</intent-filter>
    -
    -

    The following example filters for a URI in the form of -http://developer.android.com/index.html. -

    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    -    <category android:name="android.intent.category.DEFAULT"/>
    -   <data android:scheme="http"
    -              android:host="developer.android.com"
    -              android:pathPrefix="/index.html" />
    -</intent-filter>
    -
    - - -

    ACTION_TECH_DISCOVERED

    - -

    If your activity filters for the {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent, -you must create an XML resource file that specifies the technologies that your activity supports -within a tech-list set. Your activity is - considered a match if a tech-list set is a subset of the technologies that are - supported by the tag, which you can obtain by calling {@link android.nfc.Tag#getTechList - getTechList()}.

    - -

    For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your - tech-list set must specify all three, two, or one of the technologies (and nothing - else) in order for your activity to be matched.

    - -

    The following sample defines all of the technologies. You can remove the ones that you do not - need. Save this file (you can name it anything you wish) in the - <project-root>/res/xml folder.

    -
    -<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    -    <tech-list>
    -        <tech>android.nfc.tech.IsoDep</tech>
    -        <tech>android.nfc.tech.NfcA</tech>
    -        <tech>android.nfc.tech.NfcB</tech>
    -        <tech>android.nfc.tech.NfcF</tech>
    -        <tech>android.nfc.tech.NfcV</tech>
    -        <tech>android.nfc.tech.Ndef</tech>
    -        <tech>android.nfc.tech.NdefFormatable</tech>
    -        <tech>android.nfc.tech.MifareClassic</tech>
    -        <tech>android.nfc.tech.MifareUltralight</tech>
    -    </tech-list>
    -</resources>
    -
    - -

    You can also specify multiple tech-list sets. Each of the tech-list - sets is considered independently, and your activity is considered a match if any single - tech-list set is a subset of the technologies that are returned by {@link - android.nfc.Tag#getTechList getTechList()}. This provides AND and OR - semantics for matching technologies. The following example matches tags that can support the - NfcA and Ndef technologies or can support the NfcB and Ndef technologies:

    -
    -<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    -    <tech-list>
    -        <tech>android.nfc.tech.NfcA</tech>
    -        <tech>android.nfc.tech.Ndef</tech>
    -    </tech-list>
    -</resources>
    -
    -<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    -    <tech-list>
    -        <tech>android.nfc.tech.NfcB</tech>
    -        <tech>android.nfc.tech.Ndef</tech>
    -    </tech-list>
    -</resources>
    -
    - -

    In your AndroidManifest.xml file, specify the resource file that you just created - in the <meta-data> element inside the <activity> - element like in the following example:

    -
    -<activity>
    -...
    -<intent-filter>
    -    <action android:name="android.nfc.action.TECH_DISCOVERED"/>
    -</intent-filter>
    -
    -<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
    -    android:resource="@xml/nfc_tech_filter" />
    -...
    -</activity>
    -
    - -

    For more information about working with tag technologies and the {@link -android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent, see Working with Supported Tag -Technologies in the Advanced NFC document.

    -

    ACTION_TAG_DISCOVERED

    -

    To filter for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} use the following intent -filter:

    - - -
    <intent-filter>
    -    <action android:name="android.nfc.action.TAG_DISCOVERED"/>
    -</intent-filter>
    -
    - - - -

    Obtaining information from intents

    - -

    If an activity starts because of an NFC intent, you can obtain information about the scanned NFC -tag from the intent. Intents can contain the following extras depending on the tag that was scanned: - -

    - -

    To obtain these extras, check to see if your activity was launched with one of -the NFC intents to ensure that a tag was scanned, and then obtain the extras out of the -intent. The following example checks for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} -intent and gets the NDEF messages from an intent extra.

    - -
    -public void onResume() {
    -    super.onResume();
    -    ...
    -    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
    -        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    -        if (rawMsgs != null) {
    -            msgs = new NdefMessage[rawMsgs.length];
    -            for (int i = 0; i < rawMsgs.length; i++) {
    -                msgs[i] = (NdefMessage) rawMsgs[i];
    -            }
    -        }
    -    }
    -    //process the msgs array
    -}
    -
    - -

    Alternatively, you can obtain a {@link android.nfc.Tag} object from the intent, which will -contain the payload and allow you to enumerate the tag's technologies:

    - -
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    - - -

    Creating Common Types of NDEF Records

    -

    This section describes how to create common types of NDEF records to help you when writing to -NFC tags or sending data with Android Beam. It also describes how to create the corresponding -intent filter for the record. All of these NDEF record examples should be in the first NDEF -record of the NDEF message that you are writing to a tag or beaming.

    - -

    TNF_ABSOLUTE_URI

    -

    Given the following {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI} NDEF record, which is -stored as the first record inside of an {@link android.nfc.NdefMessage}:

    - -
    -NdefRecord uriRecord = new NdefRecord(
    -    NdefRecord.TNF_ABSOLUTE_URI ,
    -    "http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),
    -    new byte[0], new byte[0]);
    -
    - -

    the intent filter would look like this:

    -
    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    -    <category android:name="android.intent.category.DEFAULT" />
    -    <data android:scheme="http"
    -        android:host="developer.android.com"
    -        android:pathPrefix="/index.html" />
    -</intent-filter>
    -
    - - -

    TNF_MIME_MEDIA

    -

    Given the following {@link android.nfc.NdefRecord#TNF_MIME_MEDIA} NDEF record, which is stored as -the first record inside -of an {@link android.nfc.NdefMessage}:

    -
    -NdefRecord mimeRecord = new NdefRecord(
    -    NdefRecord.TNF_MIME_MEDIA ,
    -    "application/com.example.android.beam".getBytes(Charset.forName("US-ASCII")),
    -    new byte[0], "Beam me up, Android!".getBytes(Charset.forName("US-ASCII")));
    -
    - -

    the intent filter would look like this:

    -
    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    -    <category android:name="android.intent.category.DEFAULT" />
    -    <data android:mimeType="application/com.example.android.beam" />
    -</intent-filter>
    -
    - - -

    TNF_WELL_KNOWN with RTD_TEXT

    - -

    Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as -the first record inside of an {@link android.nfc.NdefMessage}:

    -
    -public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    -    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    -    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    -    byte[] textBytes = payload.getBytes(utfEncoding);
    -    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    -    char status = (char) (utfBit + langBytes.length);
    -    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    -    data[0] = (byte) status;
    -    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    -    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    -    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    -    NdefRecord.RTD_TEXT, new byte[0], data);
    -    return record;
    -}
    -
    - -

    the intent filter would look like this:

    -
    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    -    <category android:name="android.intent.category.DEFAULT" />
    -    <data android:mimeType="text/plain" />
    -</intent-filter>
    -
    - - -

    TNF_WELL_KNOWN with RTD_URI

    - -

    Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as -the first record inside of an {@link android.nfc.NdefMessage}:

    - -
    -byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII"));
    -byte[] payload = new byte[uriField.length + 1];              //add 1 for the URI Prefix
    -byte payload[0] = 0x01;                                      //prefixes http://www. to the URI
    -System.arraycopy(uriField, 0, payload, 1, uriField.length);  //appends URI to payload
    -NdefRecord rtdUriRecord = new NdefRecord(
    -    NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);
    -
    - -

    the intent filter would look like this:

    - -
    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    -    <category android:name="android.intent.category.DEFAULT" />
    -    <data android:scheme="http"
    -        android:host="example.com"
    -        android:pathPrefix="" />
    -</intent-filter>
    -
    - -

    TNF_EXTERNAL_TYPE

    -

    Given the following {@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} NDEF record, which is stored -as the first record inside of an {@link android.nfc.NdefMessage}:

    - -
    -byte[] payload;
    -...
    -NdefRecord mimeRecord = new NdefRecord(
    -    NdefRecord.TNF_EXTERNAL_TYPE, "example.com:externalType", new byte[0], payload);
    -
    - -

    the intent filter would look like this:

    -
    -<intent-filter>
    -    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    -    <category android:name="android.intent.category.DEFAULT" />
    -    <data android:scheme="vnd.android.nfc"
    -        android:host="ext"
    -        android:pathPrefix="/example.com:externalType"/>
    -</intent-filter>
    -
    - - -

    Use TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better support both -Android-powered and non-Android-powered devices.

    - -

    Note: URNs for {@link -android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} have a canonical format of: -urn:nfc:ext:example.com:externalType, however the NFC Forum RTD specification -declares that the urn:nfc:ext: portion of the URN must be ommitted from the -NDEF record. So all you need to provide is the domain (example.com in the example) -and type (externalType in the example) separated by a colon. -When dispatching TNF_EXTERNAL_TYPE, Android converts the urn:nfc:ext:example.com:externalType URN to a -vnd.android.nfc://ext/example.com:externalType URI, which is what the intent filter in the example -declares.

    - -

    Android Application Records

    - -

    -Introduced in Android 4.0 (API level 14), an Android Application Record (AAR) provides a stronger -certainty that your application is started when an NFC tag is scanned. An AAR has the package name -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, -Google Play is launched to download the application.

    - -

    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, use intent filters. -

    - - - -

    If a tag contains an AAR, the tag dispatch system dispatches in the following manner:

    -
      -
    1. Try to start an Activity using an intent filter as normal. If the Activity that matches -the intent also matches the AAR, start the Activity.
    2. -
    3. 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.
    4. -
    5. If no application can start with the AAR, go to Google Play to download the -application based on the AAR.
    6. -
    - -

    - -

    Note: You can override AARs and the intent dispatch system with the foreground dispatch -system, which allows a foreground activity to have priority when an NFC tag is discovered. -With this method, the activity must be in the foreground to -override AARs and the intent dispatch system.

    - -

    If you still want to filter for scanned tags that do not contain an AAR, you can declare -intent filters as normal. This is useful if your application is interested in other tags -that do not contain an AAR. For example, maybe you want to guarantee that your application handles -proprietary tags that you deploy as well as general tags deployed by third parties. Keep in mind -that AARs are specific to Android 4.0 devices or later, so when deploying tags, you most likely want -to use a combination of AARs and MIME types/URIs to support the widest range of devices. In -addition, when you deploy NFC tags, think about how you want to write your NFC tags to enable -support for the most devices (Android-powered and other devices). You can do this by -defining a relatively unique MIME type or URI to make it easier for applications to distinguish. -

    - -

    Android provides a simple API to create an AAR, -{@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}. All you need to -do is embed the AAR anywhere in your {@link android.nfc.NdefMessage}. You do not want -to use the first record of your {@link android.nfc.NdefMessage}, unless the AAR is the only -record in the {@link android.nfc.NdefMessage}. This is because the Android -system checks the first record of an {@link android.nfc.NdefMessage} to determine the MIME type or -URI of the tag, which is used to create an intent for applications to filter. The following code -shows you how to create an AAR:

    - -
    -NdefMessage msg = new NdefMessage(
    -        new NdefRecord[] {
    -            ...,
    -            NdefRecord.createApplicationRecord("com.example.android.beam")}
    -
    - - -

    Beaming NDEF Messages to Other Devices

    - -

    Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The -application that wants to beam data to another device must be in the foreground and the device -receiving the data must not be locked. When the beaming device comes in close enough contact with a -receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose -whether or not to beam the message to the receiving device.

    - -

    Note: Foreground NDEF pushing was available at API level 10, -which provides similar functionality to Android Beam. These APIs have since been deprecated, but -are available to support older devices. See {@link android.nfc.NfcAdapter#enableForegroundNdefPush -enableForegroundNdefPush()} for more information.

    - -

    You can enable Android Beam for your application by calling one of the two methods:

    - - -

    An activity can only push one NDEF message at a time, so {@link -android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()} takes precedence -over {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if both are set. To use -Android Beam, the following general guidelines must be met: -

    - - - -

    Note: If your activity enables Android Beam and is -in the foreground, the standard intent dispatch system is disabled. However, if your activity also -enables foreground -dispatching, then it can still scan tags that match the intent filters set in the foreground -dispatching.

    - -

    To enable Android Beam:

    - -
      -
    1. Create an {@link android.nfc.NdefMessage} that contains the {@link android.nfc.NdefRecord}s -that you want to push onto the other device.
    2. - -
    3. Call {@link -android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} with a {@link -android.nfc.NdefMessage} or call {@link -android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} passing in a {@link -android.nfc.NfcAdapter.CreateNdefMessageCallback} object in the onCreate() method of -your activity. These methods require at least one activity that you want to enable with Android -Beam, along with an optional list of other activities to activate. - -

      In general, you normally use {@link -android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if your Activity only needs to -push the same NDEF message at all times, when two devices are in range to communicate. You use -{@link android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} when your -application cares about the current context of the application and wants to push an NDEF message -depending on what the user is doing in your application.

      -
    4. -
    - -

    The following sample shows how a simple activity calls {@link -android.nfc.NfcAdapter.CreateNdefMessageCallback} in the onCreate() method of an -activity (see AndroidBeamDemo -for the complete sample). This example also has methods to help you create a MIME record:

    - -
    -package com.example.android.beam;
    -
    -import android.app.Activity;
    -import android.content.Intent;
    -import android.nfc.NdefMessage;
    -import android.nfc.NdefRecord;
    -import android.nfc.NfcAdapter;
    -import android.nfc.NfcAdapter.CreateNdefMessageCallback;
    -import android.nfc.NfcEvent;
    -import android.os.Bundle;
    -import android.os.Parcelable;
    -import android.widget.TextView;
    -import android.widget.Toast;
    -import java.nio.charset.Charset;
    -
    -
    -public class Beam extends Activity implements CreateNdefMessageCallback {
    -    NfcAdapter mNfcAdapter;
    -    TextView textView;
    -
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        setContentView(R.layout.main);
    -        TextView textView = (TextView) findViewById(R.id.textView);
    -        // Check for available NFC Adapter
    -        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    -        if (mNfcAdapter == null) {
    -            Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
    -            finish();
    -            return;
    -        }
    -        // Register callback
    -        mNfcAdapter.setNdefPushMessageCallback(this, this);
    -    }
    -
    -    @Override
    -    public NdefMessage createNdefMessage(NfcEvent event) {
    -        String text = ("Beam me up, Android!\n\n" +
    -                "Beam Time: " + System.currentTimeMillis());
    -        NdefMessage msg = new NdefMessage(
    -                new NdefRecord[] { createMimeRecord(
    -                        "application/com.example.android.beam", text.getBytes())
    -         /**
    -          * The Android Application Record (AAR) is commented out. When a device
    -          * receives a push with an AAR in it, the application specified in the AAR
    -          * is guaranteed to run. The AAR overrides the tag dispatch system.
    -          * You can add it back in to guarantee that this
    -          * activity starts when receiving a beamed message. For now, this code
    -          * uses the tag dispatch system.
    -          */
    -          //,NdefRecord.createApplicationRecord("com.example.android.beam")
    -        });
    -        return msg;
    -    }
    -
    -    @Override
    -    public void onResume() {
    -        super.onResume();
    -        // Check to see that the Activity started due to an Android Beam
    -        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
    -            processIntent(getIntent());
    -        }
    -    }
    -
    -    @Override
    -    public void onNewIntent(Intent intent) {
    -        // onResume gets called after this to handle the intent
    -        setIntent(intent);
    -    }
    -
    -    /**
    -     * Parses the NDEF Message from the intent and prints to the TextView
    -     */
    -    void processIntent(Intent intent) {
    -        textView = (TextView) findViewById(R.id.textView);
    -        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
    -                NfcAdapter.EXTRA_NDEF_MESSAGES);
    -        // only one message sent during the beam
    -        NdefMessage msg = (NdefMessage) rawMsgs[0];
    -        // record 0 contains the MIME type, record 1 is the AAR, if present
    -        textView.setText(new String(msg.getRecords()[0].getPayload()));
    -    }
    -
    -    /**
    -     * Creates a custom MIME type encapsulated in an NDEF record
    -     */
    -    public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
    -        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
    -        NdefRecord mimeRecord = new NdefRecord(
    -                NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
    -        return mimeRecord;
    -    }
    -}
    -
    - -

    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, 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: -

    - -
    -<intent-filter>
    -  <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    -  <category android:name="android.intent.category.DEFAULT"/>
    -  <data android:mimeType="application/com.example.android.beam"/>
    -</intent-filter>
    -
    -

    With this intent filter, the com.example.android.beam application now can be started -when it scans an NFC tag or receives an Android Beam with an AAR of -type com.example.android.beam, or when an NDEF formatted message contains a MIME record -of type application/com.example.android.beam.

    - -

    Even though AARs guarantee an application is started or downloaded, intent filters are -recommended, because they let you start an Activity of your choice in your -application instead of always starting the main Activity within the package specified by an AAR. -AARs do not have Activity level granularity. Also, because some Android-powered devices do not -support AARs, you should also embed identifying information in the first NDEF record of your NDEF -messages and filter for that as well, just in case. See Creating Common -Types of NDEF records for more information on how to create records. -

    diff --git a/docs/html/guide/topics/providers/calendar-provider.jd b/docs/html/guide/topics/providers/calendar-provider.jd index d30dda423ec5..f53b0625841d 100644 --- a/docs/html/guide/topics/providers/calendar-provider.jd +++ b/docs/html/guide/topics/providers/calendar-provider.jd @@ -250,27 +250,30 @@ and store its events on the device.

    Querying a calendar

    -

    Here is an example that shows how to get all the calendars for a particular +

    Here is an example that shows how to get the calendars that are owned by a particular user. For simplicity's sake, in this example the query operation is shown in the user interface thread ("main thread"). In practice, this should be done in an asynchronous thread instead of on the main thread. For more discussion, see -Loaders. If you are not just reading data but modifying it, see {@link android.content.AsyncQueryHandler}. +Loaders. If you are not just +reading data but modifying it, see {@link android.content.AsyncQueryHandler}.

    -  // Projection array. Creating indices for this array instead of doing
    -  // dynamic lookups improves performance.
    -  public static final String[] EVENT_PROJECTION = new String[] {
    +// Projection array. Creating indices for this array instead of doing
    +// dynamic lookups improves performance.
    +public static final String[] EVENT_PROJECTION = new String[] {
         Calendars._ID,                           // 0
         Calendars.ACCOUNT_NAME,                  // 1
    -    Calendars.CALENDAR_DISPLAY_NAME          // 2
    -  };
    +    Calendars.CALENDAR_DISPLAY_NAME,         // 2
    +    Calendars.OWNER_ACCOUNT                  // 3
    +};
       
    -  // The indices for the projection array above.
    -  private static final int PROJECTION_ID_INDEX = 0;
    -  private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
    -  private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
    +// The indices for the projection array above. +private static final int PROJECTION_ID_INDEX = 0; +private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1; +private static final int PROJECTION_DISPLAY_NAME_INDEX = 2; +private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;

    In the next part of the example, you construct your query. The selection specifies the criteria for the query. In this example the query is looking for -all calendars that have the ACCOUNT_NAME -"sampleuser@google.com" and the ACCOUNT_TYPE -"com.google". The query returns a {@link android.database.Cursor} +calendars that have the ACCOUNT_NAME +"sampleuser@google.com", the ACCOUNT_TYPE +"com.google", and the OWNER_ACCOUNT +"sampleuser@google.com". If you want to see all calendars that a user +has viewed, not just calendars the user owns, omit the OWNER_ACCOUNT. +The query returns a {@link android.database.Cursor} object that you can use to traverse the result set returned by the database -query. For more discussion of using queries in content providers, see Content Providers.

    +query. For more discussion of using queries in content providers, +see Content Providers.

    // Run query
    @@ -303,8 +310,10 @@ Cursor cur = null;
     ContentResolver cr = getContentResolver();
     Uri uri = Calendars.CONTENT_URI;   
     String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" 
    -                        + Calendars.ACCOUNT_TYPE + " = ?))";
    -String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google"}; 
    +                        + Calendars.ACCOUNT_TYPE + " = ?) AND ("
    +                        + Calendars.OWNER_ACCOUNT + " = ?))";
    +String[] selectionArgs = new String[] {"sampleuser@gmail.com", "com.google",
    +        "sampleuser@gmail.com"}; 
     // Submit the query and get a Cursor object back. 
     cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
    @@ -316,12 +325,14 @@ for each field.

    while (cur.moveToNext()) { long calID = 0; String displayName = null; - String accountName = null; + String accountName = null; + String ownerName = null; // Get the field values calID = cur.getLong(PROJECTION_ID_INDEX); displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX); accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX); + ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX); // Do something with the values... @@ -1179,5 +1190,3 @@ However, a sync adapter is restricted to the ACCOUNT_NAME and

    For a sample implementation of a sync adapter (not specifically related to Calendar), see SampleSyncAdapter. - - diff --git a/docs/html/guide/topics/providers/contacts-provider.jd b/docs/html/guide/topics/providers/contacts-provider.jd new file mode 100644 index 000000000000..e3b998a7677f --- /dev/null +++ b/docs/html/guide/topics/providers/contacts-provider.jd @@ -0,0 +1,2361 @@ +page.title=Contacts Provider +@jd:body +

    +
    +

    Quickview

    +
      +
    • Android's repository of information about people.
    • +
    • + Syncs with the web. +
    • +
    • + Integrates social stream data. +
    • +
    +

    In this document

    +
      +
    1. + Contacts Provider Organization +
    2. +
    3. + Raw contacts +
    4. +
    5. + Data +
    6. +
    7. + Contacts +
    8. +
    9. + Data From Sync Adapters +
    10. +
    11. + Required Permissions +
    12. +
    13. + The User Profile +
    14. +
    15. + Contacts Provider Metadata +
    16. +
    17. + Contacts Provider Access +
    18. +
    19. +
    20. + Contacts Provider Sync Adapters +
    21. +
    22. + Social Stream Data +
    23. +
    24. + Additional Contacts Provider Features +
    25. +
    +

    Key classes

    +
      +
    1. {@link android.provider.ContactsContract.Contacts}
    2. +
    3. {@link android.provider.ContactsContract.RawContacts}
    4. +
    5. {@link android.provider.ContactsContract.Data}
    6. +
    7. {@link android.provider.ContactsContract.StreamItems}
    8. +
    +

    Related Samples

    +
      +
    1. + + Contact Manager + +
    2. +
    3. + + Sample Sync Adapter +
    4. +
    +

    See Also

    +
      +
    1. + + Content Provider Basics + +
    2. +
    +
    +
    +

    + The Contacts Provider is a powerful and flexible Android component that manages the + device's central repository of data about people. The Contacts Provider is the source of data + you see in the device's contacts application, and you can also access its data in your own + application and transfer data between the device and online services. The provider accommodates + a wide range of data sources and tries to manage as much data as possible for each person, with + the result that its organization is complex. Because of this, the provider's API includes an + extensive set of contract classes and interfaces that facilitate both data retrieval and + modification. +

    +

    + This guide describes the following: +

    + +

    + This guide assumes that you know the basics of Android content providers. To learn more + about Android content providers, read the + + Content Provider Basics guide. The + Sample Sync Adapter + sample app is an example of using a sync adapter to transfer data between the Contacts + Provider and a sample application hosted by Google Web Services. +

    +

    Contacts Provider Organization

    +

    + The Contacts Provider is an Android content provider component. It maintains three types of + data about a person, each of which corresponds to a table offered by the provider, as + illustrated in figure 1: +

    + +

    + Figure 1. Contacts Provider table structure. +

    +

    + The three tables are commonly referred to by the names of their contract classes. The classes + define constants for content URIs, column names, and column values used by the tables: +

    +
    +
    + {@link android.provider.ContactsContract.Contacts} table +
    +
    + Rows representing different people, based on aggregations of raw contact rows. +
    +
    + {@link android.provider.ContactsContract.RawContacts} table +
    +
    + Rows containing a summary of a person's data, specific to a user account and type. +
    +
    + {@link android.provider.ContactsContract.Data} table +
    +
    + Rows containing the details for raw contact, such as email addresses or phone numbers. +
    +
    +

    + The other tables represented by contract classes in {@link android.provider.ContactsContract} + are auxiliary tables that the Contacts Provider uses to manage its operations or support + specific functions in the device's contacts or telephony applications. +

    +

    Raw contacts

    +

    + A raw contact represents a person's data coming from a single account type and account + name. Because the Contacts Provider allows more than one online service as the source of + data for a person, the Contacts Provider allows multiple raw contacts for the same person. + Multiple raw contacts also allow a user to combine a person's data from more than one account + from the same account type. +

    +

    + Most of the data for a raw contact isn't stored in the + {@link android.provider.ContactsContract.RawContacts} table. Instead, it's stored in one or more + rows in the {@link android.provider.ContactsContract.Data} table. Each data row has a column + {@link android.provider.ContactsContract.DataColumns#RAW_CONTACT_ID Data.RAW_CONTACT_ID} that + contains the {@link android.provider.BaseColumns#_ID RawContacts._ID} value of its + parent {@link android.provider.ContactsContract.RawContacts} row. +

    +

    Important raw contact columns

    +

    + The important columns in the {@link android.provider.ContactsContract.RawContacts} table are + listed in table 1. Please read the notes that follow after the table: +

    +

    + Table 1. Important raw contact columns. +

    + + + + + + + + + + + + + + + + + + + + +
    Column nameUseNotes
    + {@link android.provider.ContactsContract.SyncColumns#ACCOUNT_NAME} + + The account name for the account type that's the source of this raw contact. + For example, the account name of a Google account is one of the device owner's Gmail + addresses. See the next entry for + {@link android.provider.ContactsContract.SyncColumns#ACCOUNT_TYPE} for more + information. + + The format of this name is specific to its account type. It is not + necessarily an email address. +
    + {@link android.provider.ContactsContract.SyncColumns#ACCOUNT_TYPE} + + The account type that's the source of this raw contact. For example, the account + type of a Google account is com.google. Always qualify your account type + with a domain identifier for a domain you own or control. This will ensure that your + account type is unique. + + An account type that offers contacts data usually has an associated sync adapter that + synchronizes with the Contacts Provider. +
    + {@link android.provider.ContactsContract.RawContactsColumns#DELETED} + + The "deleted" flag for a raw contact. + + This flag allows the Contacts Provider to maintain the row internally until sync + adapters are able to delete the row from their servers and then finally delete the row + from the repository. +
    +

    Notes

    +

    + The following are important notes about the + {@link android.provider.ContactsContract.RawContacts} table: +

    + +

    Sources of raw contacts data

    +

    + To understand how raw contacts work, consider the user "Emily Dickinson" who has the following + three user accounts defined on her device: +

    + +

    + This user has enabled Sync Contacts for all three of these accounts in the + Accounts settings. +

    +

    + Suppose Emily Dickinson opens a browser window, logs into Gmail as + emily.dickinson@gmail.com, opens + Contacts, and adds "Thomas Higginson". Later on, she logs into Gmail as + emilyd@gmail.com and sends an email to "Thomas Higginson", which automatically + adds him as a contact. She also follows "colonel_tom" (Thomas Higginson's Twitter ID) on + Twitter. +

    +

    + The Contacts Provider creates three raw contacts as a result of this work: +

    +
      +
    1. + A raw contact for "Thomas Higginson" associated with emily.dickinson@gmail.com. + The user account type is Google. +
    2. +
    3. + A second raw contact for "Thomas Higginson" associated with emilyd@gmail.com. + The user account type is also Google. There is a second raw contact even + though the name is identical to a previous name, because the person was added for a + different user account. +
    4. +
    5. + A third raw contact for "Thomas Higginson" associated with "belle_of_amherst". The user + account type is Twitter. +
    6. +
    +

    Data

    +

    + As noted previously, the data for a raw contact is stored in a + {@link android.provider.ContactsContract.Data} row that is linked to the raw contact's + _ID value. This allows a single raw contact to have multiple instances of the same + type of data such as email addresses or phone numbers. For example, if + "Thomas Higginson" for {@code emilyd@gmail.com} (the raw contact row for Thomas Higginson + associated with the Google account emilyd@gmail.com) has a home email address of + thigg@gmail.com and a work email address of + thomas.higginson@gmail.com, the Contacts Provider stores the two email address + rows and links them both to the raw contact. +

    +

    + Notice that different types of data are stored in this single table. Display name, + phone number, email, postal address, photo, and website detail rows are all found in the + {@link android.provider.ContactsContract.Data} table. To help manage this, the + {@link android.provider.ContactsContract.Data} table has some columns with descriptive names, + and others with generic names. The contents of a descriptive-name column have the same meaning + regardless of the type of data in the row, while the contents of a generic-name column have + different meanings depending on the type of data. +

    +

    Descriptive column names

    +

    + Some examples of descriptive column names are: +

    +
    +
    + {@link android.provider.ContactsContract.Data#RAW_CONTACT_ID} +
    +
    + The value of the _ID column of the raw contact for this data. +
    +
    + {@link android.provider.ContactsContract.Data#MIMETYPE} +
    +
    + The type of data stored in this row, expressed as a custom MIME type. The Contacts Provider + uses the MIME types defined in the subclasses of + {@link android.provider.ContactsContract.CommonDataKinds}. These MIME types are open source, + and can be used by any application or sync adapter that works with the Contacts Provider. +
    +
    + {@link android.provider.ContactsContract.DataColumns#IS_PRIMARY} +
    +
    + If this type of data row can occur more than once for a raw contact, the + {@link android.provider.ContactsContract.DataColumns#IS_PRIMARY} column flags + the data row that contains the primary data for the type. For example, if + the user long-presses a phone number for a contact and selects Set default, + then the {@link android.provider.ContactsContract.Data} row containing that number + has its {@link android.provider.ContactsContract.DataColumns#IS_PRIMARY} column set to a + non-zero value. +
    +
    +

    Generic column names

    +

    + There are 15 generic columns named DATA1 through + DATA15 that are generally available and an additional four generic + columns SYNC1 through SYNC4 that should only be used by sync + adapters. The generic column name constants always work, regardless of the type of + data the row contains. +

    +

    + The DATA1 column is indexed. The Contacts Provider always uses this column for + the data that the provider expects will be the most frequent target of a query. For example, + in an email row, this column contains the actual email address. +

    +

    + By convention, the column DATA15 is reserved for storing Binary Large Object + (BLOB) data such as photo thumbnails. +

    +

    Type-specific column names

    +

    + To facilitate working with the columns for a particular type of row, the Contacts Provider + also provides type-specific column name constants, defined in subclasses of + {@link android.provider.ContactsContract.CommonDataKinds}. The constants simply give a + different constant name to the same column name, which helps you access data in a row of a + particular type. +

    +

    + For example, the {@link android.provider.ContactsContract.CommonDataKinds.Email} class defines + type-specific column name constants for a {@link android.provider.ContactsContract.Data} row + that has the MIME type + {@link android.provider.ContactsContract.CommonDataKinds.Email#CONTENT_ITEM_TYPE + Email.CONTENT_ITEM_TYPE}. The class contains the constant + {@link android.provider.ContactsContract.CommonDataKinds.Email#ADDRESS} for the email address + column. The actual value of + {@link android.provider.ContactsContract.CommonDataKinds.Email#ADDRESS} is "data1", which is + the same as the column's generic name. +

    +

    + Caution: Don't add your own custom data to the + {@link android.provider.ContactsContract.Data} table using a row that has one of the + provider's pre-defined MIME types. If you do, you may lose the data or cause the provider to + malfunction. For example, you should not add a row with the MIME type + {@link android.provider.ContactsContract.CommonDataKinds.Email#CONTENT_ITEM_TYPE + Email.CONTENT_ITEM_TYPE} that contains a user name instead of an email address in the + column DATA1. If you use your own custom MIME type for the row, then you are free + to define your own type-specific column names and use the columns however you wish. +

    +

    + Figure 2 shows how descriptive columns and data columns appear in a + {@link android.provider.ContactsContract.Data} row, and how type-specific column names "overlay" + the generic column names +

    +How type-specific column names map to generic column names +

    + Figure 2. Type-specific column names and generic column names. +

    +

    Type-specific column name classes

    +

    + Table 2 lists the most commonly-used type-specific column name classes: +

    +

    + Table 2. Type-specific column name classes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Mapping classType of dataNotes
    {@link android.provider.ContactsContract.CommonDataKinds.StructuredName}The name data for the raw contact associated with this data row.A raw contact has only one of these rows.
    {@link android.provider.ContactsContract.CommonDataKinds.Photo}The main photo for the raw contact associated with this data row.A raw contact has only one of these rows.
    {@link android.provider.ContactsContract.CommonDataKinds.Email}An email address for the raw contact associated with this data row.A raw contact can have multiple email addresses.
    {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal}A postal address for the raw contact associated with this data row.A raw contact can have multiple postal addresses.
    {@link android.provider.ContactsContract.CommonDataKinds.GroupMembership}An identifier that links the raw contact to one of the groups in the Contacts Provider. + Groups are an optional feature of an account type and account name. They're described in + more detail in the section Contact groups. +
    +

    Contacts

    +

    + The Contacts Provider combines the raw contact rows across all account types and account names + to form a contact. This facilitates displaying and modifying all the data a + user has collected for a person. The Contacts Provider manages the creation of new contact + rows, and the aggregation of raw contacts with an existing contact row. Neither applications nor + sync adapters are allowed to add contacts, and some columns in a contact row are read-only. +

    +

    + Note: If you try to add a contact to the Contacts Provider with an + {@link android.content.ContentResolver#insert(Uri,ContentValues) insert()}, you'll get + an {@link java.lang.UnsupportedOperationException} exception. If you try to update a column + that's listed as "read-only," the update is ignored. +

    +

    + The Contacts Provider creates a new contact in response to the addition of a new raw contact + that doesn't match any existing contacts. The provider also does this if an existing raw + contact's data changes in such a way that it no longer matches the contact to which it was + previously attached. If an application or sync adapter creates a new raw contact that + does match an existing contact, the new raw contact is aggregated to the existing + contact. +

    +

    + The Contacts Provider links a contact row to its raw contact rows with the contact row's + _ID column in the {@link android.provider.ContactsContract.Contacts Contacts} + table. The CONTACT_ID column of the raw contacts table + {@link android.provider.ContactsContract.RawContacts} contains _ID values for + the contacts row associated with each raw contacts row. +

    +

    + The {@link android.provider.ContactsContract.Contacts} table also has the column + {@link android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY} that is a + "permanent" link to the contact row. Because the Contacts Provider maintains contacts + automatically, it may change a contact row's {@link android.provider.BaseColumns#_ID} value + in response to an aggregation or sync. Even If this happens, the content URI + {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI} combined with + contact's {@link android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY} will still + point to the contact row, so you can use + {@link android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY} + to maintain links to "favorite" contacts, and so forth. This column has its own format that is + unrelated to the format of the {@link android.provider.BaseColumns#_ID} column. +

    +

    + Figure 3 shows how the three main tables relate to each other. +

    +Contacts provider main tables +

    + Figure 3. Contacts, Raw Contacts, and Details table relationships. +

    +

    Data From Sync Adapters

    +

    + Users enter contacts data directly into the device, but data also flows into the Contacts + Provider from web services via sync adapters, which automate + the transfer of data between the device and services. Sync adapters run in the background + under the control of the system, and they call {@link android.content.ContentResolver} methods + to manage data. +

    +

    + In Android, the web service that a sync adapter works with is identified by an account type. + Each sync adapter works with one account type, but it can support multiple account names for + that type. Account types and account names are described briefly in the section + Sources of raw contacts data. The following definitions offer + more detail, and describe how account type and name relate to sync adapters and services. +

    +
    +
    + Account type +
    +
    + Identifies a service in which the user has stored data. Most of the time, the user has to + authenticate with the service. For example, Google Contacts is an account type, identified + by the code google.com. This value corresponds to the account type used by + {@link android.accounts.AccountManager}. +
    +
    + Account name +
    +
    + Identifies a particular account or login for an account type. Google Contacts accounts + are the same as Google accounts, which have an email address as an account name. + Other services may use a single-word username or numeric id. +
    +
    +

    + Account types don't have to be unique. A user can configure multiple Google Contacts accounts + and download their data to the Contacts Provider; this may happen if the user has one set of + personal contacts for a personal account name, and another set for work. Account names are + usually unique. Together, they identify a specific data flow between the Contacts Provider and + an external service. +

    +

    + If you want to transfer your service's data to the Contacts Provider, you need to write your + own sync adapter. This is described in more detail in the section + Contacts Provider Sync Adapters. +

    +

    + Figure 4 shows how the Contacts Provider fits into the flow of data + about people. In the box marked "sync adapters," each adapter is labeled by its account type. +

    +Flow of data about people +

    + Figure 4. The Contacts Provider flow of data. +

    +

    Required Permissions

    +

    + Applications that want to access the Contacts Provider must request the following + permissions: +

    +
    +
    Read access to one or more tables
    +
    + {@link android.Manifest.permission#READ_CONTACTS}, specified in + AndroidManifest.xml with the + + <uses-permission> element as + <uses-permission android:name="android.permission.READ_CONTACTS">. +
    +
    Write access to one or more tables
    +
    + {@link android.Manifest.permission#WRITE_CONTACTS}, specified in + AndroidManifest.xml with the + + <uses-permission> element as + <uses-permission android:name="android.permission.WRITE_CONTACTS">. +
    +
    +

    + These permissions do not extend to the user profile data. The user profile and its + required permissions are discussed in the following section, + The User Profile. +

    +

    + Remember that the user's contacts data is personal and sensitive. Users are concerned about + their privacy, so they don't want applications collecting data about them or their contacts. + If it's not obvious why you need permission to access their contacts data, they may give + your application low ratings or simply refuse to install it. +

    +

    The User Profile

    +

    + The {@link android.provider.ContactsContract.Contacts} table has a single row containing + profile data for the device's user. This data describes the device's user rather + than one of the user's contacts. The profile contacts row is linked to a raw + contacts row for each system that uses a profile. + Each profile raw contact row can have multiple data rows. Constants for accessing the user + profile are available in the {@link android.provider.ContactsContract.Profile} class. +

    +

    + Access to the user profile requires special permissions. In addition to the + {@link android.Manifest.permission#READ_CONTACTS} and + {@link android.Manifest.permission#WRITE_CONTACTS} permissions needed to read and write, access + to the user profile requires the {@link android.Manifest.permission#READ_PROFILE} and + {@link android.Manifest.permission#WRITE_PROFILE} permissions for read and write access, + respectively. +

    +

    + Remember that you should consider a user's profile to be sensitive. The permission + {@link android.Manifest.permission#READ_PROFILE} allows you to access the device user's + personally-identifying data. Make sure to tell the user why + you need user profile access permissions in the description of your application. +

    +

    + To retrieve the contact row that contains the user's profile, + call {@link android.content.ContentResolver#query(Uri,String[], String, String[], String) + ContentResolver.query()}. Set the content URI to + {@link android.provider.ContactsContract.Profile#CONTENT_URI} and don't provide any + selection criteria. You can also use this content URI as the base URI for retrieving raw + contacts or data for the profile. For example, this snippet retrieves data for the profile: +

    +
    +// Sets the columns to retrieve for the user profile
    +mProjection = new String[]
    +    {
    +        Profile._ID,
    +        Profile.DISPLAY_NAME_PRIMARY,
    +        Profile.LOOKUP_KEY,
    +        Profile.PHOTO_THUMBNAIL_URI
    +    };
    +
    +// Retrieves the profile from the Contacts Provider
    +mProfileCursor =
    +        getContentResolver().query(
    +                Profile.CONTENT_URI,
    +                mProjection ,
    +                null,
    +                null,
    +                null);
    +
    +

    + Note: If you retrieve multiple contact rows, and you want to determine if one of them + is the user profile, test the row's + {@link android.provider.ContactsContract.ContactsColumns#IS_USER_PROFILE} column. This column + is set to "1" if the contact is the user profile. +

    +

    Contacts Provider Metadata

    +

    + The Contacts Provider manages data that keeps track of the state of contacts data in the + repository. This metadata about the repository is stored in various places, including the + Raw Contacts, Data, and Contacts table rows, the + {@link android.provider.ContactsContract.Settings} table, and the + {@link android.provider.ContactsContract.SyncState} table. The following table shows the + effect of each of these pieces of metadata: +

    +

    + Table 3. Metadata in the Contacts Provider

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TableColumnValuesMeaning
    {@link android.provider.ContactsContract.RawContacts}{@link android.provider.ContactsContract.SyncColumns#DIRTY}"0" - not changed since the last sync. + Marks raw contacts that were changed on the device and have to be synced back to the + server. The value is set automatically by the Contacts Provider when Android + applications update a row. +

    + Sync adapters that modify the raw contact or data tables should always append the + string {@link android.provider.ContactsContract#CALLER_IS_SYNCADAPTER} to the + content URI they use. This prevents the provider from marking rows as dirty. + Otherwise, sync adapter modifications appear to be local modifications and are + sent to the server, even though the server was the source of the modification. +

    +
    "1" - changed since last sync, needs to be synced back to the server.
    {@link android.provider.ContactsContract.RawContacts}{@link android.provider.ContactsContract.SyncColumns#VERSION}The version number of this row. + The Contacts Provider automatically increments this value whenever the row or + its related data changes. +
    {@link android.provider.ContactsContract.Data}{@link android.provider.ContactsContract.DataColumns#DATA_VERSION}The version number of this row. + The Contacts Provider automatically increments this value whenever the data row + is changed. +
    {@link android.provider.ContactsContract.RawContacts}{@link android.provider.ContactsContract.SyncColumns#SOURCE_ID} + A string value that uniquely identifies this raw contact to the account in + which it was created. + + When a sync adapter creates a new raw contact, this column should be set to the + server's unique ID for the raw contact. When an Android application creates a new + raw contact, the application should leave this column empty. This signals the sync + adapter that it should create a new raw contact on the server, and get a + value for the {@link android.provider.ContactsContract.SyncColumns#SOURCE_ID}. +

    + In particular, the source id must be unique for each account + type and should be stable across syncs: +

    +
      +
    • + Unique: Each raw contact for an account must have its own source id. If you + don't enforce this, you'll cause problems in the contacts application. + Notice that two raw contacts for the same account type may have + the same source id. For example, the raw contact "Thomas Higginson" for the + account {@code emily.dickinson@gmail.com} is allowed to have the same source + id as the raw contact "Thomas Higginson" for the account + {@code emilyd@gmail.com}. +
    • +
    • + Stable: Source ids are a permanent part of the online service's data for + the raw contact. For example, if the user clears Contacts Storage from the + Apps settings and re-syncs, the restored raw contacts should have the same + source ids as before. If you don't enforce this, shortcuts will stop + working. +
    • +
    +
    {@link android.provider.ContactsContract.Groups}{@link android.provider.ContactsContract.GroupsColumns#GROUP_VISIBLE}"0" - Contacts in this group should not be visible in Android application UIs. + This column is for compatibility with servers that allow a user to hide contacts in + certain groups. +
    "1" - Contacts in this group are allowed to be visible in application UIs.
    {@link android.provider.ContactsContract.Settings} + {@link android.provider.ContactsContract.SettingsColumns#UNGROUPED_VISIBLE} + "0" - For this account and account type, contacts that don't belong to a group are + invisible to Android application UIs. + + By default, contacts are invisible if none of their raw contacts belongs to a group + (Group membership for a raw contact is indicated by one or more + {@link android.provider.ContactsContract.CommonDataKinds.GroupMembership} rows + in the {@link android.provider.ContactsContract.Data} table). + By setting this flag in the {@link android.provider.ContactsContract.Settings} table row + for an account type and account, you can force contacts without groups to be visible. + One use of this flag is to show contacts from servers that don't use groups. +
    + "1" - For this account and account type, contacts that don't belong to a group are + visible to application UIs. +
    {@link android.provider.ContactsContract.SyncState}(all) + Use this table to store metadata for your sync adapter. + + With this table you can store sync state and other sync-related data persistently on + the device. +
    +

    Contacts Provider Access

    +

    + This section describes guidelines for accessing data from the Contacts Provider, focusing on + the following: +

    + +

    + Making modifications from a sync adapter is also covered in more detail in the section + Contacts Provider Sync Adapters. +

    +

    Querying entities

    +

    + Because the Contacts Provider tables are organized in a hierarchy, it's often useful to + retrieve a row and all of the "child" rows that are linked to it. For example, to display + all the information for a person, you may want to retrieve all the + {@link android.provider.ContactsContract.RawContacts} rows for a single + {@link android.provider.ContactsContract.Contacts} row, or all the + {@link android.provider.ContactsContract.CommonDataKinds.Email} rows for a single + {@link android.provider.ContactsContract.RawContacts} row. To facilitate this, the Contacts + Provider offers entity constructs, which act like database joins between + tables. +

    +

    + An entity is like a table composed of selected columns from a parent table and its child table. + When you query an entity, you supply a projection and search criteria based on the columns + available from the entity. The result is a {@link android.database.Cursor} that contains + contains one row for each child table row that was retrieved. For example, if you query + {@link android.provider.ContactsContract.Contacts.Entity} for a contact name + and all the {@link android.provider.ContactsContract.CommonDataKinds.Email} rows for all the + raw contacts for that name, you get back a {@link android.database.Cursor} containing one row + for each {@link android.provider.ContactsContract.CommonDataKinds.Email} row. +

    +

    + Entities simplify queries. Using an entity, you can retrieve all of the contacts data for a + contact or raw contact at once, instead of having to query the parent table first to get an + ID, and then having to query the child table with that ID. Also, the Contacts Provider processes + a query against an entity in a single transaction, which ensures that the retrieved data is + internally consistent. +

    +

    + Note: An entity usually doesn't contain all the columns of the parent and + child table. If you attempt to work with a column name that isn't in the list of column name + constants for the entity, you'll get an {@link java.lang.Exception}. +

    +

    + The following snippet shows how to retrieve all the raw contact rows for a contact. The snippet + is part of a larger application that has two activities, "main" and "detail". The main activity + shows a list of contact rows; when the user select one, the activity sends its ID to the detail + activity. The detail activity uses the {@link android.provider.ContactsContract.Contacts.Entity} + to display all of the data rows from all of the raw contacts associated with the selected + contact. +

    +

    + This snippet is taken from the "detail" activity: +

    +
    +...
    +    /*
    +     * Appends the entity path to the URI. In the case of the Contacts Provider, the
    +     * expected URI is content://com.google.contacts/#/entity (# is the ID value).
    +     */
    +    mContactUri = Uri.withAppendedPath(
    +            mContactUri,
    +            ContactsContract.Contacts.Entity.CONTENT_DIRECTORY);
    +
    +    // Initializes the loader identified by LOADER_ID.
    +    getLoaderManager().initLoader(
    +            LOADER_ID,  // The identifier of the loader to initialize
    +            null,       // Arguments for the loader (in this case, none)
    +            this);      // The context of the activity
    +
    +    // Creates a new cursor adapter to attach to the list view
    +    mCursorAdapter = new SimpleCursorAdapter(
    +            this,                        // the context of the activity
    +            R.layout.detail_list_item,   // the view item containing the detail widgets
    +            mCursor,                     // the backing cursor
    +            mFromColumns,                // the columns in the cursor that provide the data
    +            mToViews,                    // the views in the view item that display the data
    +            0);                          // flags
    +
    +    // Sets the ListView's backing adapter.
    +    mRawContactList.setAdapter(mCursorAdapter);
    +...
    +@Override
    +public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    +
    +    /*
    +     * Sets the columns to retrieve.
    +     * RAW_CONTACT_ID is included to identify the raw contact associated with the data row.
    +     * DATA1 contains the first column in the data row (usually the most important one).
    +     * MIMETYPE indicates the type of data in the data row.
    +     */
    +    String[] projection =
    +        {
    +            ContactsContract.Contacts.Entity.RAW_CONTACT_ID,
    +            ContactsContract.Contacts.Entity.DATA1,
    +            ContactsContract.Contacts.Entity.MIMETYPE
    +        };
    +
    +    /*
    +     * Sorts the retrieved cursor by raw contact id, to keep all data rows for a single raw
    +     * contact collated together.
    +     */
    +    String sortOrder =
    +            ContactsContract.Contacts.Entity.RAW_CONTACT_ID +
    +            " ASC";
    +
    +    /*
    +     * Returns a new CursorLoader. The arguments are similar to
    +     * ContentResolver.query(), except for the Context argument, which supplies the location of
    +     * the ContentResolver to use.
    +     */
    +    return new CursorLoader(
    +            getApplicationContext(),  // The activity's context
    +            mContactUri,              // The entity content URI for a single contact
    +            projection,               // The columns to retrieve
    +            null,                     // Retrieve all the raw contacts and their data rows.
    +            null,                     //
    +            sortOrder);               // Sort by the raw contact ID.
    +}
    +
    +

    + When the load is finished, {@link android.app.LoaderManager} invokes a callback to + {@link android.app.LoaderManager.LoaderCallbacks#onLoadFinished(Loader, D) + onLoadFinished()}. One of the incoming arguments to this method is a + {@link android.database.Cursor} with the results of the query. In your own app, you can get the + data from this {@link android.database.Cursor} to display it or work with it further. +

    +

    Batch modification

    +

    + Whenever possible, you should insert, update, and delete data in the Contacts Provider in + "batch mode", by creating an {@link java.util.ArrayList} of + {@link android.content.ContentProviderOperation} objects and calling + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()}. Because + the Contacts Provider performs all of the operations in an + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()} in a single + transaction, your modifications will never leave the contacts repository in an inconsistent + state. A batch modification also facilitates inserting a raw contact and its detail data at + the same time. +

    +

    + Note: To modify a single raw contact, consider sending an intent to + the device's contacts application rather than handling the modification in your app. + Doing this is described in more detail in the section + Retrieval and modification with intents. +

    +

    Yield points

    +

    + A batch modification containing a large number of operations can block other processes, + resulting in a bad overall user experience. To organize all the modifications you want to + perform in as few separate lists as possible, and at the same time prevent them from + blocking the system, you should set yield points for one or more operations. + A yield point is a {@link android.content.ContentProviderOperation} object that has its + {@link android.content.ContentProviderOperation#isYieldAllowed()} value set to + true. When the Contacts Provider encounters a yield point, it pauses its work to + let other processes run and closes the current transaction. When the provider starts again, it + continues with the next operation in the {@link java.util.ArrayList} and starts a new + transaction. +

    +

    + Yield points do result in more than one transaction per call to + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()}. Because of + this, you should set a yield point for the last operation for a set of related rows. + For example, you should set a yield point for the last operation in a set that adds a + raw contact rows and its associated data rows, or the last operation for a set of rows related + to a single contact. +

    +

    + Yield points are also a unit of atomic operation. All accesses between two yield points will + either succeed or fail as a single unit. If you don't set any yield points, the smallest + atomic operation is the entire batch of operations. If you do use yield points, you prevent + operations from degrading system performance, while at the same time ensuring that a subset of + operations is atomic. +

    +

    Modification back references

    +

    + When you're inserting a new raw contact row and its associated data rows as a set of + {@link android.content.ContentProviderOperation} objects, you have to link the data rows to + the raw contact row by inserting the raw contact's + {@link android.provider.BaseColumns#_ID} value as the + {@link android.provider.ContactsContract.DataColumns#RAW_CONTACT_ID} value. However, this + value isn't available when you're creating the {@link android.content.ContentProviderOperation} + for the data row, because you haven't yet applied the + {@link android.content.ContentProviderOperation} for the raw contact row. To work around this, + the {@link android.content.ContentProviderOperation.Builder} class has the method + {@link android.content.ContentProviderOperation.Builder#withValueBackReference(String, int) withValueBackReference()}. + This method allows you to insert or modify a column with the + result of a previous operation. +

    +

    + The {@link android.content.ContentProviderOperation.Builder#withValueBackReference(String, int) withValueBackReference()} + method has two arguments: +

    +
    +
    + key +
    +
    + The key of a key-value pair. The value of this argument should be the name of a column + in the table that you're modifying. +
    +
    + previousResult +
    +
    + The 0-based index of a value in the array of + {@link android.content.ContentProviderResult} objects from + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()}. As + the batch operations are applied, the result of each operation is stored in an + intermediate array of results. The previousResult value is the index + of one of these results, which is retrieved and stored with the key + value. This allows you to insert a new raw contact record and get back its + {@link android.provider.BaseColumns#_ID} value, then make a "back reference" to the + value when you add a {@link android.provider.ContactsContract.Data} row. +

    + The entire result array is created when you first call + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()}, + with a size equal to the size of the {@link java.util.ArrayList} of + {@link android.content.ContentProviderOperation} objects you provide. However, all + the elements in the result array are set to null, and if you try + to do a back reference to a result for an operation that hasn't yet been applied, +{@link android.content.ContentProviderOperation.Builder#withValueBackReference(String, int) withValueBackReference()} + throws an {@link java.lang.Exception}. + +

    +
    +
    +

    + The following snippets show how to insert a new raw contact and data in batch. They + includes code that establishes a yield point and uses a back reference. The snippets are an + expanded version of the createContacEntry() method, which is part of the + ContactAdder class in the + + Contact Manager sample application. +

    +

    + The first snippet retrieves contact data from the UI. At this point, the user has already + selected the account for which the new raw contact should be added. +

    +
    +// Creates a contact entry from the current UI values, using the currently-selected account.
    +protected void createContactEntry() {
    +    /*
    +     * Gets values from the UI
    +     */
    +    String name = mContactNameEditText.getText().toString();
    +    String phone = mContactPhoneEditText.getText().toString();
    +    String email = mContactEmailEditText.getText().toString();
    +
    +    int phoneType = mContactPhoneTypes.get(
    +            mContactPhoneTypeSpinner.getSelectedItemPosition());
    +
    +    int emailType = mContactEmailTypes.get(
    +            mContactEmailTypeSpinner.getSelectedItemPosition());
    +
    +

    + The next snippet creates an operation to insert the raw contact row into the + {@link android.provider.ContactsContract.RawContacts} table: +

    +
    +    /*
    +     * Prepares the batch operation for inserting a new raw contact and its data. Even if
    +     * the Contacts Provider does not have any data for this person, you can't add a Contact,
    +     * only a raw contact. The Contacts Provider will then add a Contact automatically.
    +     */
    +
    +     // Creates a new array of ContentProviderOperation objects.
    +    ArrayList<ContentProviderOperation> ops =
    +            new ArrayList<ContentProviderOperation>();
    +
    +    /*
    +     * Creates a new raw contact with its account type (server type) and account name
    +     * (user's account). Remember that the display name is not stored in this row, but in a
    +     * StructuredName data row. No other data is required.
    +     */
    +    ContentProviderOperation.Builder op =
    +            ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
    +            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, mSelectedAccount.getType())
    +            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, mSelectedAccount.getName());
    +
    +    // Builds the operation and adds it to the array of operations
    +    ops.add(op.build());
    +
    +

    + Next, the code creates data rows for the display name, phone, and email rows. +

    +

    + Each operation builder object uses + {@link android.content.ContentProviderOperation.Builder#withValueBackReference(String, int) withValueBackReference()} + to get the + {@link android.provider.ContactsContract.DataColumns#RAW_CONTACT_ID}. The reference points + back to the {@link android.content.ContentProviderResult} object from the first operation, + which adds the raw contact row and returns its new {@link android.provider.BaseColumns#_ID} + value. As a result, each data row is automatically linked by its + {@link android.provider.ContactsContract.DataColumns#RAW_CONTACT_ID} + to the new {@link android.provider.ContactsContract.RawContacts} row to which it belongs. +

    +

    + The {@link android.content.ContentProviderOperation.Builder} object that adds the email row is + flagged with {@link android.content.ContentProviderOperation.Builder#withYieldAllowed(boolean) + withYieldAllowed()}, which sets a yield point: +

    +
    +    // Creates the display name for the new raw contact, as a StructuredName data row.
    +    op =
    +            ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
    +            /*
    +             * withValueBackReference sets the value of the first argument to the value of
    +             * the ContentProviderResult indexed by the second argument. In this particular
    +             * call, the raw contact ID column of the StructuredName data row is set to the
    +             * value of the result returned by the first operation, which is the one that
    +             * actually adds the raw contact row.
    +             */
    +            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
    +
    +            // Sets the data row's MIME type to StructuredName
    +            .withValue(ContactsContract.Data.MIMETYPE,
    +                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
    +
    +            // Sets the data row's display name to the name in the UI.
    +            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
    +
    +    // Builds the operation and adds it to the array of operations
    +    ops.add(op.build());
    +
    +    // Inserts the specified phone number and type as a Phone data row
    +    op =
    +            ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
    +            /*
    +             * Sets the value of the raw contact id column to the new raw contact ID returned
    +             * by the first operation in the batch.
    +             */
    +            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
    +
    +            // Sets the data row's MIME type to Phone
    +            .withValue(ContactsContract.Data.MIMETYPE,
    +                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
    +
    +            // Sets the phone number and type
    +            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
    +            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType);
    +
    +    // Builds the operation and adds it to the array of operations
    +    ops.add(op.build());
    +
    +    // Inserts the specified email and type as a Phone data row
    +    op =
    +            ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
    +            /*
    +             * Sets the value of the raw contact id column to the new raw contact ID returned
    +             * by the first operation in the batch.
    +             */
    +            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
    +
    +            // Sets the data row's MIME type to Email
    +            .withValue(ContactsContract.Data.MIMETYPE,
    +                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
    +
    +            // Sets the email address and type
    +            .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email)
    +            .withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType);
    +
    +    /*
    +     * Demonstrates a yield point. At the end of this insert, the batch operation's thread
    +     * will yield priority to other threads. Use after every set of operations that affect a
    +     * single contact, to avoid degrading performance.
    +     */
    +    op.withYieldAllowed(true);
    +
    +    // Builds the operation and adds it to the array of operations
    +    ops.add(op.build());
    +
    +

    + The last snippet shows the call to + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()} that + inserts the new raw contact and data rows. +

    +
    +    // Ask the Contacts Provider to create a new contact
    +    Log.d(TAG,"Selected account: " + mSelectedAccount.getName() + " (" +
    +            mSelectedAccount.getType() + ")");
    +    Log.d(TAG,"Creating contact: " + name);
    +
    +    /*
    +     * Applies the array of ContentProviderOperation objects in batch. The results are
    +     * discarded.
    +     */
    +    try {
    +
    +            getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    +    } catch (Exception e) {
    +
    +            // Display a warning
    +            Context ctx = getApplicationContext();
    +
    +            CharSequence txt = getString(R.string.contactCreationFailure);
    +            int duration = Toast.LENGTH_SHORT;
    +            Toast toast = Toast.makeText(ctx, txt, duration);
    +            toast.show();
    +
    +            // Log exception
    +            Log.e(TAG, "Exception encountered while inserting contact: " + e);
    +    }
    +}
    +
    +

    + Batch operations also allow you to implement optimistic concurrency control, + a method of applying modification transactions without having to lock the underlying repository. + To use this method, you apply the transaction and then check for other modifications that + may have been made at the same time. If you find an inconsistent modification has occurred, you + roll back your transaction and retry it. +

    +

    + Optimistic concurrency control is useful for a mobile device, where there's only one user at + a time, and simultaneous accesses to a data repository are rare. Because locking isn't used, + no time is wasted on setting locks or waiting for other transactions to release their locks. +

    +

    + To use optimistic concurrency control while updating a single + {@link android.provider.ContactsContract.RawContacts} row, follow these steps: +

    +
      +
    1. + Retrieve the raw contact's {@link android.provider.ContactsContract.SyncColumns#VERSION} + column along with the other data you retrieve. +
    2. +
    3. + Create a {@link android.content.ContentProviderOperation.Builder} object suitable for + enforcing a constraint, using the method + {@link android.content.ContentProviderOperation#newAssertQuery(Uri)}. For the content URI, + use {@link android.provider.ContactsContract.RawContacts#CONTENT_URI + RawContacts.CONTENT_URI} + with the raw contact's {@link android.provider.BaseColumns#_ID} appended to it. +
    4. +
    5. + For the {@link android.content.ContentProviderOperation.Builder} object, call + {@link android.content.ContentProviderOperation.Builder#withValue(String, Object) + withValue()} to compare the {@link android.provider.ContactsContract.SyncColumns#VERSION} + column to the version number you just retrieved. +
    6. +
    7. + For the same {@link android.content.ContentProviderOperation.Builder}, call + {@link android.content.ContentProviderOperation.Builder#withExpectedCount(int) + withExpectedCount()} to ensure that only one row is tested by this assertion. +
    8. +
    9. + Call {@link android.content.ContentProviderOperation.Builder#build()} to create the + {@link android.content.ContentProviderOperation} object, then add this object as the + first object in the {@link java.util.ArrayList} that you pass to + {@link android.content.ContentResolver#applyBatch(String, ArrayList) applyBatch()}. +
    10. +
    11. + Apply the batch transaction. +
    12. +
    +

    + If the raw contact row is updated by another operation between the time you read the row and + the time you attempt to modify it, the "assert" {@link android.content.ContentProviderOperation} + will fail, and the entire batch of operations will be backed out. You can then choose to retry + the batch or take some other action. +

    +

    + The following snippet demonstrates how to create an "assert" + {@link android.content.ContentProviderOperation} after querying for a single raw contact using + a {@link android.content.CursorLoader}: +

    +
    +/*
    + * The application uses CursorLoader to query the raw contacts table. The system calls this method
    + * when the load is finished.
    + */
    +public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    +
    +    // Gets the raw contact's _ID and VERSION values
    +    mRawContactID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
    +    mVersion = cursor.getInt(cursor.getColumnIndex(SyncColumns.VERSION));
    +}
    +
    +...
    +
    +// Sets up a Uri for the assert operation
    +Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, mRawContactID);
    +
    +// Creates a builder for the assert operation
    +ContentProviderOperation.Builder assertOp = ContentProviderOperation.netAssertQuery(rawContactUri);
    +
    +// Adds the assertions to the assert operation: checks the version and count of rows tested
    +assertOp.withValue(SyncColumns.VERSION, mVersion);
    +assertOp.withExpectedCount(1);
    +
    +// Creates an ArrayList to hold the ContentProviderOperation objects
    +ArrayList ops = new ArrayList<ContentProviderOperationg>;
    +
    +ops.add(assertOp.build());
    +
    +// You would add the rest of your batch operations to "ops" here
    +
    +...
    +
    +// Applies the batch. If the assert fails, an Exception is thrown
    +try
    +    {
    +        ContentProviderResult[] results =
    +                getContentResolver().applyBatch(AUTHORITY, ops);
    +
    +    } catch (OperationApplicationException e) {
    +
    +        // Actions you want to take if the assert operation fails go here
    +    }
    +
    +

    Retrieval and modification with intents

    +

    + Sending an intent to the device's contacts application allows you to access the Contacts + Provider indirectly. The intent starts the device's contacts application UI, in which users can + do contacts-related work. With this type of access, users can: +

    +

    + If the user is inserting or updating data, you can collect the data first and send it as + part of the intent. +

    +

    + When you use intents to access the Contacts Provider via the device's contacts application, you + don't have to write your own UI or code for accessing the provider. You also don't have to + request permission to read or write to the provider. The device's contacts application can + delegate read permission for a contact to you, and because you're making modifications to the + provider through another application, you don't have to have write permissions. +

    +

    + The general process of sending an intent to access a provider is described in detail in the + + Content Provider Basics guide in the section "Data access via intents." The action, + MIME type, and data values you use for the available tasks are summarized in Table 4, while the + extras values you can use with + {@link android.content.Intent#putExtra(String, String) putExtra()} are listed in the + reference documentation for {@link android.provider.ContactsContract.Intents.Insert}: +

    +

    + Table 4. Contacts Provider Intents. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TaskActionDataMIME typeNotes
    Pick a contact from a list{@link android.content.Intent#ACTION_PICK} + One of: +
      +
    • +{@link android.provider.ContactsContract.Contacts#CONTENT_URI Contacts.CONTENT_URI}, + which displays a list of contacts. +
    • +
    • +{@link android.provider.ContactsContract.CommonDataKinds.Phone#CONTENT_URI Phone.CONTENT_URI}, + which displays a list of phone numbers for a raw contact. +
    • +
    • +{@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#CONTENT_URI +StructuredPostal.CONTENT_URI}, + which displays a list of postal addresses for a raw contact. +
    • +
    • +{@link android.provider.ContactsContract.CommonDataKinds.Email#CONTENT_URI Email.CONTENT_URI}, + which displays a list of email addresses for a raw contact. +
    • +
    +
    + Not used + + Displays a list of raw contacts or a list of data from a raw contact, depending on the + content URI type you supply. +

    + Call + {@link android.app.Activity#startActivityForResult(Intent, int) startActivityForResult()}, + which returns the content URI of the selected row. The form of the URI is the + table's content URI with the row's LOOKUP_ID appended to it. + The device's contacts app delegates read and write permissions to this content URI + for the life of your activity. See the + + Content Provider Basics guide for more details. +

    +
    Insert a new raw contact{@link android.provider.ContactsContract.Intents.Insert#ACTION Insert.ACTION}N/A + {@link android.provider.ContactsContract.RawContacts#CONTENT_TYPE + RawContacts.CONTENT_TYPE}, MIME type for a set of raw contacts. + + Displays the device's contacts application's Add Contact screen. The + extras values you add to the intent are displayed. If sent with + {@link android.app.Activity#startActivityForResult(Intent, int) startActivityForResult()}, + the content URI of the newly-added raw contact is passed back to your activity's + {@link android.app.Activity#onActivityResult(int, int, Intent) onActivityResult()} + callback method in the {@link android.content.Intent} argument, in the + "data" field. To get the value, call {@link android.content.Intent#getData()}. +
    Edit a contact{@link android.content.Intent#ACTION_EDIT} + {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI} for + the contact. The editor activity will allow the user to edit any of the data associated + with this contact. + + {@link android.provider.ContactsContract.Contacts#CONTENT_ITEM_TYPE + Contacts.CONTENT_ITEM_TYPE}, a single contact. + Displays the Edit Contact screen in the contacts application. The extras values you add + to the intent are displayed. When the user clicks Done to save the + edits, your activity returns to the foreground. +
    Display a picker that can also add data.{@link android.content.Intent#ACTION_INSERT_OR_EDIT} + N/A + + {@link android.provider.ContactsContract.Contacts#CONTENT_ITEM_TYPE} + + This intent always displays the contacts app's picker screen. The user can either + pick a contact to edit, or add a new contact. Either the edit or the add screen + appears, depending on the user's choice, and the extras data you pass in the intent + is displayed. If your app displays contact data such as an email or phone number, use + this intent to allow the user to add the data to an existing contact. + contact, +

    + Note: There's no need to send a name value in this intent's extras, + because the user always picks an existing name or adds a new one. Moreover, + if you send a name, and the user chooses to do an edit, the contacts app will + display the name you send, overwriting the previous value. If the user doesn't + notice this and saves the edit, the old value is lost. +

    +
    +

    + The device's contacts app doesn't allow you to delete a raw contact or any of its data with an + intent. Instead, to delete a raw contact, use + {@link android.content.ContentResolver#delete(Uri, String, String[]) ContentResolver.delete()} + or {@link android.content.ContentProviderOperation#newDelete(Uri) + ContentProviderOperation.newDelete()}. +

    +

    + The following snippet shows how to construct and send an intent that inserts a new raw + contact and data: +

    +
    +// Gets values from the UI
    +String name = mContactNameEditText.getText().toString();
    +String phone = mContactPhoneEditText.getText().toString();
    +String email = mContactEmailEditText.getText().toString();
    +
    +String company = mCompanyName.getText().toString();
    +String jobtitle = mJobTitle.getText().toString();
    +
    +// Creates a new intent for sending to the device's contacts application
    +Intent insertIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
    +
    +// Sets the MIME type to the one expected by the insertion activity
    +insertIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
    +
    +// Sets the new contact name
    +insertIntent.putExtra(ContactsContract.Intents.Insert.NAME, name);
    +
    +// Sets the new company and job title
    +insertIntent.putExtra(ContactsContract.Intents.Insert.COMPANY, company);
    +insertIntent.putExtra(ContactsContract.Intents.Insert.JOB_TITLE, jobtitle);
    +
    +/*
    + * Demonstrates adding data rows as an array list associated with the DATA key
    + */
    +
    +// Defines an array list to contain the ContentValues objects for each row
    +ArrayList<ContentValues> contactData = new ArrayList<ContentValues>();
    +
    +
    +/*
    + * Defines the raw contact row
    + */
    +
    +// Sets up the row as a ContentValues object
    +ContentValues rawContactRow = new ContentValues();
    +
    +// Adds the account type and name to the row
    +rawContactRow.put(ContactsContract.RawContacts.ACCOUNT_TYPE, mSelectedAccount.getType());
    +rawContactRow.put(ContactsContract.RawContacts.ACCOUNT_NAME, mSelectedAccount.getName());
    +
    +// Adds the row to the array
    +contactData.add(rawContactRow);
    +
    +/*
    + * Sets up the phone number data row
    + */
    +
    +// Sets up the row as a ContentValues object
    +ContentValues phoneRow = new ContentValues();
    +
    +// Specifies the MIME type for this data row (all data rows must be marked by their type)
    +phoneRow.put(
    +        ContactsContract.Data.MIMETYPE,
    +        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
    +);
    +
    +// Adds the phone number and its type to the row
    +phoneRow.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
    +
    +// Adds the row to the array
    +contactData.add(phoneRow);
    +
    +/*
    + * Sets up the email data row
    + */
    +
    +// Sets up the row as a ContentValues object
    +ContentValues emailRow = new ContentValues();
    +
    +// Specifies the MIME type for this data row (all data rows must be marked by their type)
    +emailRow.put(
    +        ContactsContract.Data.MIMETYPE,
    +        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
    +);
    +
    +// Adds the email address and its type to the row
    +emailRow.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
    +
    +// Adds the row to the array
    +contactData.add(emailRow);
    +
    +/*
    + * Adds the array to the intent's extras. It must be a parcelable object in order to
    + * travel between processes. The device's contacts app expects its key to be
    + * Intents.Insert.DATA
    + */
    +insertIntent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, contactData);
    +
    +// Send out the intent to start the device's contacts app in its add contact activity.
    +startActivity(insertIntent);
    +
    +

    Data integrity

    +

    + Because the contacts repository contains important and sensitive data that users expect to be + correct and up-to-date, the Contacts Provider has well-defined rules for data integrity. It's + your responsibility to conform to these rules when you modify contacts data. The important + rules are listed here: +

    +
    +
    + Always add a {@link android.provider.ContactsContract.CommonDataKinds.StructuredName} row + for every {@link android.provider.ContactsContract.RawContacts} row you add. +
    +
    + A {@link android.provider.ContactsContract.RawContacts} row without a + {@link android.provider.ContactsContract.CommonDataKinds.StructuredName} row in the + {@link android.provider.ContactsContract.Data} table may cause problems during + aggregation. +
    +
    + Always link new {@link android.provider.ContactsContract.Data} rows to their parent + {@link android.provider.ContactsContract.RawContacts} row. +
    +
    + A {@link android.provider.ContactsContract.Data} row that isn't linked to a + {@link android.provider.ContactsContract.RawContacts} won't be visible in the device's + contacts application, and it might cause problems with sync adapters. +
    +
    + Change data only for those raw contacts that you own. +
    +
    + Remember that the Contacts Provider is usually managing data from several different + account types/online services. You need to ensure that your application only modifies + or deletes data for rows that belong to you, and that it only inserts data with an + account type and name that you control. +
    +
    + Always use the constants defined in {@link android.provider.ContactsContract} and its + subclasses for authorities, content URIs, URI paths, column names, MIME types, and + {@link android.provider.ContactsContract.CommonDataKinds.CommonColumns#TYPE} values. +
    +
    + Using these constants helps you to avoid errors. You'll also be notified with compiler + warnings if any of the constants is deprecated. +
    +
    +

    Custom data rows

    +

    + By creating and using your own custom MIME types, you can insert, edit, delete, and retrieve + your own data rows in the {@link android.provider.ContactsContract.Data} table. Your rows + are limited to using the column defined in + {@link android.provider.ContactsContract.DataColumns}, although you can map your own + type-specific column names to the default column names. In the device's contacts application, + the data for your rows is displayed but can't be edited or deleted, and users can't add + additional data. To allow users to modify your custom data rows, you must provide an editor + activity in your own application. +

    +

    + To display your custom data, provide a contacts.xml file containing a + <ContactsAccountType> element and one or more of its + <ContactsDataKind> child elements. This is described in more detail in the + section <ContactsDataKind> element. +

    +

    + To learn more about custom MIME types, read the + + Creating a Content Provider guide. +

    +

    Contacts Provider Sync Adapters

    +

    + The Contacts Provider is specifically designed for handling synchronization + of contacts data between a device and an online service. This allows users to download + existing data to a new device and upload existing data to a new account. + Synchronization also ensures that users have the latest data at hand, regardless + of the source of additions and changes. Another advantage of synchronization is that it makes + contacts data available even when the device is not connected to the network. +

    +

    + Although you can implement synchronization in a variety of ways, the Android system provides + a plug-in synchronization framework that automates the following tasks: +

    +

    + To use this framework, you supply a sync adapter plug-in. Each sync adapter is unique to a + service and content provider, but can handle multiple account names for the same service. The + framework also allows multiple sync adapters for the same service and provider. +

    +

    Sync adapter classes and files

    +

    + You implement a sync adapter as a subclass of + {@link android.content.AbstractThreadedSyncAdapter} and install it as part of an Android + application. The system learns about the sync adapter from elements in your application + manifest, and from a special XML file pointed to by the manifest. The XML file defines the + account type for the online service and the authority for the content provider, which together + uniquely identify the adapter. The sync adapter does not become active until the user adds an + account for the sync adapter's account type and enables synchronization for the content + provider the sync adapter syncs with. At that point, the system starts managing the adapter, + calling it as necessary to synchronize between the content provider and the server. +

    +

    + Note: Using an account type as part of the sync adapter's identification allows + the system to detect and group together sync adapters that access different services from the + same organization. For example, sync adapters for Google online services all have the same + account type com.google. When users add a Google account to their devices, all + of the installed sync adapters for Google services are listed together; each sync adapter + listed syncs with a different content provider on the device. +

    +

    + Because most services require users to verify their identity before accessing + data, the Android system offers an authentication framework that is similar to, and often + used in conjunction with, the sync adapter framework. The authentication framework uses + plug-in authenticators that are subclasses of + {@link android.accounts.AbstractAccountAuthenticator}. An authenticator verifies + the user's identity in the following steps: +

      +
    1. + Collects the user's name, password or similar information (the user's + credentials). +
    2. +
    3. + Sends the credentials to the service +
    4. +
    5. + Examines the service's reply. +
    6. +
    +

    + If the service accepts the credentials, the authenticator can + store the credentials for later use. Because of the plug-in authenticator framework, the + {@link android.accounts.AccountManager} can provide access to any authtokens an authenticator + supports and chooses to expose, such as OAuth2 authtokens. +

    +

    + Although authentication is not required, most contacts services use it. + However, you're not required to use the Android authentication framework to do authentication. +

    +

    Sync adapter implementation

    +

    + To implement a sync adapter for the Contacts Provider, you start by creating an + Android application that contains the following: +

    +
    +
    + A {@link android.app.Service} component that responds to requests from the system to + bind to the sync adapter. +
    +
    + When the system wants to run a synchronization, it calls the service's + {@link android.app.Service#onBind(Intent) onBind()} method to get an + {@link android.os.IBinder} for the sync adapter. This allows the system to do + cross-process calls to the adapter's methods. +

    + In the + Sample Sync Adapter sample app, the class name of this service is + com.example.android.samplesync.syncadapter.SyncService. +

    +
    +
    + The actual sync adapter, implemented as a concrete subclass of + {@link android.content.AbstractThreadedSyncAdapter}. +
    +
    + This class does the work of downloading data from the server, uploading data from the + device, and resolving conflicts. The main work of the adapter is + done in the method {@link android.content.AbstractThreadedSyncAdapter#onPerformSync( + Account, Bundle, String, ContentProviderClient, SyncResult) + onPerformSync()}. This class must be instantiated as a singleton. +

    + In the + Sample Sync Adapter sample app, the sync adapter is defined in the class + com.example.android.samplesync.syncadapter.SyncAdapter. +

    +
    +
    + A subclass of {@link android.app.Application}. +
    +
    + This class acts as a factory for the sync adapter singleton. Use the + {@link android.app.Application#onCreate()} method to instantiate the sync adapter, and + provide a static "getter" method to return the singleton to the + {@link android.app.Service#onBind(Intent) onBind()} method of the sync adapter's + service. +
    +
    + Optional: A {@link android.app.Service} component that responds to + requests from the system for user authentication. +
    +
    + {@link android.accounts.AccountManager} starts this service to begin the authentication + process. The service's {@link android.app.Service#onCreate()} method instantiates an + authenticator object. When the system wants to authenticate a user account for the + application's sync adapter, it calls the service's + {@link android.app.Service#onBind(Intent) onBind()} method to get an + {@link android.os.IBinder} for the authenticator. This allows the system to do + cross-process calls to the authenticator's methods.. +

    + In the + Sample Sync Adapter sample app, the class name of this service is + com.example.android.samplesync.authenticator.AuthenticationService. +

    +
    +
    + Optional: A concrete subclass of + {@link android.accounts.AbstractAccountAuthenticator} that handles requests for + authentication. +
    +
    + This class provides methods that the {@link android.accounts.AccountManager} invokes + to authenticate the user's credentials with the server. The details of the + authentication process vary widely, based on the server technology in use. You should + refer to the documentation for your server software to learn more about authentication. +

    + In the + Sample Sync Adapter sample app, the authenticator is defined in the class + com.example.android.samplesync.authenticator.Authenticator. +

    +
    +
    + XML files that define the sync adapter and authenticator to the system. +
    +
    + The sync adapter and authenticator service components described previously are + defined in +<service> + elements in the application manifest. These elements + contain +<meta-data> +child elements that provide specific data to the + system: +
      +
    • + The +<meta-data> + element for the sync adapter service points to the + XML file res/xml/syncadapter.xml. In turn, this file specifies + a URI for the web service that will be synchronized with the Contacts Provider, + and an account type for the web service. +
    • +
    • + Optional: The +<meta-data> + element for the authenticator points to the XML file + res/xml/authenticator.xml. In turn, this file specifies the + account type that this authenticator supports, as well as UI resources that + appear during the authentication process. The account type specified in this + element must be the same as the account type specified for the sync + adapter. +
    • +
    +
    +
    +

    Social Stream Data

    +

    + The {@link android.provider.ContactsContract.StreamItems} and + {@link android.provider.ContactsContract.StreamItemPhotos} tables + manage incoming data from social networks. You can write a sync adapter that adds stream data + from your own network to these tables, or you can read stream data from these tables and + display it in your own application, or both. With these features, your social networking + services and applications can be integrated into Android's social networking experience. +

    +

    Social stream text

    +

    + Stream items are always associated with a raw contact. The + {@link android.provider.ContactsContract.StreamItemsColumns#RAW_CONTACT_ID} links to the + _ID value for the raw contact. The account type and account name of the raw + contact are also stored in the stream item row. +

    +

    + Store the data from your stream in the following columns: +

    +
    +
    + {@link android.provider.ContactsContract.StreamItemsColumns#ACCOUNT_TYPE} +
    +
    + Required. The user's account type for the raw contact associated with this + stream item. Remember to set this value when you insert a stream item. +
    +
    + {@link android.provider.ContactsContract.StreamItemsColumns#ACCOUNT_NAME} +
    +
    + Required. The user's account name for the raw contact associated with this + stream item. Remember to set this value when you insert a stream item. +
    +
    + Identifier columns +
    +
    + Required. You must insert the following identifier columns when you + insert a stream item: +
      +
    • + {@link android.provider.ContactsContract.StreamItemsColumns#CONTACT_ID}: The + {@link android.provider.BaseColumns#_ID} value of the contact that this stream + item is associated with. +
    • +
    • + {@link android.provider.ContactsContract.StreamItemsColumns#CONTACT_LOOKUP_KEY}: The + {@link android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY} value of the + contact this stream item is associated with. +
    • +
    • + {@link android.provider.ContactsContract.StreamItemsColumns#RAW_CONTACT_ID}: The + {@link android.provider.BaseColumns#_ID} value of the raw contact that this stream + item is associated with. +
    • +
    +
    +
    + {@link android.provider.ContactsContract.StreamItemsColumns#COMMENTS} +
    +
    + Optional. Stores summary information that you can display at the beginning of a stream item. +
    +
    + {@link android.provider.ContactsContract.StreamItemsColumns#TEXT} +
    +
    + The text of the stream item, either the content that was posted by the source of the item, + or a description of some action that generated the stream item. This column can contain + any formatting and embedded resource images that can be rendered by + {@link android.text.Html#fromHtml(String) fromHtml()}. The provider may truncate or + ellipsize long content, but it will try to avoid breaking tags. +
    +
    + {@link android.provider.ContactsContract.StreamItemsColumns#TIMESTAMP} +
    +
    + A text string containing the time the stream item was inserted or updated, in the form + of milliseconds since epoch. Applications that insert or update stream items are + responsible for maintaining this column; it is not automatically maintained by the + Contacts Provider. +
    +
    +

    + To display identifying information for your stream items, use the + {@link android.provider.ContactsContract.StreamItemsColumns#RES_ICON}, + {@link android.provider.ContactsContract.StreamItemsColumns#RES_LABEL}, and + {@link android.provider.ContactsContract.StreamItemsColumns#RES_PACKAGE} to link to resources + in your application. +

    +

    + The {@link android.provider.ContactsContract.StreamItems} table also contains the columns + {@link android.provider.ContactsContract.StreamItemsColumns#SYNC1} through + {@link android.provider.ContactsContract.StreamItemsColumns#SYNC4} for the exclusive use of + sync adapters. +

    +

    Social stream photos

    +

    + The {@link android.provider.ContactsContract.StreamItemPhotos} table stores photos associated + with a stream item. The table's + {@link android.provider.ContactsContract.StreamItemPhotosColumns#STREAM_ITEM_ID} column + links to values in the {@link android.provider.BaseColumns#_ID} column of + {@link android.provider.ContactsContract.StreamItems} table. Photo references are stored in the + table in these columns: +

    +
    +
    + {@link android.provider.ContactsContract.StreamItemPhotos#PHOTO} column (a BLOB). +
    +
    + A binary representation of the photo, resized by the provider for storage and display. + This column is available for backwards compatibility with previous versions of the Contacts + Provider that used it for storing photos. However, in the current version + you should not use this column to store photos. Instead, use + either {@link android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_FILE_ID} or + {@link android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_URI} (both of + which are described in the following points) to store photos in a file. This column now + contains a thumbnail of the photo, which is available for reading. +
    +
    + {@link android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_FILE_ID} +
    +
    + A numeric identifier of a photo for a raw contact. Append this value to the constant + {@link android.provider.ContactsContract.DisplayPhoto#CONTENT_URI DisplayPhoto.CONTENT_URI} + to get a content URI pointing to a single photo file, and then call + {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String) + openAssetFileDescriptor()} to get a handle to the photo file. +
    +
    + {@link android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_URI} +
    +
    + A content URI pointing directly to the photo file for the photo represented by this row. + Call {@link android.content.ContentResolver#openAssetFileDescriptor(Uri, String) + openAssetFileDescriptor()} with this URI to get a handle to the photo file. +
    +
    +

    Using the social stream tables

    +

    + These tables work the same as the other main tables in the Contacts Provider, except that: +

    + + +

    + The class {@link android.provider.ContactsContract.StreamItems.StreamItemPhotos} defines a + sub-table of {@link android.provider.ContactsContract.StreamItemPhotos} containing the photo + rows for a single stream item. +

    +

    Social stream interactions

    +

    + The social stream data managed by the Contacts Provider, in conjunction with the + device's contacts application, offers a powerful way to connect your social networking system + with existing contacts. The following features are available: +

    + +

    + Regular synchronization of stream items with the Contacts Provider is the same as + other synchronizations. To learn more about synchronization, see the section + Contacts Provider Sync Adapters. Registering notifications and + inviting contacts are covered in the next two sections. +

    +

    Registering to handle social networking views

    +

    + To register your sync adapter to receive notifications when the user views a contact that's + managed by your sync adapter: +

    +
      +
    1. + Create a file named contacts.xml in your project's res/xml/ + directory. If you already have this file, you can skip this step. +
    2. +
    3. + In this file, add the element +<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android">. + If this element already exists, you can skip this step. +
    4. +
    5. + To register a service that is notified when the user opens a contact's detail page in + the device's contacts application, add the attribute + viewContactNotifyService="serviceclass" to the element, where + serviceclass is the fully-qualified classname of the service + that should receive the intent from the device's contacts application. For the notifier + service, use a class that extends {@link android.app.IntentService}, to allow the service to + receive intents. The data in the incoming intent contains the content URI of the raw + contact the user clicked. From the notifier service, you can bind to and then call your + sync adapter to update the data for the raw contact. +
    6. +
    +

    + To register an activity to be called when the user clicks on a stream item or photo or both: +

    +
      +
    1. + Create a file named contacts.xml in your project's res/xml/ + directory. If you already have this file, you can skip this step. +
    2. +
    3. + In this file, add the element +<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android">. + If this element already exists, you can skip this step. +
    4. +
    5. + To register one of your activities to handle the user clicking on a stream item in the + device's contacts application, add the attribute + viewStreamItemActivity="activityclass" to the element, where + activityclass is the fully-qualified classname of the activity + that should receive the intent from the device's contacts application. +
    6. +
    7. + To register one of your activities to handle the user clicking on a stream photo in the + device's contacts application, add the attribute + viewStreamItemPhotoActivity="activityclass" to the element, where + activityclass is the fully-qualified classname of the activity + that should receive the intent from the device's contacts application. +
    8. +
    +

    + The <ContactsAccountType> element is described in more detail in the + section <ContactsAccountType> element. +

    +

    + The incoming intent contains the content URI of the item or photo that the user clicked. + To have separate activities for text items and for photos, use both attributes in the same file. +

    +

    Interacting with your social networking service

    +

    + Users don't have to leave the device's contacts application to invite a contact to your social + networking site. Instead, you can have the device's contacts app send an intent for inviting the + contact to one of your activities. To set this up: +

    +
      +
    1. + Create a file named contacts.xml in your project's res/xml/ + directory. If you already have this file, you can skip this step. +
    2. +
    3. + In this file, add the element +<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android">. + If this element already exists, you can skip this step. +
    4. +
    5. + Add the following attributes: +
        +
      • inviteContactActivity="activityclass"
      • +
      • + inviteContactActionLabel="@string/invite_action_label" +
      • +
      + The activityclass value is the fully-qualified classname of the + activity that should receive the intent. The invite_action_label + value is a text string that's displayed in the Add Connection menu in the + device's contacts application. +
    6. +
    +

    + Note: ContactsSource is a deprecated tag name for + ContactsAccountType. +

    +

    contacts.xml reference

    +

    + The file contacts.xml contains XML elements that control the interaction of your + sync adapter and application with the contacts application and the Contacts Provider. These + elements are described in the following sections. +

    +

    <ContactsAccountType> element

    +

    + The <ContactsAccountType> element controls the interaction of your + application with the contacts application. It has the following syntax: +

    +
    +<ContactsAccountType
    +        xmlns:android="http://schemas.android.com/apk/res/android"
    +        inviteContactActivity="activity_name"
    +        inviteContactActionLabel="invite_command_text"
    +        viewContactNotifyService="view_notify_service"
    +        viewGroupActivity="group_view_activity"
    +        viewGroupActionLabel="group_action_text"
    +        viewStreamItemActivity="viewstream_activity_name"
    +        viewStreamItemPhotoActivity="viewphotostream_activity_name">
    +
    +

    + contained in: +

    +

    + res/xml/contacts.xml +

    +

    + can contain: +

    +

    + <ContactsDataKind> +

    +

    + Description: +

    +

    + Declares Android components and UI labels that allow users to invite one of their contacts to + a social network, notify users when one of their social networking streams is updated, and + so forth. +

    +

    + Notice that the attribute prefix android: is not necessary for the attributes + of <ContactsAccountType>. +

    +

    + Attributes: +

    +
    +
    {@code inviteContactActivity}
    +
    + The fully-qualified class name of the activity in your application that you want to + activate when the user selects Add connection from the device's + contacts application. +
    +
    {@code inviteContactActionLabel}
    +
    + A text string that is displayed for the activity specified in + {@code inviteContactActivity}, in the Add connection menu. + For example, you can use the string "Follow in my network". You can use a string resource + identifier for this label. +
    +
    {@code viewContactNotifyService}
    +
    + The fully-qualified class name of a service in your application that should receive + notifications when the user views a contact. This notification is sent by the device's + contacts application; it allows your application to postpone data-intensive operations + until they're needed. For example, your application can respond to this notification + by reading in and displaying the contact's high-resolution photo and most recent + social stream items. This feature is described in more detail in the section + Social stream interactions. You can see an + example of the notification service in the NotifierService.java file in the + SampleSyncAdapter + sample app. +
    +
    {@code viewGroupActivity}
    +
    + The fully-qualified class name of an activity in your application that can display + group information. When the user clicks the group label in the device's contacts + application, the UI for this activity is displayed. +
    +
    {@code viewGroupActionLabel}
    +
    + The label that the contacts application displays for a UI control that allows + the user to look at groups in your application. +

    + For example, if you install the Google+ application on your device and you sync + Google+ with the contacts application, you'll see Google+ circles listed as groups + in your contacts application's Groups tab. If you click on a + Google+ circle, you'll see people in that circle listed as a "group". At the top of + the display, you'll see a Google+ icon; if you click it, control switches to the + Google+ app. The contacts application does this with the + {@code viewGroupActivity}, using the Google+ icon as the value of + {@code viewGroupActionLabel}. +

    +

    + A string resource identifier is allowed for this attribute. +

    +
    +
    {@code viewStreamItemActivity}
    +
    + The fully-qualified class name of an activity in your application that the device's + contacts application launches when the user clicks a stream item for a raw contact. +
    +
    {@code viewStreamItemPhotoActivity}
    +
    + The fully-qualified class name of an activity in your application that the device's + contacts application launches when the user clicks a photo in the stream item + for a raw contact. +
    +
    +

    <ContactsDataKind> element

    +

    + The <ContactsDataKind> element controls the display of your application's + custom data rows in the contacts application's UI. It has the following syntax: +

    +
    +<ContactsDataKind
    +        android:mimeType="MIMEtype"
    +        android:icon="icon_resources"
    +        android:summaryColumn="column_name"
    +        android:detailColumn="column_name">
    +
    +

    + contained in: +

    +<ContactsAccountType> +

    + Description: +

    +

    + Use this element to have the contacts application display the contents of a custom data row as + part of the details of a raw contact. Each <ContactsDataKind> child element + of <ContactsAccountType> represents a type of custom data row that your sync + adapter adds to the {@link android.provider.ContactsContract.Data} table. Add one + <ContactsDataKind> element for each custom MIME type you use. You don't have + to add the element if you have a custom data row for which you don't want to display data. +

    +

    + Attributes: +

    +
    +
    {@code android:mimeType}
    +
    + The custom MIME type you've defined for one of your custom data row types in the + {@link android.provider.ContactsContract.Data} table. For example, the value + vnd.android.cursor.item/vnd.example.locationstatus could be a custom + MIME type for a data row that records a contact's last known location. +
    +
    {@code android:icon}
    +
    + An Android + drawable resource + that the contacts application displays next to your data. Use this to indicate to the + user that the data comes from your service. +
    +
    {@code android:summaryColumn}
    +
    + The column name for the first of two values retrieved from the data row. The + value is displayed as the first line of the entry for this data row. The first line is + intended to be used as a summary of the data, but that is optional. See also + android:detailColumn. +
    +
    {@code android:detailColumn}
    +
    + The column name for the second of two values retrieved from the data row. The value is + displayed as the second line of the entry for this data row. See also + {@code android:summaryColumn}. +
    +
    +

    Additional Contacts Provider Features

    +

    + Besides the main features described in previous sections, the Contacts Provider offers + these useful features for working with contacts data: +

    + +

    Contact groups

    +

    + The Contacts Provider can optionally label collections of related contacts with + group data. If the server associated with a user account + wants to maintain groups, the sync adapter for the account's account type should transfer + groups data between the Contacts Provider and the server. When users add a new contact to the + server and then put this contact in a new group, the sync adapter must add the new group + to the {@link android.provider.ContactsContract.Groups} table. The group or groups a raw + contact belongs to are stored in the {@link android.provider.ContactsContract.Data} table, using + the {@link android.provider.ContactsContract.CommonDataKinds.GroupMembership} MIME type. +

    +

    + If you're designing a sync adapter that will add raw contact data from + server to the Contacts Provider, and you aren't using groups, then you need to tell the + Provider to make your data visible. In the code that is executed when a user adds an account + to the device, update the {@link android.provider.ContactsContract.Settings} + row that the Contacts Provider adds for the account. In this row, set the value of the + {@link android.provider.ContactsContract.SettingsColumns#UNGROUPED_VISIBLE + Settings.UNGROUPED_VISIBLE} column to 1. When you do this, the Contacts Provider will always + make your contacts data visible, even if you don't use groups. +

    +

    Contact photos

    +

    + The {@link android.provider.ContactsContract.Data} table stores photos as rows with MIME type + {@link android.provider.ContactsContract.CommonDataKinds.Photo#CONTENT_ITEM_TYPE + Photo.CONTENT_ITEM_TYPE}. The row's + {@link android.provider.ContactsContract.RawContactsColumns#CONTACT_ID} column is linked to the + {@link android.provider.BaseColumns#_ID} column of the raw contact to which it belongs. + The class {@link android.provider.ContactsContract.Contacts.Photo} defines a sub-table of + {@link android.provider.ContactsContract.Contacts} containing photo information for a contact's + primary photo, which is the primary photo of the contact's primary raw contact. Similarly, + the class {@link android.provider.ContactsContract.RawContacts.DisplayPhoto} defines a sub-table + of {@link android.provider.ContactsContract.RawContacts} containing photo information for a + raw contact's primary photo. +

    +

    + The reference documentation for {@link android.provider.ContactsContract.Contacts.Photo} and + {@link android.provider.ContactsContract.RawContacts.DisplayPhoto} contain examples of + retrieving photo information. There is no convenience class for retrieving the primary + thumbnail for a raw contact, but you can send a query to the + {@link android.provider.ContactsContract.Data} table, selecting on the raw contact's + {@link android.provider.BaseColumns#_ID}, the + {@link android.provider.ContactsContract.CommonDataKinds.Photo#CONTENT_ITEM_TYPE + Photo.CONTENT_ITEM_TYPE}, and the {@link android.provider.ContactsContract.Data#IS_PRIMARY} + column to find the raw contact's primary photo row. +

    +

    + Social stream data for a person may also include photos. These are stored in the + {@link android.provider.ContactsContract.StreamItemPhotos} table, which is described in more + detail in the section Social stream photos. +

    diff --git a/docs/html/guide/topics/providers/content-provider-basics.jd b/docs/html/guide/topics/providers/content-provider-basics.jd index de89568c4fc6..b1d6827eb1c2 100644 --- a/docs/html/guide/topics/providers/content-provider-basics.jd +++ b/docs/html/guide/topics/providers/content-provider-basics.jd @@ -371,7 +371,7 @@ Uri singleUri = ContentUri.withAppendedId(UserDictionary.Words.CONTENT_URI,4); 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 + in more detail in the Loaders guide. Also, the lines of code are snippets only; they don't show a complete application.

    @@ -941,7 +941,7 @@ mRowsDeleted = getContentResolver().delete(
  • 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 - Loaders guide demonstrate + Loaders guide demonstrate how to do this.
  • diff --git a/docs/html/guide/topics/providers/content-provider-creating.jd b/docs/html/guide/topics/providers/content-provider-creating.jd index 4ebdb502138c..bad5390fa5f5 100644 --- a/docs/html/guide/topics/providers/content-provider-creating.jd +++ b/docs/html/guide/topics/providers/content-provider-creating.jd @@ -551,7 +551,7 @@ public class ExampleProvider extends ContentProvider { 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 - + Processes and Threads.
  • @@ -1211,5 +1211,5 @@ vnd.android.cursor.item/vnd.com.example.provider.table1

    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 - Intents and Intent Filters. + Intents and Intent Filters.

    diff --git a/docs/html/guide/topics/providers/content-providers.jd b/docs/html/guide/topics/providers/content-providers.jd index 1707f038b3ce..751fc95bbc85 100644 --- a/docs/html/guide/topics/providers/content-providers.jd +++ b/docs/html/guide/topics/providers/content-providers.jd @@ -18,6 +18,9 @@ page.title=Content Providers
  • Calendar Provider
  • +
  • + Contacts Provider +
  • @@ -38,6 +41,10 @@ page.title=Content Providers href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/List7.html"> "Cursor (Phones)" +
  • + + Sample Sync Adapter +
  • @@ -93,4 +100,11 @@ page.title=Content Providers
    How to access the Calendar Provider that is part of the Android platform.
    +
    + + Contacts Provider +
    +
    + How to access the Contacts Provider that is part of the Android platform. +
    diff --git a/docs/html/guide/topics/renderscript/compute.jd b/docs/html/guide/topics/renderscript/compute.jd deleted file mode 100644 index e827f003f97d..000000000000 --- a/docs/html/guide/topics/renderscript/compute.jd +++ /dev/null @@ -1,253 +0,0 @@ -page.title=Compute -parent.title=Renderscript -parent.link=index.html - -@jd:body - -
    -
    -

    In this document

    - -
      -
    1. - Creating a Compute Renderscript - -
        -
      1. Creating the Renderscript file
      2. - -
      3. Calling the Renderscript code
      4. -
      -
    2. -
    - -

    Related Samples

    - -
      -
    1. Hello - Compute
    2. - -
    3. Balls
    4. -
    -
    -
    - -

    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.

    - -

    Compute Renderscripts scale to the amount of -processing cores available on the device. This is enabled through a function named -rsForEach() (or the forEach_root() 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.

    - -

    Creating a Compute Renderscript

    - -

    Implementing a compute Renderscript creating a .rs file that contains -your Renderscript code and calling it at the Android framework level with the -forEach_root() or at the Renderscript runtime level with the -rsForEach() function. The following diagram describes how a typical compute -Renderscript is set up:

    - -

    Figure 1. Compute Renderscript overview

    - -

    The following sections describe how to create a simple compute Renderscript and use it in an -Android application. This example uses the HelloCompute Renderscript -sample that is provided in the SDK as a guide (some code has been modified from its original -form for simplicity).

    - -

    Creating the Renderscript file

    - -

    Your Renderscript code resides in .rs and .rsh files in the -<project_root>/src/ directory. This code contains the compute logic -and declares all necessary variables and pointers. -Every compute .rs file generally contains the following items:

    - - - -

    The following code shows how the -mono.rs file is implemented:

    -
    -#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);
    -}
    -
    - -

    Calling the Renderscript code

    - -

    You can do Renderscript to Renderscript calls with rsForEach in situations -such as when a graphics Renderscript needs to do a lot of computational operations. The Renderscript -Balls sample shows how -this is setup. The balls.rs -graphics Renderscript calls the balls_physics.rs -compute Renderscript to calculate the location of the balls that are rendered to the screen.

    - -

    Another way to use a compute Renderscript is to call it from your Android framework code by -creating a Renderscript object by instantiating the (ScriptC_script_name) -class. This class contains a method, forEach_root(), that lets you invoke -rsForEach. 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 HelloCompute sample to see -how a simple Android application can utilize a compute Renderscript.

    - -

    To call a compute Renderscript at the Android framework level:

    - -
      -
    1. 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.
    2. - -
    3. Create an instance of the ScriptC_script_name class.
    4. - -
    5. Call forEach_root(), passing in the allocations, the - Renderscript, and any optional user-defined data. The output allocation will contain the output - of the compute Renderscript.
    6. -
    - -

    In the following example, taken from the HelloCompute sample, processes -a bitmap and outputs a black and white version of it. The -createScript() method carries out the steps described previously. This method the compute -Renderscript, mono.rs, 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:

    -
    -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);
    -  }
    -}
    -
    - -

    To call a compute Renderscript from another Renderscript file:

    -
      -
    1. 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.
    2. - -
    3. Call rsForEach(), passing in the allocations and any optional user-defined data. - The output allocation will contain the output of the compute Renderscript.
    4. -
    -

    The following example, taken from the Renderscript -Balls sample, demonstrates how to do make a script to script call:

    -
    -rs_script script;
    -rs_allocation in_allocation;
    -rs_allocation out_allocation;
    -UserData_t data;
    -...
    -rsForEach(script, in_allocation, out_allocation, &data, sizeof(data));
    -
    - -

    In this example, assume that the script and memory allocations have already been -allocated and bound at the Android framework level and that UserData_t is a struct -declared previously. Passing a pointer to a struct and the size of the struct to rsForEach -is optional, but useful if your compute Renderscript requires additional information other than -the necessary memory allocations.

    diff --git a/docs/html/guide/topics/renderscript/graphics.jd b/docs/html/guide/topics/renderscript/graphics.jd deleted file mode 100644 index 462a9904faaa..000000000000 --- a/docs/html/guide/topics/renderscript/graphics.jd +++ /dev/null @@ -1,993 +0,0 @@ -page.title=Graphics -parent.title=Renderscript -parent.link=index.html - -@jd:body - - - -

    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 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.

    - -

    Creating a Graphics Renderscript

    - -

    Renderscript applications require various layers of code, so it is useful to create the following - files to help keep your application organized:

    - -
    -
    The Renderscript .rs file
    - -
    This file contains the logic to do the graphics rendering.
    - -
    The Renderscript entry point .java class
    - -
    This class allows the view class to interact with the code defined in the .rs - file. This class contains a Renderscript object (instance of - ScriptC_renderscript_file), which allows your Android framework code to - 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.
    - -
    The view .java class
    - -
    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()} 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
    - -
    The activity .java class
    - -
    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.
    -
    -

    Figure 1 describes how these classes interact with one another in a graphics Renderscript:

    - - -

    Figure 1. Graphics Renderscript overview

    - - -

    The following sections describe how to create an application that uses a graphics Renderscript by using - the Renderscript Fountain - sample that is provided in the SDK as a guide (some code has been modified from its original - form for simplicity).

    - -

    Creating the Renderscript file

    - -

    Your Renderscript code resides in .rs and .rsh (headers) files in the - <project_root>/src/ directory. This code contains the logic to render your - graphics and declares all other necessary items such as variables, structs, - and pointers. Every graphics .rs file generally contains the following items:

    - - - -

    The following code shows how the fountain.rs file is implemented:

    -
    -#pragma version(1)
    -
    -// Tell which java package name the reflected files should belong to
    -#pragma rs java_package_name(com.example.android.rs.fountain)
    -
    -//declare shader binding
    -#pragma stateFragment(parent)
    -
    -// header with graphics APIs, must include explicitly
    -#include "rs_graphics.rsh"
    -
    -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;
    -}
    -
    -// 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];
    -        }
    -    }
    -}
    -
    - -

    Creating the Renderscript entry point class

    - -

    When you create a Renderscript (.rs) file, it is helpful to create a - corresponding Android framework class that is an entry point into the .rs file. - The most important thing this class does is receive a {@link android.renderscript.RenderScriptGL} rendering context - object from the view class and binds the actual Renderscript - code to the rendering context. This notifies your view class of the code that it needs - to render graphics. -

    - -

    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:

    - - - -

    The following code shows how the - FountainRS class is implemented:

    -
    -package com.example.android.rs.fountain;
    -
    -import android.content.res.Resources;
    -import android.renderscript.*;
    -import android.util.Log;
    -
    -public class FountainRS {
    -    public static final int PART_COUNT = 50000;
    -
    -    public FountainRS() {
    -    }
    -
    -    /**
    -     * 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;
    -
    -        /**
    -         * 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];
    -
    -    /**
    -     * Calls Renderscript functions (invoke_addParticles)
    -     * via the Renderscript object to add particles to render
    -     * based on where a user touches the screen.
    -     */
    -    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;
    -        }
    -
    -    }
    -}
    -
    - - -

    Creating the view class

    - - -

    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 FountainView class is implemented:

    -
    -package com.example.android.rs.fountain;
    -
    -import android.renderscript.RSTextureView;
    -import android.renderscript.RenderScriptGL;
    -import android.content.Context;
    -import android.view.MotionEvent;
    -
    -public class FountainView extends RSTextureView {
    -
    -    public FountainView(Context context) {
    -        super(context);
    -    }
    -    // Renderscript context
    -    private RenderScriptGL mRS;
    -    // Renderscript entry point object that calls Renderscript code
    -    private FountainRS mRender;
    -
    -    /**
    -     * Create Renderscript context and initialize Renderscript entry point
    -     */
    -    @Override
    -    protected void onAttachedToWindow() {
    -        super.onAttachedToWindow();
    -        android.util.Log.e("rs", "onAttachedToWindow");
    -        if (mRS == null) {
    -            RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
    -            mRS = createRenderScriptGL(sc);
    -            mRender = new FountainRS();
    -            mRender.init(mRS, getResources());
    -        }
    -    }
    -
    -    @Override
    -    protected void onDetachedFromWindow() {
    -        super.onDetachedFromWindow();
    -        android.util.Log.e("rs", "onDetachedFromWindow");
    -        if (mRS != null) {
    -            mRS = null;
    -            destroyRenderScriptGL();
    -        }
    -    }
    -
    -
    -    /**
    -     * Use callbacks to relay data to Renderscript entry point class
    -     */
    -    @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);
    -        }
    -        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;
    -    }
    -}
    -
    - -

    Creating the activity class

    - -

    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.

    - -

    The following code shows how the Fountain - sample declares its activity class:

    -
    -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;
    -
    -    private FountainView mView;
    -
    -    @Override
    -    public void onCreate(Bundle icicle) {
    -        super.onCreate(icicle);
    -
    -        // Create our Preview view and set it as 
    -        // the content of our activity
    -        mView = new FountainView(this);
    -        setContentView(mView);
    -    }
    -
    -    @Override
    -    protected void onResume() {
    -        Log.e("rs", "onResume");
    -
    -        // Ideally a game should implement onResume() and onPause()
    -        // to take appropriate action when the activity looses focus
    -        super.onResume();
    -        mView.resume();
    -    }
    -
    -    @Override
    -    protected void onPause() {
    -        Log.e("rs", "onPause");
    -
    -        // Ideally a game should implement onResume() and onPause()
    -        // to take appropriate action when the activity looses focus
    -        super.onPause();
    -        mView.pause();
    -
    -    }
    -
    -    static void log(String message) {
    -        if (LOG_ENABLED) {
    -            Log.v(LOG_TAG, message);
    -        }
    -    }
    -}
    -
    - -

    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 -Renderscript samples as a starting -point if this is your first time using Renderscript.

    - -

    Drawing

    -

    The following sections describe how to use the graphics functions to draw with Renderscript.

    - -

    Simple drawing

    - -

    The native Renderscript APIs provide a few convenient functions to easily draw a polygon or text to - the screen. You call these in your root() 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:

    - - - -

    Drawing with a mesh

    - -

    When you want to render complex scenes to the screen, instantiate a {@link - android.renderscript.Mesh} and draw it with rsgDrawMesh(). A {@link - android.renderscript.Mesh} is a collection of allocations that represent vertex data (positions, - 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:

    - - - -

    To create a mesh using the {@link android.renderscript.Mesh.TriangleMeshBuilder}, you need to - supply it with a set of vertices and the indices for the vertices that comprise the triangle. For - example, the following code specifies three vertices, which are added to an internal array, - indexed in the order they were added. The call to {@link - android.renderscript.Mesh.TriangleMeshBuilder#addTriangle addTriangle()} draws the triangle with - vertex 0, 1, and 2 (the vertices are drawn counter-clockwise).

    -
    -int float2VtxSize = 2;
    -Mesh.TriangleMeshBuilder triangles = new Mesh.TriangleMeshBuilder(renderscriptGL,
    -float2VtxSize, Mesh.TriangleMeshBuilder.COLOR);
    -triangles.addVertex(300.f, 300.f);
    -triangles.addVertex(150.f, 450.f);
    -triangles.addVertex(450.f, 450.f);
    -triangles.addTriangle(0 , 1, 2);
    -Mesh smP = triangle.create(true);
    -script.set_mesh(smP);
    -
    - -

    To draw a mesh using the {@link android.renderscript.Mesh.AllocationBuilder}, you need to - supply it with one or more allocations that contain the vertex data:

    -
    -Allocation vertices;
    -
    -...
    -Mesh.AllocationBuilder triangle = new Mesh.AllocationBuilder(mRS);
    -smb.addVertexAllocation(vertices.getAllocation());
    -smb.addIndexSetType(Mesh.Primitive.TRIANGLE);
    -Mesh smP = smb.create();
    -script.set_mesh(smP);
    -
    - -

    In your Renderscript code, draw the built mesh to the screen:

    -
    -rs_mesh mesh;
    -...
    -
    -int root(){
    -...
    -rsgDrawMesh(mesh);
    -...
    -return 0; //specify a non zero, positive integer to specify the frame refresh.
    -          //0 refreshes the frame only when the mesh changes.
    -}
    -
    - -

    Programs

    - -

    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 that controls culling. The four programs mirror a - traditional graphical rendering pipeline:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Android Object TypeRenderscript Native TypeDescription
    {@link android.renderscript.ProgramVertex}rs_program_vertex -

    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:

    - -
      -
    • An {@link android.renderscript.Element} describing its varying inputs or attributes
    • - -
    • GLSL shader string that defines the body of the program
    • - -
    • a {@link android.renderscript.Type} that describes the layout of an - Allocation containing constant or uniform inputs
    • -
    - -

    Once the program is created, bind it to the {@link android.renderscript.RenderScriptGL} - graphics context by calling {@link android.renderscript.RenderScriptGL#bindProgramVertex - 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 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 {@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.

    - -

    To bind shader constants to the program, declare a struct that contains the necessary - shader constants in your 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 {@link android.renderscript.Allocation} to the program and the - Renderscript runtime sends the data that is contained in the struct 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.

    - -

    The {@link android.renderscript.ProgramVertexFixedFunction.Builder} class also - lets you build a simple vertex shader without writing GLSL code. -

    -
    {@link android.renderscript.ProgramFragment}rs_program_fragment -

    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, 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 {@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 rsgAllocationSyncAll(), 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 - inside the program vertex must provide it.

    - -

    To bind shader constructs to the program, declare a struct that contains the necessary - shader constants in your 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 {@link android.renderscript.Allocation} to the program and the - Renderscript runtime sends the data that is contained in the struct 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.

    - -

    The {@link android.renderscript.ProgramFragmentFixedFunction.Builder} class also - lets you build a simple fragment shader without writing GLSL code. -

    -
    {@link android.renderscript.ProgramStore}rs_program_storeThe 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.
    {@link android.renderscript.ProgramRaster}rs_program_rasterThe 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.
    - -

    The following example defines a vertex shader in GLSL and binds it to a Renderscript context object:

    -
    -    private RenderScriptGL glRenderer;      //rendering context
    -    private ScriptField_Point mPoints;      //vertices
    -    private ScriptField_VpConsts mVpConsts; //shader constants
    -
    -    ...
    -
    -     ProgramVertex.Builder sb = new ProgramVertex.Builder(glRenderer);
    -        String t =  "varying vec4 varColor;\n" +
    -                    "void main() {\n" +
    -                    "  vec4 pos = vec4(0.0, 0.0, 0.0, 1.0);\n" +
    -                    "  pos.xy = ATTRIB_position;\n" +
    -                    "  gl_Position = UNI_MVP * pos;\n" +
    -                    "  varColor = vec4(1.0, 1.0, 1.0, 1.0);\n" +
    -                    "  gl_PointSize = ATTRIB_size;\n" +
    -                    "}\n";
    -        sb.setShader(t);
    -        sb.addConstant(mVpConsts.getType());
    -        sb.addInput(mPoints.getElement());
    -        ProgramVertex pvs = sb.create();
    -        pvs.bindConstants(mVpConsts.getAllocation(), 0);
    -        glRenderer.bindProgramVertex(pvs);
    -
    - - -

    The - RsRenderStatesRS sample has many examples on how to create a shader without writing GLSL.

    - -

    Program bindings

    - -

    You can also declare four pragmas that control default program bindings to the {@link - android.renderscript.RenderScriptGL} context when the script is executing:

    - - - -

    The possible values for each pragma are parent or default. Using - default binds the shaders to the graphical context with the system defaults.

    - -

    Using parent 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.

    - -

    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:

    -
    -#pragma stateVertex(parent)
    -#pragma stateStore(parent)
    -
    - -

    Defining a sampler

    - -

    A {@link android.renderscript.Sampler} object defines how data is extracted from textures. - 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.

    - -

    The - RsRenderStatesRS sample has many examples on how to create a sampler and bind it to a - Fragment program.

    - - - -

    Rendering to a Framebuffer Object

    - -

    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.

    - -

    In general, you need to do the following to render to a framebuffer object:

    - - - -

    The following example shows you how to render to a framebuffer object by modifying the -Fountain Renderscript sample. The end -result is the FountainFBO 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.

    - -
      -
    1. Modify fountain.rs and add the following global variables. This creates setter - methods when this file is reflected into a .java file, allowing you to allocate - memory in your Android framework code and binding it to the Renderscript runtime. -
      -//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;
      -
      -
    2. - -
    3. Modify the root function of fountain.rs to look like the following code. The - modifications are commented: -
      -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;
      -}
      -
      -
    4. - -
    5. In the FountainRS.java file, modify the init() method to look - like the following code. The modifications are commented: - -
      -/* 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);
      -}
      -
      - -

      Note: 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: - -

      -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);
      -
      -
      -

      -
    6. - -
    7. 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.
    8. -
    diff --git a/docs/html/guide/topics/renderscript/index.jd b/docs/html/guide/topics/renderscript/index.jd deleted file mode 100644 index b2d9f8461be3..000000000000 --- a/docs/html/guide/topics/renderscript/index.jd +++ /dev/null @@ -1,804 +0,0 @@ -page.title=Renderscript -@jd:body - - - -

    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:

    - - -

    The main disadvantages are:

    - - - - -

    For an example of Renderscript in action, install the Renderscript sample applications that - are shipped with the SDK in <sdk_root>/samples/android-11/RenderScript. - 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.

    - -

    Renderscript Overview

    -

    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).

    - -

    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 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.

    - - -

    Figure 1. Renderscript system overview

    - -

    When using Renderscript, there are three layers of APIs that enable communication between the - Renderscript runtime and Android framework code:

    - - - -

    - -

    Renderscript Runtime Layer

    - -

    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. -

    -

    Note: 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.

    - -

    You define your Renderscript code in .rs - and .rsh files in the src/ directory of your Android project. The code - is compiled to intermediate bytecode by the - llvm 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 - llvm 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.

    - -

    Some key features of the Renderscript runtime libraries include:

    - - - -

    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:

    - -
    #include "rs_graphics.rsh"
    - -

    Reflected Layer

    - -

    The reflected layer is a set of classes that the Android build tools generate to allow access - 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:

    - - - - -

    Functions

    -

    Functions are reflected into the script class itself, located in -project_root/gen/package/name/ScriptC_renderscript_filename. For -example, if you declare the following function in your Renderscript code:

    - -
    -void touch(float x, float y, float pressure, int id) {
    -    if (id >= 10) {
    -        return;
    -    }
    -
    -    touchPos[id].x = x;
    -    touchPos[id].y = y;
    -    touchPressure[id] = pressure;
    -}
    -
    - -

    then the following code is generated:

    - -
    -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);
    -}
    -
    -

    -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.

    - -

    -If you want the Renderscript code to send a value back to the Android framework, use the -rsSendToClient() -function. -

    - -

    Variables

    - -

    Variables of supported types are reflected into the script class itself, located in -project_root/gen/package/name/ScriptC_renderscript_filename. A set of accessor -methods are generated for each variable. For example, if you declare the following variable in -your Renderscript code:

    -
    uint32_t unsignedInteger = 1;
    - -

    then the following code is generated:

    - -
    -private long mExportVar_unsignedInteger;
    -public void set_unsignedInteger(long v){
    -    mExportVar_unsignedInteger = v;
    -    setVar(mExportVarIdx_unsignedInteger, v);
    -}
    -
    -public long get_unsignedInteger(){
    -    return mExportVar_unsignedInteger;
    -}
    -  
    - - -

    Structs

    -

    Structs are reflected into their own classes, located in - <project_root>/gen/com/example/renderscript/ScriptField_struct_name. This - class represents an array of the struct and allows you to allocate memory for a - specified number of structs. For example, if you declare the following struct:

    -
    -typedef struct Point {
    -    float2 position;
    -    float size;
    -} Point_t;
    -
    - -

    then the following code is generated in ScriptField_Point.java: -

    -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 = 12;
    -
    -        Float2 position;
    -        float size;
    -
    -        Item() {
    -            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), "position");
    -        eb.add(Element.F32(rs), "size");
    -        return eb.create();
    -    }
    -
    -    public  ScriptField_Point(RenderScript rs, int count) {
    -        mItemArray = null;
    -        mIOBuffer = null;
    -        mElement = createElement(rs);
    -        init(rs, count);
    -    }
    -
    -    public  ScriptField_Point(RenderScript rs, int count, int usages) {
    -        mItemArray = null;
    -        mIOBuffer = null;
    -        mElement = createElement(rs);
    -        init(rs, count, usages);
    -    }
    -
    -    private void copyToArray(Item i, int index) {
    -        if (mIOBuffer == null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count
    -        */);
    -        mIOBuffer.reset(index * Item.sizeof);
    -        mIOBuffer.addF32(i.position);
    -        mIOBuffer.addF32(i.size);
    -    }
    -
    -    public void set(Item i, int index, boolean copyNow) {
    -        if (mItemArray == null) mItemArray = new Item[getType().getX() /* count */];
    -        mItemArray[index] = i;
    -        if (copyNow)  {
    -            copyToArray(i, index);
    -            mAllocation.setFromFieldPacker(index, mIOBuffer);
    -        }
    -    }
    -
    -    public Item get(int index) {
    -        if (mItemArray == null) return null;
    -        return mItemArray[index];
    -    }
    -
    -    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].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_position(int index) {
    -        if (mItemArray == null) return null;
    -        return mItemArray[index].position;
    -    }
    -
    -    public float get_size(int index) {
    -        if (mItemArray == null) return 0;
    -        return mItemArray[index].size;
    -    }
    -
    -    public void copyAll() {
    -        for (int ct = 0; ct < mItemArray.length; ct++) copyToArray(mItemArray[ct], ct);
    -        mAllocation.setFromFieldPacker(0, mIOBuffer);
    -    }
    -
    -    public void resize(int newSize) {
    -        if (mItemArray != null)  {
    -            int oldSize = mItemArray.length;
    -            int copySize = Math.min(oldSize, newSize);
    -            if (newSize == oldSize) return;
    -            Item ni[] = new Item[newSize];
    -            System.arraycopy(mItemArray, 0, ni, 0, copySize);
    -            mItemArray = ni;
    -        }
    -        mAllocation.resize(newSize);
    -        if (mIOBuffer != null) mIOBuffer = new FieldPacker(Item.sizeof * getType().getX()/* count */);
    -    }
    -}
    -
    - -

    The generated code is provided to you as a convenience to allocate memory for structs requested -by the Renderscript runtime and to interact with structs -in memory. Each struct's class defines the following methods and constructors:

    - - - -

    Pointers

    -

    Pointers are reflected into the script class itself, located in -project_root/gen/package/name/ScriptC_renderscript_filename. You -can declare pointers to a struct or any of the supported Renderscript types, but a -struct cannot contain pointers or nested arrays. For example, if you declare the -following pointers to a struct and int32_t

    - -
    -typedef struct Point {
    -    float2 position;
    -    float size;
    -} Point_t;
    -
    -Point_t *touchPoints;
    -int32_t *intPointer;
    -
    -

    then the following code is generated in:

    - -
    -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;
    -}
    -  
    - -

    A get method and a special method named bind_pointer_name -(instead of a set() 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 .rs file). For more information, see Working -with Allocated Memory. -

    - - -

    Memory Allocation APIs

    - -

    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 malloc 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 Figure 1 -for more information on how memory allocation occurs. -

    - -

    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 malloc 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 -malloc call that can look like this:

    - -
    array = (int *)malloc(sizeof(int)*10);
    - -

    The malloc call can be broken up into two parts: the size of the memory being allocated (sizeof(int)), - 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 malloc itself.

    - -

    The {@link android.renderscript.Element} class represents the (sizeof(int)) portion - of the malloc 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.

    - -

    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 - Allocating and binding memory to the Renderscript section. - The following table describes the three memory management classes in more detail:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    Android Object TypeDescription
    {@link android.renderscript.Element} -

    An element describes one cell of a memory allocation and can have two forms: basic or - complex.

    - -

    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.

    - -

    Complex elements contain a list of basic elements and are created from - structs that you declare in your Renderscript code. For instance an allocation - can contain multiple structs arranged in order in memory. Each struct is considered as its - own element, rather than each data type within that struct.

    -
    {@link android.renderscript.Type} -

    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.

    - -

    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.

    -
    {@link android.renderscript.Allocation} -

    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. -

    - -

    Allocation data is uploaded in one of two primary ways: type checked and type unchecked. - For simple arrays there are copyFrom() 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.

    -
    - -

    Working with Memory

    - -

    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 set method is -not generated.

    - - -

    Note: If you are using certain Renderscript structures that contain pointers, such as -rs_program_fragment and rs_allocation, you have to obtain an object of the -corresponding Android framework class first and then call the set 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. -

    - -

    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 .rs 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.

    - - - -

    Allocating and binding dynamic memory to the Renderscript

    - -

    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 bind method of the pointer to bind the allocated memory to the - Renderscript runtime.

    -

    The example below allocates memory for both a primitive type pointer, - intPointer, and a pointer to a struct, touchPoints. It also binds the memory to the - Renderscript:

    -
    -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);
    -
    -   ...
    -}
    -
    - -

    Reading and writing to memory

    -

    You can read and write to statically and dynamically allocated memory both at the Renderscript runtime - and Android framework layer.

    - -

    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 get -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 -rsSendToClient() function -to overcome this limitation. -

    -

    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.

    - -

    Reading and writing to global variables

    - -

    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.

    - -

    For example, given the following struct declared in a file named rsfile.rs:

    -
    -typedef struct Point {
    -    int x;
    -    int y;
    -} Point_t;
    -
    -Point_t point;
    -
    -
    -

    You can assign values to the struct like this directly in rsfile.rs. These values are not -propagated back to the Android framework level:

    -
    -point.x = 1;
    -point.y = 1;
    -
    - -

    You can assign values to the struct at the Android framework layer like this. These values are -propagated back to the Renderscript runtime level:

    -
    -ScriptC_rsfile mScript;
    -
    -...
    -
    -Item i = new ScriptField_Point.Item();
    -i.x = 1;
    -i.y = 1;
    -mScript.set_point(i);
    -
    - -

    You can read the values in your Renderscript code like this:

    - -
    -rsDebug("Printing out a Point", point.x, point.y);
    -
    - -

    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:

    - -
    -Log.i("TAGNAME", "Printing out a Point: " + mScript.get_point().x + " " + mScript.get_point().y);
    -System.out.println(point.get_x() + " " + point.get_y());
    -
    - -

    Reading and writing global pointers

    - -

    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 get and set 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.

    - -

    For example, given the following pointer to a struct in a file named rsfile.rs:

    -
    -typedef struct Point {
    -    int x;
    -    int y;
    -} Point_t;
    -
    -Point_t *point;
    -
    - -

    Assuming you already allocated memory at the Android framework layer, you can access values in -the struct as normal. Any changes you make to the struct via its pointer variable -are automatically available to the Android framework layer:

    - -
    -point[index].x = 1;
    -point[index].y = 1;
    -
    - -

    You can read and write values to the pointer at the Android framework layer as well: -

    -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);
    -
    - -

    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.

    diff --git a/docs/html/guide/topics/renderscript/reference.jd b/docs/html/guide/topics/renderscript/reference.jd deleted file mode 100644 index a0a9df2df8ab..000000000000 --- a/docs/html/guide/topics/renderscript/reference.jd +++ /dev/null @@ -1,18 +0,0 @@ -page.title=Runtime API Reference -@jd:body - - - - - diff --git a/docs/html/guide/topics/resources/animation-resource.jd b/docs/html/guide/topics/resources/animation-resource.jd index 6473155f33fd..3af52aae38c6 100644 --- a/docs/html/guide/topics/resources/animation-resource.jd +++ b/docs/html/guide/topics/resources/animation-resource.jd @@ -18,7 +18,7 @@ parent.link=available-resources.html

    See also

    1. View Animation
    2. -
    3. Property Animation
    4. +
    5. Property Animation
    @@ -334,7 +334,7 @@ set.start();
    see also:
    diff --git a/docs/html/guide/topics/resources/index.jd b/docs/html/guide/topics/resources/index.jd index 3f0f1eeb9611..386abf50a38a 100644 --- a/docs/html/guide/topics/resources/index.jd +++ b/docs/html/guide/topics/resources/index.jd @@ -1,103 +1,55 @@ -page.title=Application Resources -@jd:body - - - - -

    You should always externalize resources such as images and strings from your application -code, so that you can maintain them independently. Externalizing your -resources also allows you to provide alternative resources that support specific device -configurations such as different languages or screen sizes, which becomes increasingly -important as more Android-powered devices become available with different configurations. In order -to provide compatibility with different configurations, you must organize resources in your -project's {@code res/} directory, using various sub-directories that group resources by type and -configuration.

    - -
    - -

    -Figure 1. Two different devices, each using the default layout -(the app provides no alternative layouts).

    -
    - -
    - -

    -Figure 2. Two different devices, each using a different layout provided -for different screen sizes.

    -
    +page.title=App Resources +page.landing=true +page.landing.intro=It takes more than just code to build a great app. Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more. +page.landing.image=images/develop/resources.png -

    For any type of resource, you can specify default and multiple -alternative resources for your application:

    -
      -
    • Default resources are those that should be used regardless of -the device configuration or when there are no alternative resources that match the current -configuration.
    • -
    • Alternative resources are those that you've designed for use with a specific -configuration. To specify that a group of resources are for a specific configuration, -append an appropriate configuration qualifier to the directory name.
    • -
    - -

    For example, while your default UI -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.

    - -

    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.

    - -

    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:

    - -
    -
    Providing Resources
    -
    What kinds of resources you can provide in your app, where to save them, and how to create -alternative resources for specific device configurations.
    -
    Accessing Resources
    -
    How to use the resources you've provided, either by referencing them from your application -code or from other XML resources.
    -
    Handling Runtime Changes
    -
    How to manage configuration changes that occur while your Activity is running.
    -
    Localization
    -
    A bottom-up guide to localizing your application using alternative resources. While this is -just one specific use of alternative resources, it is very important in order to reach more -users.
    -
    Resource Types
    -
    A reference of various resource types you can provide, describing their XML elements, -attributes, and syntax. For example, this reference shows you how to create a resource for -application menus, drawables, animations, and more.
    -
    - - +
    + + + + +
    diff --git a/docs/html/guide/topics/resources/layout-resource.jd b/docs/html/guide/topics/resources/layout-resource.jd index 286e3d1280a3..5643075c6a3a 100644 --- a/docs/html/guide/topics/resources/layout-resource.jd +++ b/docs/html/guide/topics/resources/layout-resource.jd @@ -7,7 +7,7 @@ parent.link=available-resources.html

    See also

      -
    1. XML Layouts
    2. +
    3. Layouts
    @@ -128,7 +128,7 @@ or {@code "wrap_content"}). See the valid values bel

    More attributes are supported by the {@link android.view.View} base class, and many more are supported by each implementation of {@link android.view.View}. Read XML Layouts for more information. For +href="{@docRoot}guide/topics/ui/declaring-layout.html">Layouts for more information. For a reference of all available attributes, see the corresponding reference documentation (for example, the TextView XML attributes).

    @@ -275,7 +275,7 @@ public void onCreate(Bundle savedInstanceState) {
    see also:
    diff --git a/docs/html/guide/topics/resources/localization.jd b/docs/html/guide/topics/resources/localization.jd index c2b668da99dd..41961a346d6e 100755 --- a/docs/html/guide/topics/resources/localization.jd +++ b/docs/html/guide/topics/resources/localization.jd @@ -38,7 +38,6 @@ defaults.
  • Testing on an Emulator
  • Testing for Default Resources
  • -
  • Publishing
  • Localization Checklists
    1. Planning and Design Checklist
    2. @@ -52,7 +51,7 @@ defaults.
    3. Hello, L10N Tutorial
    4. Providing Resources
    5. -
    6. XML Layouts
    7. +
    8. Layouts
    9. Activity Lifecycle
    @@ -430,7 +429,7 @@ Menu > Settings > Locale & text > Select locale).

    Testing on an Emulator

    For details about using the emulator, see See Android Emulator.

    +href="{@docRoot}tools/help/emulator.html">Android Emulator.

    Creating and using a custom locale

    A "custom" locale is a language/region combination that the Android @@ -505,26 +504,6 @@ the new locale.

    res/layout-port/main.xml, then set the emulator or device to portrait orientation and see if the application will run. -

    Publishing Localized Applications

    - -

    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 Preparing to Publish.

    - -

    If you split your application in several .apk files, each targeted to a -different locale, follow these guidelines:

    - -
      -
    • Sign each .apk file with the same certificate. For more about this, see Signing -Strategies.
    • -
    • Give each .apk file a different application name. Currently it is -impossible to publish two applications on Google Play that have exactly the -same name.
    • -
    • Include a complete set of default resources in each .apk file.
    • -

    Localization Checklists

    @@ -640,8 +619,6 @@ border="0"> border="0"> Upload your .apk file or files to Google Play, selecting the appropriate languages as - you upload. (For more details, see Publishing Your -Applications.) + you upload. \ No newline at end of file diff --git a/docs/html/guide/topics/resources/menu-resource.jd b/docs/html/guide/topics/resources/menu-resource.jd index fb7612e41767..b2d6eb3445c9 100644 --- a/docs/html/guide/topics/resources/menu-resource.jd +++ b/docs/html/guide/topics/resources/menu-resource.jd @@ -111,7 +111,7 @@ only parameter, which indicates the item clicked. This method takes precedence o callback to {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()}. See the example at the bottom.

    Warning: If you obfuscate your code using ProGuard (or a similar tool), +href="{@docRoot}tools/help/proguard.html">ProGuard (or a similar tool), be sure to exclude the method you specify in this attribute from renaming, because it can break the functionality.

    Introduced in API Level 11.

    @@ -133,7 +133,8 @@ Avoid using this unless it's critical that the item always appear in the action bar. Setting multiple items to always appear as action items can result in them overlapping with other UI in the action bar. collapseActionViewThe action view associated -with this action item (as declared by android:actionViewLayout) is +with this action item (as declared by android:actionLayout or +android:actionViewClass) is collapsible.
    Introduced in API Level 14.

    See the Action Bar developer @@ -141,7 +142,7 @@ guide for more information.

    Introduced in API Level 11.

    -
    android:actionViewLayout
    +
    android:actionLayout
    Layout resource. A layout to use as the action view.

    See the Action Bar developer guide for more information.

    @@ -154,7 +155,7 @@ to use as the action view. For example,

    See the Action Bar developer guide for more information.

    Warning: If you obfuscate your code using ProGuard (or a similar tool), +href="{@docRoot}tools/help/proguard.html">ProGuard (or a similar tool), be sure to exclude the class you specify in this attribute from renaming, because it can break the functionality.

    Introduced in API Level 11.

    @@ -166,7 +167,7 @@ android.view.ActionProvider} to use in place of the action item. For example,

    See the Action Bar developer guide for more information.

    Warning: If you obfuscate your code using ProGuard (or a similar tool), +href="{@docRoot}tools/help/proguard.html">ProGuard (or a similar tool), be sure to exclude the class you specify in this attribute from renaming, because it can break the functionality.

    Introduced in API Level 14.

    diff --git a/docs/html/guide/topics/resources/overview.jd b/docs/html/guide/topics/resources/overview.jd new file mode 100644 index 000000000000..c3bd0bfb0581 --- /dev/null +++ b/docs/html/guide/topics/resources/overview.jd @@ -0,0 +1,103 @@ +page.title=Resources Overview +@jd:body + + + + +

    You should always externalize resources such as images and strings from your application +code, so that you can maintain them independently. Externalizing your +resources also allows you to provide alternative resources that support specific device +configurations such as different languages or screen sizes, which becomes increasingly +important as more Android-powered devices become available with different configurations. In order +to provide compatibility with different configurations, you must organize resources in your +project's {@code res/} directory, using various sub-directories that group resources by type and +configuration.

    + +
    + +

    +Figure 1. Two different devices, each using the default layout +(the app provides no alternative layouts).

    +
    + +
    + +

    +Figure 2. Two different devices, each using a different layout provided +for different screen sizes.

    +
    + +

    For any type of resource, you can specify default and multiple +alternative resources for your application:

    + + +

    For example, while your default UI +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.

    + +

    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.

    + +

    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:

    + +
    +
    Providing Resources
    +
    What kinds of resources you can provide in your app, where to save them, and how to create +alternative resources for specific device configurations.
    +
    Accessing Resources
    +
    How to use the resources you've provided, either by referencing them from your application +code or from other XML resources.
    +
    Handling Runtime Changes
    +
    How to manage configuration changes that occur while your Activity is running.
    +
    Localization
    +
    A bottom-up guide to localizing your application using alternative resources. While this is +just one specific use of alternative resources, it is very important in order to reach more +users.
    +
    Resource Types
    +
    A reference of various resource types you can provide, describing their XML elements, +attributes, and syntax. For example, this reference shows you how to create a resource for +application menus, drawables, animations, and more.
    +
    + + diff --git a/docs/html/guide/topics/resources/providing-resources.jd b/docs/html/guide/topics/resources/providing-resources.jd index 82b5e29472f8..b0d5d6fc21ee 100644 --- a/docs/html/guide/topics/resources/providing-resources.jd +++ b/docs/html/guide/topics/resources/providing-resources.jd @@ -44,7 +44,7 @@ Screens

    You should always externalize application resources such as images and strings from your code, so that you can maintain them independently. You should also provide alternative resources for specific device configurations, by grouping them in specially-named resource directories. At -runtime, Android uses uses the appropriate resource based on the current configuration. For +runtime, Android uses the appropriate resource based on the current configuration. For example, you might want to provide a different UI layout depending on the screen size or different strings depending on the language setting.

    @@ -89,7 +89,7 @@ supported inside project {@code res/} directory.

    animator/ - XML files that define property + XML files that define property animations. @@ -744,7 +744,7 @@ orientation" described above.

    The API level supported by the device. For example, v1 for API level 1 (devices with Android 1.0 or higher) and v4 for API level 4 (devices with Android 1.6 or higher). See the Android API levels document for more information +href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">Android API levels document for more information about these values.

    Caution: Android 1.5 and 1.6 only match resources with this qualifier when it exactly matches the platform version. See the section below about -

  • Ensure that your SDK Tools version +
  • Ensure that your SDK Tools version is r6 or greater.

    You need SDK Tools, Revision 6 (or greater), because it includes a new packaging tool that diff --git a/docs/html/guide/topics/resources/runtime-changes.jd b/docs/html/guide/topics/resources/runtime-changes.jd index 871b06320cde..f5475b40abc4 100644 --- a/docs/html/guide/topics/resources/runtime-changes.jd +++ b/docs/html/guide/topics/resources/runtime-changes.jd @@ -32,7 +32,7 @@ alternative resources that match the new device configuration.

    To properly handle a restart, it is important that your activity restores its previous state through the normal Activity +href="{@docRoot}guide/components/activities.html#Lifecycle">Activity lifecycle, in which Android calls {@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} before it destroys your activity so that you can save data about the application state. You can then restore the state @@ -45,7 +45,7 @@ tasks in your application. Your application should be able to restart at any tim user data or state in order to handle events such as configuration changes or when the user receives an incoming phone call and then returns to your application much later after your application process may have been destroyed. To learn how you can restore your activity state, read about the Activity lifecycle.

    +href="{@docRoot}guide/components/activities.html#Lifecycle">Activity lifecycle.

    However, you might encounter a situation in which restarting your application and restoring significant amounts of data can be costly and create a poor user experience. In such a diff --git a/docs/html/guide/topics/search/index.jd b/docs/html/guide/topics/search/index.jd index 218511b2a8e4..2ee624b6b7a7 100644 --- a/docs/html/guide/topics/search/index.jd +++ b/docs/html/guide/topics/search/index.jd @@ -1,4 +1,4 @@ -page.title=Search +page.title=Search Overview @jd:body

    diff --git a/docs/html/guide/topics/search/search-dialog.jd b/docs/html/guide/topics/search/search-dialog.jd index 8b8e75bb8a73..49451acf4d29 100644 --- a/docs/html/guide/topics/search/search-dialog.jd +++ b/docs/html/guide/topics/search/search-dialog.jd @@ -561,7 +561,7 @@ case, the search dialog naturally disappears).

    events are triggered once the user executes a search (the current activity receives {@link android.app.Activity#onPause()} and so forth, as described in the Activities +href="{@docRoot}guide/components/activities.html#Lifecycle">Activities document). If, however, the current activity is the searchable activity, then one of two things happens:

    diff --git a/docs/html/guide/topics/security/index.jd b/docs/html/guide/topics/security/index.jd new file mode 100644 index 000000000000..775fc036547b --- /dev/null +++ b/docs/html/guide/topics/security/index.jd @@ -0,0 +1,65 @@ +page.title=Security and Permissions +page.landing=true +page.landing.intro=Android's security architecture gives the user full control over what resources are accessible to each app, protecting the system itself and all apps in it. Learn how to use system permissions to request access to the resources your app needs and design your app for optimal security. +page.landing.image= + +@jd:body + +
    + +
    +

    Blog Articles

    + +
    + +
    + +
    + +
    +

    Accessibility: Are You Serving All Your Users?

    +

    In the upcoming weeks, some of the older Client Login authentication keys will expire. + If you generated the token you’re currently using to authenticate with the C2DM servers before October 2011, it will stop working.

    + +

    Android C2DM — Client Login key expiration

    +

    Accessibility is about making sure that Android users who have limited vision or other physical impairments can use your application just as well

    + +

    A Faster Emulator with Better Hardware Support

    +

    The Android emulator is a key tool for Android developers in building and testing their apps. + As the power and diversity of Android devices has grown quickly, it’s been hard for the emulator keep pace.

    + + More » +
    +
    +
    + +
    +

    Training

    + +
    + +
    + +
    + +
    +

    Managing the Activity Lifecycle

    +

    This class explains important lifecycle callback methods that each Activity + instance receives and how you can use them so your activity does what the user expects and does not consume system + resources when your activity doesn't need them.

    + +

    Supporting Different Devices

    +

    This class teaches you how to use basic platform features that leverage alternative + resources and other features so your app can provide an optimized user experience on a variety of Android-compatible devices, + using a single application package (APK).

    + +

    Sharing Content

    +

    This class covers some common ways you can send and receive content between + applications using Intent APIs and the ActionProvider object.

    + + More » +
    +
    +
    + +
    \ No newline at end of file diff --git a/docs/html/guide/topics/security/permissions.jd b/docs/html/guide/topics/security/permissions.jd new file mode 100644 index 000000000000..3013e387008d --- /dev/null +++ b/docs/html/guide/topics/security/permissions.jd @@ -0,0 +1,407 @@ +page.title=Permissions +@jd:body + + +

    This document describes how application developers can use the +security features provided by Android. A more general Android Security +Overview is provided in the Android Open Source Project.

    + +

    Android is a privilege-separated operating system, in which each +application runs with a distinct system identity (Linux user ID and group +ID). Parts of the system are also separated into distinct identities. +Linux thereby isolates applications from each other and from the system.

    + +

    Additional finer-grained security features are provided through a +"permission" mechanism that enforces restrictions on the specific operations +that a particular process can perform, and per-URI permissions for granting +ad-hoc access to specific pieces of data.

    + + +

    Security Architecture

    + +

    A central design point of the Android security architecture is that no +application, by default, has permission to perform any operations that would +adversely impact other applications, the operating system, or the user. This +includes reading or writing the user's private data (such as contacts or +e-mails), reading or writing another application's files, performing +network access, keeping the device awake, etc.

    + +

    Because Android sandboxes applications from each other, applications +must explicitly share resources and data. They do this by declaring the +permissions they need for additional capabilities not provided by +the basic sandbox. Applications statically declare the permissions they +require, and the Android system prompts the user for consent at the time the +application is installed. Android has no mechanism for granting permissions +dynamically (at run-time) because it complicates the user experience to the +detriment of security.

    + +

    The application sandbox does not depend on the technology used to build +an application. In particular the Dalvik VM is not a security boundary, and +any app can run native code (see the Android +NDK). All types of applications — Java, native, and hybrid — +are sandboxed in the same way and have the same degree of security from each +other.

    + + +

    Application Signing

    + +

    All Android applications (.apk files) must be signed with a certificate +whose private key is held by their developer. This certificate identifies +the author of the application. The certificate does not need to be +signed by a certificate authority: it is perfectly allowable, and typical, +for Android applications to use self-signed certificates. The purpose of +certificates in Android is to distinguish application authors. This allows +the system to grant or deny applications access to signature-level +permissions and to grant or deny an application's request to be given +the same Linux identity as another application.

    + + +

    User IDs and File Access

    + +

    At install time, Android gives each package a distinct Linux user ID. The +identity remains constant for the duration of the package's life on that +device. On a different device, the same package may have a different UID; +what matters is that each package has a distinct UID on a given device.

    + +

    Because security enforcement happens at the +process level, the code of any two packages can not normally +run in the same process, since they need to run as different Linux users. +You can use the {@link android.R.attr#sharedUserId} attribute in the +AndroidManifest.xml's +{@link android.R.styleable#AndroidManifest manifest} tag of each package to +have them assigned the same user ID. By doing this, for purposes of security +the two packages are then treated as being the same application, with the same +user ID and file permissions. Note that in order to retain security, only two applications +signed with the same signature (and requesting the same sharedUserId) will +be given the same user ID.

    + +

    Any data stored by an application will be assigned that application's user +ID, and not normally accessible to other packages. When creating a new file +with {@link android.content.Context#getSharedPreferences}, +{@link android.content.Context#openFileOutput}, or +{@link android.content.Context#openOrCreateDatabase}, +you can use the +{@link android.content.Context#MODE_WORLD_READABLE} and/or +{@link android.content.Context#MODE_WORLD_WRITEABLE} flags to allow any other +package to read/write the file. When setting these flags, the file is still +owned by your application, but its global read and/or write permissions have +been set appropriately so any other application can see it.

    + + + +

    Using Permissions

    + +

    A basic Android application has no permissions associated with it, +meaning it can not do anything that would adversely impact the user experience +or any data on the device. To make use of protected features of the device, +you must include in your AndroidManifest.xml one or more +{@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} +tags declaring the permissions that your application needs.

    + +

    For example, an application that needs to monitor incoming SMS messages would +specify:

    + +
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +    package="com.android.app.myapp" >
    +    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    +    ...
    +</manifest>
    + +

    At application install time, permissions requested by the application are +granted to it by the package installer, based on checks against the +signatures of the applications declaring those permissions and/or interaction +with the user. No checks with the user +are done while an application is running: it either was granted a particular +permission when installed, and can use that feature as desired, or the +permission was not granted and any attempt to use the feature will fail +without prompting the user.

    + +

    Often times a permission failure will result in a {@link +java.lang.SecurityException} being thrown back to the application. However, +this is not guaranteed to occur everywhere. For example, the {@link +android.content.Context#sendBroadcast} method checks permissions as data is +being delivered to each receiver, after the method call has returned, so you +will not receive an exception if there are permission failures. In almost all +cases, however, a permission failure will be printed to the system log.

    + +

    The permissions provided by the Android system can be found at {@link +android.Manifest.permission}. Any application may also define and enforce its +own permissions, so this is not a comprehensive list of all possible +permissions.

    + +

    A particular permission may be enforced at a number of places during your +program's operation:

    + +
      +
    • At the time of a call into the system, to prevent an application from +executing certain functions.
    • +
    • When starting an activity, to prevent applications from launching +activities of other applications.
    • +
    • Both sending and receiving broadcasts, to control who can receive +your broadcast or who can send a broadcast to you.
    • +
    • When accessing and operating on a content provider.
    • +
    • Binding to or starting a service.
    • +
    + + + +

    Declaring and Enforcing Permissions

    + +

    To enforce your own permissions, you must first declare them in your +AndroidManifest.xml using one or more +{@link android.R.styleable#AndroidManifestPermission <permission>} +tags.

    + +

    For example, an application that wants to control who can start one +of its activities could declare a permission for this operation as follows:

    + +
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +    package="com.me.app.myapp" >
    +    <permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"
    +        android:label="@string/permlab_deadlyActivity"
    +        android:description="@string/permdesc_deadlyActivity"
    +        android:permissionGroup="android.permission-group.COST_MONEY"
    +        android:protectionLevel="dangerous" />
    +    ...
    +</manifest>
    + +

    The {@link android.R.styleable#AndroidManifestPermission_protectionLevel +<protectionLevel>} attribute is required, telling the system how the +user is to be informed of applications requiring the permission, or who is +allowed to hold that permission, as described in the linked documentation.

    + +

    The {@link android.R.styleable#AndroidManifestPermission_permissionGroup +<permissionGroup>} attribute is optional, and only used to help the system display +permissions to the user. You will usually want to set this to either a standard +system group (listed in {@link android.Manifest.permission_group +android.Manifest.permission_group}) or in more rare cases to one defined by +yourself. It is preferred to use an existing group, as this simplifies the +permission UI shown to the user.

    + +

    Note that both a label and description should be supplied for the +permission. These are string resources that can be displayed to the user when +they are viewing a list of permissions +({@link android.R.styleable#AndroidManifestPermission_label android:label}) +or details on a single permission ( +{@link android.R.styleable#AndroidManifestPermission_description android:description}). +The label should be short, a few words +describing the key piece of functionality the permission is protecting. The +description should be a couple sentences describing what the permission allows +a holder to do. Our convention for the description is two sentences, the first +describing the permission, the second warning the user of what bad things +can happen if an application is granted the permission.

    + +

    Here is an example of a label and description for the CALL_PHONE +permission:

    + +
    +    <string name="permlab_callPhone">directly call phone numbers</string>
    +    <string name="permdesc_callPhone">Allows the application to call
    +        phone numbers without your intervention. Malicious applications may
    +        cause unexpected calls on your phone bill. Note that this does not
    +        allow the application to call emergency numbers.</string>
    +
    + +

    You can look at the permissions currently defined in the system with the +Settings app and the shell command adb shell pm list permissions. +To use the Settings app, go to Settings > Applications. Pick an app and +scroll down to see the permissions that the app uses. For developers, the adb '-s' +option displays the permissions in a form similar to how the user will see them:

    + +
    +$ adb shell pm list permissions -s
    +All Permissions:
    +
    +Network communication: view Wi-Fi state, create Bluetooth connections, full
    +Internet access, view network state
    +
    +Your location: access extra location provider commands, fine (GPS) location,
    +mock location sources for testing, coarse (network-based) location
    +
    +Services that cost you money: send SMS messages, directly call phone numbers
    +
    +...
    + + +

    Enforcing Permissions in AndroidManifest.xml

    + +

    High-level permissions restricting access to entire components of the +system or application can be applied through your +AndroidManifest.xml. All that this requires is including an {@link +android.R.attr#permission android:permission} attribute on the desired +component, naming the permission that will be used to control access to +it.

    + +

    {@link android.app.Activity} permissions +(applied to the +{@link android.R.styleable#AndroidManifestActivity <activity>} tag) +restrict who can start the associated +activity. The permission is checked during +{@link android.content.Context#startActivity Context.startActivity()} and +{@link android.app.Activity#startActivityForResult Activity.startActivityForResult()}; +if the caller does not have +the required permission then {@link java.lang.SecurityException} is thrown +from the call.

    + +

    {@link android.app.Service} permissions +(applied to the +{@link android.R.styleable#AndroidManifestService <service>} tag) +restrict who can start or bind to the +associated service. The permission is checked during +{@link android.content.Context#startService Context.startService()}, +{@link android.content.Context#stopService Context.stopService()} and +{@link android.content.Context#bindService Context.bindService()}; +if the caller does not have +the required permission then {@link java.lang.SecurityException} is thrown +from the call.

    + +

    {@link android.content.BroadcastReceiver} permissions +(applied to the +{@link android.R.styleable#AndroidManifestReceiver <receiver>} tag) +restrict who can send broadcasts to the associated receiver. +The permission is checked after +{@link android.content.Context#sendBroadcast Context.sendBroadcast()} returns, +as the system tries +to deliver the submitted broadcast to the given receiver. As a result, a +permission failure will not result in an exception being thrown back to the +caller; it will just not deliver the intent. In the same way, a permission +can be supplied to +{@link android.content.Context#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter, String, android.os.Handler) +Context.registerReceiver()} +to control who can broadcast to a programmatically registered receiver. +Going the other way, a permission can be supplied when calling +{@link android.content.Context#sendBroadcast(Intent, String) Context.sendBroadcast()} +to restrict which BroadcastReceiver objects are allowed to receive the broadcast (see +below).

    + +

    {@link android.content.ContentProvider} permissions +(applied to the +{@link android.R.styleable#AndroidManifestProvider <provider>} tag) +restrict who can access the data in +a {@link android.content.ContentProvider}. (Content providers have an important +additional security facility available to them called +URI permissions which is described later.) +Unlike the other components, +there are two separate permission attributes you can set: +{@link android.R.attr#readPermission android:readPermission} restricts who +can read from the provider, and +{@link android.R.attr#writePermission android:writePermission} restricts +who can write to it. Note that if a provider is protected with both a read +and write permission, holding only the write permission does not mean +you can read from a provider. The permissions are checked when you first +retrieve a provider (if you don't have either permission, a SecurityException +will be thrown), and as you perform operations on the provider. Using +{@link android.content.ContentResolver#query ContentResolver.query()} requires +holding the read permission; using +{@link android.content.ContentResolver#insert ContentResolver.insert()}, +{@link android.content.ContentResolver#update ContentResolver.update()}, +{@link android.content.ContentResolver#delete ContentResolver.delete()} +requires the write permission. +In all of these cases, not holding the required permission results in a +{@link java.lang.SecurityException} being thrown from the call.

    + + + +

    Enforcing Permissions when Sending Broadcasts

    + +

    In addition to the permission enforcing who can send Intents to a +registered {@link android.content.BroadcastReceiver} (as described above), you +can also specify a required permission when sending a broadcast. By calling {@link +android.content.Context#sendBroadcast(android.content.Intent,String) +Context.sendBroadcast()} with a +permission string, you require that a receiver's application must hold that +permission in order to receive your broadcast.

    + +

    Note that both a receiver and a broadcaster can require a permission. When +this happens, both permission checks must pass for the Intent to be delivered +to the associated target.

    + + + +

    Other Permission Enforcement

    + +

    Arbitrarily fine-grained permissions can be enforced at any call into a +service. This is accomplished with the {@link +android.content.Context#checkCallingPermission Context.checkCallingPermission()} +method. Call with a desired +permission string and it will return an integer indicating whether that +permission has been granted to the current calling process. Note that this can +only be used when you are executing a call coming in from another process, +usually through an IDL interface published from a service or in some other way +given to another process.

    + +

    There are a number of other useful ways to check permissions. If you have +the pid of another process, you can use the Context method {@link +android.content.Context#checkPermission(String, int, int) Context.checkPermission(String, int, int)} +to check a permission against that pid. If you have the package name of another +application, you can use the direct PackageManager method {@link +android.content.pm.PackageManager#checkPermission(String, String) +PackageManager.checkPermission(String, String)} +to find out whether that particular package has been granted a specific permission.

    + + + +

    URI Permissions

    + +

    The standard permission system described so far is often not sufficient +when used with content providers. A content provider may want to +protect itself with read and write permissions, while its direct clients +also need to hand specific URIs to other applications for them to operate on. +A typical example is attachments in a mail application. Access to the mail +should be protected by permissions, since this is sensitive user data. However, +if a URI to an image attachment is given to an image viewer, that image viewer +will not have permission to open the attachment since it has no reason to hold +a permission to access all e-mail.

    + +

    The solution to this problem is per-URI permissions: when starting an +activity or returning a result to an activity, the caller can set +{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION +Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or +{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION +Intent.FLAG_GRANT_WRITE_URI_PERMISSION}. This grants the receiving activity +permission access the specific data URI in the Intent, regardless of whether +it has any permission to access data in the content provider corresponding +to the Intent.

    + +

    This mechanism allows a common capability-style model where user interaction +(opening an attachment, selecting a contact from a list, etc) drives ad-hoc +granting of fine-grained permission. This can be a key facility for reducing +the permissions needed by applications to only those directly related to their +behavior.

    + +

    The granting of fine-grained URI permissions does, however, require some +cooperation with the content provider holding those URIs. It is strongly +recommended that content providers implement this facility, and declare that +they support it through the +{@link android.R.styleable#AndroidManifestProvider_grantUriPermissions +android:grantUriPermissions} attribute or +{@link android.R.styleable#AndroidManifestGrantUriPermission +<grant-uri-permissions>} tag.

    + +

    More information can be found in the +{@link android.content.Context#grantUriPermission Context.grantUriPermission()}, +{@link android.content.Context#revokeUriPermission Context.revokeUriPermission()}, and +{@link android.content.Context#checkUriPermission Context.checkUriPermission()} +methods.

    + diff --git a/docs/html/guide/topics/security/security.jd b/docs/html/guide/topics/security/security.jd index 1fd9ba011ce1..eeaac44e3940 100644 --- a/docs/html/guide/topics/security/security.jd +++ b/docs/html/guide/topics/security/security.jd @@ -1,407 +1,770 @@ -page.title=Security and Permissions +page.title=Designing for Security @jd:body -

    This document describes how application developers can use the -security features provided by Android. A more general Android Security -Overview is provided in the Android Open Source Project.

    - -

    Android is a privilege-separated operating system, in which each -application runs with a distinct system identity (Linux user ID and group -ID). Parts of the system are also separated into distinct identities. -Linux thereby isolates applications from each other and from the system.

    - -

    Additional finer-grained security features are provided through a -"permission" mechanism that enforces restrictions on the specific operations -that a particular process can perform, and per-URI permissions for granting -ad-hoc access to specific pieces of data.

    - - -

    Security Architecture

    - -

    A central design point of the Android security architecture is that no -application, by default, has permission to perform any operations that would -adversely impact other applications, the operating system, or the user. This -includes reading or writing the user's private data (such as contacts or -e-mails), reading or writing another application's files, performing -network access, keeping the device awake, etc.

    - -

    Because Android sandboxes applications from each other, applications -must explicitly share resources and data. They do this by declaring the -permissions they need for additional capabilities not provided by -the basic sandbox. Applications statically declare the permissions they -require, and the Android system prompts the user for consent at the time the -application is installed. Android has no mechanism for granting permissions -dynamically (at run-time) because it complicates the user experience to the -detriment of security.

    - -

    The application sandbox does not depend on the technology used to build -an application. In particular the Dalvik VM is not a security boundary, and -any app can run native code (see the Android -NDK). All types of applications — Java, native, and hybrid — -are sandboxed in the same way and have the same degree of security from each -other.

    - - -

    Application Signing

    - -

    All Android applications (.apk files) must be signed with a certificate -whose private key is held by their developer. This certificate identifies -the author of the application. The certificate does not need to be -signed by a certificate authority: it is perfectly allowable, and typical, -for Android applications to use self-signed certificates. The purpose of -certificates in Android is to distinguish application authors. This allows -the system to grant or deny applications access to signature-level -permissions and to grant or deny an application's request to be given -the same Linux identity as another application.

    - - -

    User IDs and File Access

    - -

    At install time, Android gives each package a distinct Linux user ID. The -identity remains constant for the duration of the package's life on that -device. On a different device, the same package may have a different UID; -what matters is that each package has a distinct UID on a given device.

    - -

    Because security enforcement happens at the -process level, the code of any two packages can not normally -run in the same process, since they need to run as different Linux users. -You can use the {@link android.R.attr#sharedUserId} attribute in the -AndroidManifest.xml's -{@link android.R.styleable#AndroidManifest manifest} tag of each package to -have them assigned the same user ID. By doing this, for purposes of security -the two packages are then treated as being the same application, with the same -user ID and file permissions. Note that in order to retain security, only two applications -signed with the same signature (and requesting the same sharedUserId) will -be given the same user ID.

    - -

    Any data stored by an application will be assigned that application's user -ID, and not normally accessible to other packages. When creating a new file -with {@link android.content.Context#getSharedPreferences}, -{@link android.content.Context#openFileOutput}, or -{@link android.content.Context#openOrCreateDatabase}, -you can use the -{@link android.content.Context#MODE_WORLD_READABLE} and/or -{@link android.content.Context#MODE_WORLD_WRITEABLE} flags to allow any other -package to read/write the file. When setting these flags, the file is still -owned by your application, but its global read and/or write permissions have -been set appropriately so any other application can see it.

    - - - -

    Using Permissions

    - -

    A basic Android application has no permissions associated with it, -meaning it can not do anything that would adversely impact the user experience -or any data on the device. To make use of protected features of the device, -you must include in your AndroidManifest.xml one or more -{@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} -tags declaring the permissions that your application needs.

    - -

    For example, an application that needs to monitor incoming SMS messages would -specify:

    - -
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    -    package="com.android.app.myapp" >
    -    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    -    ...
    -</manifest>
    - -

    At application install time, permissions requested by the application are -granted to it by the package installer, based on checks against the -signatures of the applications declaring those permissions and/or interaction -with the user. No checks with the user -are done while an application is running: it either was granted a particular -permission when installed, and can use that feature as desired, or the -permission was not granted and any attempt to use the feature will fail -without prompting the user.

    - -

    Often times a permission failure will result in a {@link -java.lang.SecurityException} being thrown back to the application. However, -this is not guaranteed to occur everywhere. For example, the {@link -android.content.Context#sendBroadcast} method checks permissions as data is -being delivered to each receiver, after the method call has returned, so you -will not receive an exception if there are permission failures. In almost all -cases, however, a permission failure will be printed to the system log.

    - -

    The permissions provided by the Android system can be found at {@link -android.Manifest.permission}. Any application may also define and enforce its -own permissions, so this is not a comprehensive list of all possible +

    See also

    +
      +
    1. Android +Security Overview
    2. +
    3. Android Security +And Permissions
    4. +
    +
    +

    Android was designed so that most developers will be able to build +applications using the default settings and not be confronted with difficult +decisions about security. Android also has a number of security features built +into the operating system that significantly reduce the frequency and impact of +application security issues.

    + +

    Some of the security features that help developers build secure applications +include: +

      +
    • The Android Application Sandbox that isolates data and code execution on a +per-application basis.
    • +
    • Android application framework with robust implementations of common +security functionality such as cryptography, permissions, and secure IPC.
    • +
    • Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD +calloc, and Linux mmap_min_addr to mitigate risks associated with common memory +management errors
    • +
    • An encrypted filesystem that can be enabled to protect data on lost or +stolen devices.
    • +

    + +

    Nevertheless, it is important for developers to be familiar with Android +security best practices to make sure they take advantage of these capabilities +and to reduce the likelihood of inadvertently introducing security issues that +can affect their applications.

    + +

    This document is organized around common APIs and development techniques +that can have security implications for your application and its users. As +these best practices are constantly evolving, we recommend you check back +occasionally throughout your application development process.

    + + +

    Using Dalvik Code

    +

    Writing secure code that runs in virtual machines is a well-studied topic +and many of the issues are not specific to Android. Rather than attempting to +rehash these topics, we’d recommend that you familiarize yourself with the +existing literature. Two of the more popular resources are: +

    + +

    This document is focused on the areas which are Android specific and/or +different from other environments. For developers experienced with VM +programming in other environments, there are two broad issues that may be +different about writing apps for Android: +

      +
    • Some virtual machines, such as the JVM or .net runtime, act as a security +boundary, isolating code from the underlying operating system capabilities. On +Android, the Dalvik VM is not a security boundary -- the application sandbox is +implemented at the OS level, so Dalvik can interoperate with native code in the +same application without any security constraints.
    • +
    • Given the limited storage on mobile devices, it’s common for developers +to want to build modular applications and use dynamic class loading. When +doing this consider both the source where you retrieve your application logic +and where you store it locally. Do not use dynamic class loading from sources +that are not verified, such as unsecured network sources or external storage, +since that code can be modified to include malicious behavior.
    • +

    + + +

    Using Native Code

    + +

    In general, we encourage developers to use the Android SDK for most +application development, rather than using native code. Applications built +with native code are more complex, less portable, and more like to include +common memory corruption errors such as buffer overflows.

    + +

    Android is built using the Linux kernel and being familiar with Linux +development security best practices is especially useful if you are going to +use native code. This document is too short to discuss all of those best +practices, but one of the most popular resources is “Secure Programming for +Linux and Unix HOWTO”, available at +http://www.dwheeler.com/secure-programs.

    + +

    An important difference between Android and most Linux environments is the +Application Sandbox. On Android, all applications run in the Application +Sandbox, including those written with native code. At the most basic level, a +good way to think about it for developers familiar with Linux is to know that +every application is given a unique UID with very limited permissions. This is +discussed in more detail in the Android Security +Overview and you should be familiar with application permissions even if +you are using native code.

    + + +

    Storing Data

    + +

    Using internal files

    + +

    By default, files created on internal +storage are only accessible to the application that created the file. This +protection is implemented by Android and is sufficient for most +applications.

    + +

    Use of +world writable or world +readable files for IPC is discouraged because it does not provide +the ability to limit data access to particular applications, nor does it +provide any control on data format. As an alternative, you might consider using +a ContentProvider which provides read and write permissions, and can make +dynamic permission grants on a case-by-case basis.

    + +

    To provide additional protection for sensitive data, some applications +choose to encrypt local files using a key that is not accessible to the +application. (For example, a key can be placed in a KeyStore and +protected with a user password that is not stored on the device). While this +does not protect data from a root compromise that can monitor the user +inputting the password, it can provide protection for a lost device without file system +encryption.

    + +

    Using external storage

    + +

    Files created on external +storage, such as SD Cards, are globally readable and writable. Since +external storage can be removed by the user and also modified by any +application, applications should not store sensitive information using +external storage.

    + +

    As with data from any untrusted source, applications should perform input +validation when handling data from external storage (see Input Validation +section). We strongly recommend that applications not store executables or +class files on external storage prior to dynamic loading. If an application +does retrieve executable files from external storage they should be signed and +cryptographically verified prior to dynamic loading.

    + +

    Using content providers

    + +

    ContentProviders provide a structured storage mechanism that can be limited +to your own application, or exported to allow access by other applications. By +default, a + +ContentProvider is +exported + for use by other applications. If you do not intend to provide other +applications with access to your + +ContentProvider, mark them as +android:exported=false in the application manifest.

    + +

    When creating a +ContentProvider + that will be exported for use by other applications, you can specify +a single +permission + for reading and writing, or distinct permissions for reading and writing +within the manifest. We recommend that you limit your permissions to those +required to accomplish the task at hand. Keep in mind that it’s usually +easier to add permissions later to expose new functionality than it is to take +them away and break existing users.

    + +

    If you are using a + +ContentProvider for sharing data between applications built by the +same developer, it is preferable to use +signature +level permissions. Signature permissions do not require user confirmation, +so they provide a better user experience and more controlled access to the + + +ContentProvider.

    + +

    ContentProviders can also provide more granular access by declaring the +grantUriPermissions element and using the FLAG_GRANT_READ_URI_PERMISSION +and FLAG_GRANT_WRITE_URI_PERMISSION +flags in the Intent object +that activates the component. The scope of these permissions can be further +limited by the +grant-uri-permission element.

    + +

    When accessing a + +ContentProvider, use parameterized query methods such as +query(), update(), and delete() to avoid +potential SQL +Injection from untrusted data. Note that using parameterized methods is not +sufficient if the selection is built by concatenating user data +prior to submitting it to the method.

    + +

    Do not have a false sense of security about the write permission. Consider +that the write permission allows SQL statements which make it possible for some +data to be confirmed using creative WHERE clauses and parsing the +results. For example, an attacker might probe for presence of a specific phone +number in a call-log by modifying a row only if that phone number already +exists. If the content provider data has predictable structure, the write +permission may be equivalent to providing both reading and writing.

    + + +

    Using Interprocess Communication (IPC)

    + +

    Some Android applications attempt to implement IPC using traditional Linux +techniques such as network sockets and shared files. We strongly encourage the +use of Android system functionality for IPC such as Intents, Binders, Services, +and Receivers. The Android IPC mechanisms allow you to verify the identity of +the application connecting to your IPC and set security policy for each IPC +mechanism.

    + +

    Many of the security elements are shared across IPC mechanisms. +Broadcast Receivers, +Activities, and +Services are all declared in the application manifest. If your IPC mechanism is +not intended for use by other applications, set the {@code android:exported} +property to false. This is useful for applications that consist of multiple processes +within the same UID, or if you decide late in development that you do not +actually want to expose functionality as IPC but you don’t want to rewrite +the code.

    + +

    If your IPC is intended to be accessible to other applications, you can +apply a security policy by using the +Permission tag. If IPC is between applications built by the same developer, +it is preferable to use signature +level permissions. Signature permissions do not require user confirmation, +so they provide a better user experience and more controlled access to the IPC +mechanism.

    + +

    One area that can introduce confusion is the use of intent filters. Note +that Intent filters should not be considered a security feature -- components +can be invoked directly and may not have data that would conform to the intent +filter. You should perform input validation within your intent receiver to +confirm that it is properly formatted for the invoked receiver, service, or +activity.

    + +

    Using intents

    + +

    Intents are the preferred mechanism for asynchronous IPC in Android. +Depending on your application requirements, you might use sendBroadcast(), +sendOrderedBroadcast(), +or direct an intent to a specific application component.

    + +

    Note that ordered broadcasts can be “consumed” by a recipient, so they +may not be delivered to all applications. If you are sending an Intent where +delivery to a specific receiver is required, the intent must be delivered +directly to the receiver.

    + +

    Senders of an intent can verify that the recipient has a permission +specifying a non-Null Permission upon sending. Only applications with that +Permission will receive the intent. If data within a broadcast intent may be +sensitive, you should consider applying a permission to make sure that +malicious applications cannot register to receive those messages without +appropriate permissions. In those circumstances, you may also consider +invoking the receiver directly, rather than raising a broadcast.

    + +

    Using binder and AIDL interfaces

    + +

    Binders are the +preferred mechanism for RPC-style IPC in Android. They provide a well-defined +interface that enables mutual authentication of the endpoints, if required.

    + +

    We strongly encourage designing interfaces in a manner that does not require +interface specific permission checks. Binders are not declared within the +application manifest, and therefore you cannot apply declarative permissions +directly to a Binder. Binders generally inherit permissions declared in the +application manifest for the Service or Activity within which they are +implemented. If you are creating an interface that requires authentication +and/or access controls on a specific binder interface, those controls must be +explicitly added as code in the interface.

    + +

    If providing an interface that does require access controls, use checkCallingPermission() +to verify whether the +caller of the Binder has a required permission. This is especially important +before accessing a Service on behalf of the caller, as the identify of your +application is passed to other interfaces. If invoking an interface provided +by a Service, the bindService() + invocation may fail if you do not have permission to access the given Service. + If calling an interface provided locally by your own application, it may be +useful to use the +clearCallingIdentity() to satisfy internal security checks.

    + +

    Using broadcast receivers

    + +

    Broadcast receivers are used to handle asynchronous requests initiated via +an intent.

    + +

    By default, receivers are exported and can be invoked by any other +application. If your +BroadcastReceivers is intended for use by other applications, you +may want to apply security permissions to receivers using the +<receiver> element within the application manifest. This will +prevent applications without appropriate permissions from sending an intent to +the +BroadcastReceivers.

    + +

    Using Services

    + +

    Services are often used to supply functionality for other applications to +use. Each service class must have a corresponding declaration in its +package's AndroidManifest.xml.

    + +

    By default, Services are exported and can be invoked by any other +application. Services can be protected using the {@code android:permission} +attribute +within the manifest’s +<service> tag. By doing so, other applications will need to declare +a corresponding <uses-permission> + element in their own manifest to be +able to start, stop, or bind to the service.

    + +

    A Service can protect individual IPC calls into it with permissions, by +calling checkCallingPermission() +before executing +the implementation of that call. We generally recommend using the +declarative permissions in the manifest, since those are less prone to +oversight.

    + +

    Using Activities

    + +

    Activities are most often used for providing the core user-facing +functionality of an application. By default, Activities are exported and +invokable by other applications only if they have an intent filter or binder +declared. In general, we recommend that you specifically declare a Receiver or +Service to handle IPC, since this modular approach reduces the risk of exposing +functionality that is not intended for use by other applications.

    + +

    If you do expose an Activity for purposes of IPC, the android:permission +attribute in the +<activity> declaration in the application manifest can be used to +restrict access to only those applications which have the stated permissions.

    -

    A particular permission may be enforced at a number of places during your -program's operation:

    + +

    Using Permissions

    +

    Requesting Permissions

    + +

    We recommend minimizing the number of permissions requested by an +application. Not having access to sensitive permissions reduces the risk of +inadvertently misusing those permissions, can improve user adoption, and makes +applications less attractive targets for attackers.

    + +

    If it is possible to design your application in a way that does not require +a permission, that is preferable. For example, rather than requesting access +to device information to create an identifier, create a GUID for your application. +(This specific example is also discussed in Handling User Data) Or, rather than +using external storage, store data in your application directory.

    + +

    If a permission is not required, do not request it. This sounds simple, but +there has been quite a bit of research into the frequency of over-requesting +permissions. If you’re interested in the subject you might start with this +research paper published by U.C. Berkeley: +http://www.eecs.berkeley.edu/Pubs/TechRpts/2011/EECS-2011-48.pdf

    + +

    In addition to requesting permissions, your application can use permissions +to protect IPC that is security sensitive and will be exposed to other +applications -- such as a +ContentProvider. In general, we recommend using access controls +other than user confirmed permissions where possible since permissions can +be confusing for users. For example, consider using the signature +protection level on permissions for IPC communication between applications +provided by a single developer.

    + +

    Do not cause permission re-delegation. This occurs when an app exposes data +over IPC that is only available because it has a specific permission, but does +not require that permission of any clients of it’s IPC interface. More +details on the potential impacts, and frequency of this type of problem is +provided in this research paper published at USENIX: http://www.cs.be +rkeley.edu/~afelt/felt_usenixsec2011.pdf

    + +

    Creating Permissions

    + +

    Generally, you should strive to create as few permissions as possible while +satisfying your security requirements. Creating a new permission is relatively +uncommon for most applications, since system-defined +permissions cover many situations. Where appropriate, +perform access checks using existing permissions.

    + +

    If you must create a new permission, consider whether you can accomplish +your task with a Signature permission. Signature permissions are transparent +to the user and only allow access by applications signed by the same developer +as application performing the permission check. If you create a Dangerous +permission, then the user needs to decide whether to install the application. +This can be confusing for other developers, as well as for users.

    + +

    If you create a Dangerous permission, there are a number of complexities +that you need to consider.

      -
    • At the time of a call into the system, to prevent an application from -executing certain functions.
    • -
    • When starting an activity, to prevent applications from launching -activities of other applications.
    • -
    • Both sending and receiving broadcasts, to control who can receive -your broadcast or who can send a broadcast to you.
    • -
    • When accessing and operating on a content provider.
    • -
    • Binding to or starting a service.
    • -
    - - - -

    Declaring and Enforcing Permissions

    - -

    To enforce your own permissions, you must first declare them in your -AndroidManifest.xml using one or more -{@link android.R.styleable#AndroidManifestPermission <permission>} -tags.

    - -

    For example, an application that wants to control who can start one -of its activities could declare a permission for this operation as follows:

    - -
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    -    package="com.me.app.myapp" >
    -    <permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"
    -        android:label="@string/permlab_deadlyActivity"
    -        android:description="@string/permdesc_deadlyActivity"
    -        android:permissionGroup="android.permission-group.COST_MONEY"
    -        android:protectionLevel="dangerous" />
    -    ...
    -</manifest>
    - -

    The {@link android.R.styleable#AndroidManifestPermission_protectionLevel -<protectionLevel>} attribute is required, telling the system how the -user is to be informed of applications requiring the permission, or who is -allowed to hold that permission, as described in the linked documentation.

    - -

    The {@link android.R.styleable#AndroidManifestPermission_permissionGroup -<permissionGroup>} attribute is optional, and only used to help the system display -permissions to the user. You will usually want to set this to either a standard -system group (listed in {@link android.Manifest.permission_group -android.Manifest.permission_group}) or in more rare cases to one defined by -yourself. It is preferred to use an existing group, as this simplifies the -permission UI shown to the user.

    - -

    Note that both a label and description should be supplied for the -permission. These are string resources that can be displayed to the user when -they are viewing a list of permissions -({@link android.R.styleable#AndroidManifestPermission_label android:label}) -or details on a single permission ( -{@link android.R.styleable#AndroidManifestPermission_description android:description}). -The label should be short, a few words -describing the key piece of functionality the permission is protecting. The -description should be a couple sentences describing what the permission allows -a holder to do. Our convention for the description is two sentences, the first -describing the permission, the second warning the user of what bad things -can happen if an application is granted the permission.

    - -

    Here is an example of a label and description for the CALL_PHONE -permission:

    - -
    -    <string name="permlab_callPhone">directly call phone numbers</string>
    -    <string name="permdesc_callPhone">Allows the application to call
    -        phone numbers without your intervention. Malicious applications may
    -        cause unexpected calls on your phone bill. Note that this does not
    -        allow the application to call emergency numbers.</string>
    -
    - -

    You can look at the permissions currently defined in the system with the -Settings app and the shell command adb shell pm list permissions. -To use the Settings app, go to Settings > Applications. Pick an app and -scroll down to see the permissions that the app uses. For developers, the adb '-s' -option displays the permissions in a form similar to how the user will see them:

    - -
    -$ adb shell pm list permissions -s
    -All Permissions:
    -
    -Network communication: view Wi-Fi state, create Bluetooth connections, full
    -Internet access, view network state
    -
    -Your location: access extra location provider commands, fine (GPS) location,
    -mock location sources for testing, coarse (network-based) location
    -
    -Services that cost you money: send SMS messages, directly call phone numbers
    -
    -...
    - - -

    Enforcing Permissions in AndroidManifest.xml

    - -

    High-level permissions restricting access to entire components of the -system or application can be applied through your -AndroidManifest.xml. All that this requires is including an {@link -android.R.attr#permission android:permission} attribute on the desired -component, naming the permission that will be used to control access to -it.

    - -

    {@link android.app.Activity} permissions -(applied to the -{@link android.R.styleable#AndroidManifestActivity <activity>} tag) -restrict who can start the associated -activity. The permission is checked during -{@link android.content.Context#startActivity Context.startActivity()} and -{@link android.app.Activity#startActivityForResult Activity.startActivityForResult()}; -if the caller does not have -the required permission then {@link java.lang.SecurityException} is thrown -from the call.

    - -

    {@link android.app.Service} permissions -(applied to the -{@link android.R.styleable#AndroidManifestService <service>} tag) -restrict who can start or bind to the -associated service. The permission is checked during -{@link android.content.Context#startService Context.startService()}, -{@link android.content.Context#stopService Context.stopService()} and -{@link android.content.Context#bindService Context.bindService()}; -if the caller does not have -the required permission then {@link java.lang.SecurityException} is thrown -from the call.

    - -

    {@link android.content.BroadcastReceiver} permissions -(applied to the -{@link android.R.styleable#AndroidManifestReceiver <receiver>} tag) -restrict who can send broadcasts to the associated receiver. -The permission is checked after -{@link android.content.Context#sendBroadcast Context.sendBroadcast()} returns, -as the system tries -to deliver the submitted broadcast to the given receiver. As a result, a -permission failure will not result in an exception being thrown back to the -caller; it will just not deliver the intent. In the same way, a permission -can be supplied to -{@link android.content.Context#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter, String, android.os.Handler) -Context.registerReceiver()} -to control who can broadcast to a programmatically registered receiver. -Going the other way, a permission can be supplied when calling -{@link android.content.Context#sendBroadcast(Intent, String) Context.sendBroadcast()} -to restrict which BroadcastReceiver objects are allowed to receive the broadcast (see -below).

    - -

    {@link android.content.ContentProvider} permissions -(applied to the -{@link android.R.styleable#AndroidManifestProvider <provider>} tag) -restrict who can access the data in -a {@link android.content.ContentProvider}. (Content providers have an important -additional security facility available to them called -URI permissions which is described later.) -Unlike the other components, -there are two separate permission attributes you can set: -{@link android.R.attr#readPermission android:readPermission} restricts who -can read from the provider, and -{@link android.R.attr#writePermission android:writePermission} restricts -who can write to it. Note that if a provider is protected with both a read -and write permission, holding only the write permission does not mean -you can read from a provider. The permissions are checked when you first -retrieve a provider (if you don't have either permission, a SecurityException -will be thrown), and as you perform operations on the provider. Using -{@link android.content.ContentResolver#query ContentResolver.query()} requires -holding the read permission; using -{@link android.content.ContentResolver#insert ContentResolver.insert()}, -{@link android.content.ContentResolver#update ContentResolver.update()}, -{@link android.content.ContentResolver#delete ContentResolver.delete()} -requires the write permission. -In all of these cases, not holding the required permission results in a -{@link java.lang.SecurityException} being thrown from the call.

    - - - -

    Enforcing Permissions when Sending Broadcasts

    - -

    In addition to the permission enforcing who can send Intents to a -registered {@link android.content.BroadcastReceiver} (as described above), you -can also specify a required permission when sending a broadcast. By calling {@link -android.content.Context#sendBroadcast(android.content.Intent,String) -Context.sendBroadcast()} with a -permission string, you require that a receiver's application must hold that -permission in order to receive your broadcast.

    - -

    Note that both a receiver and a broadcaster can require a permission. When -this happens, both permission checks must pass for the Intent to be delivered -to the associated target.

    - - - -

    Other Permission Enforcement

    - -

    Arbitrarily fine-grained permissions can be enforced at any call into a -service. This is accomplished with the {@link -android.content.Context#checkCallingPermission Context.checkCallingPermission()} -method. Call with a desired -permission string and it will return an integer indicating whether that -permission has been granted to the current calling process. Note that this can -only be used when you are executing a call coming in from another process, -usually through an IDL interface published from a service or in some other way -given to another process.

    - -

    There are a number of other useful ways to check permissions. If you have -the pid of another process, you can use the Context method {@link -android.content.Context#checkPermission(String, int, int) Context.checkPermission(String, int, int)} -to check a permission against that pid. If you have the package name of another -application, you can use the direct PackageManager method {@link -android.content.pm.PackageManager#checkPermission(String, String) -PackageManager.checkPermission(String, String)} -to find out whether that particular package has been granted a specific permission.

    - - - -

    URI Permissions

    - -

    The standard permission system described so far is often not sufficient -when used with content providers. A content provider may want to -protect itself with read and write permissions, while its direct clients -also need to hand specific URIs to other applications for them to operate on. -A typical example is attachments in a mail application. Access to the mail -should be protected by permissions, since this is sensitive user data. However, -if a URI to an image attachment is given to an image viewer, that image viewer -will not have permission to open the attachment since it has no reason to hold -a permission to access all e-mail.

    - -

    The solution to this problem is per-URI permissions: when starting an -activity or returning a result to an activity, the caller can set -{@link android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION -Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or -{@link android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION -Intent.FLAG_GRANT_WRITE_URI_PERMISSION}. This grants the receiving activity -permission access the specific data URI in the Intent, regardless of whether -it has any permission to access data in the content provider corresponding -to the Intent.

    - -

    This mechanism allows a common capability-style model where user interaction -(opening an attachment, selecting a contact from a list, etc) drives ad-hoc -granting of fine-grained permission. This can be a key facility for reducing -the permissions needed by applications to only those directly related to their -behavior.

    - -

    The granting of fine-grained URI permissions does, however, require some -cooperation with the content provider holding those URIs. It is strongly -recommended that content providers implement this facility, and declare that -they support it through the -{@link android.R.styleable#AndroidManifestProvider_grantUriPermissions -android:grantUriPermissions} attribute or -{@link android.R.styleable#AndroidManifestGrantUriPermission -<grant-uri-permissions>} tag.

    - -

    More information can be found in the -{@link android.content.Context#grantUriPermission Context.grantUriPermission()}, -{@link android.content.Context#revokeUriPermission Context.revokeUriPermission()}, and -{@link android.content.Context#checkUriPermission Context.checkUriPermission()} -methods.

    - +
  • The permission must have a string that concisely expresses to a user the +security decision they will be required to make.
  • +
  • The permission string must be localized to many different languages.
  • +
  • Uses may choose not to install an application because a permission is +confusing or perceived as risky.
  • +
  • Applications may request the permission when the creator of the permission +has not been installed.
  • +

    + +

    Each of these poses a significant non-technical challenge for an application +developer, which is why we discourage the use of Dangerous permission.

    + + +

    Using Networking

    + +

    Using IP Networking

    + +

    Networking on Android is not significantly different from Linux +environments. The key consideration is making sure that appropriate protocols +are used for sensitive data, such as HTTPS for +web traffic. We prefer use of HTTPS over HTTP anywhere that HTTPS is +supported on the server, since mobile devices frequently connect on networks +that are not secured, such as public WiFi hotspots.

    + +

    Authenticated, encrypted socket-level communication can be easily +implemented using the SSLSocket +class. Given the frequency with which Android devices connect to unsecured +wireless networks using WiFi, the use of secure networking is strongly +encouraged for all applications.

    + +

    We have seen some applications use localhost network ports for +handling sensitive IPC. We discourage this approach since these interfaces are +accessible by other applications on the device. Instead, use an Android IPC +mechanism where authentication is possible such as a Service and Binder. (Even +worse than using loopback is to bind to INADDR_ANY since then your application +may receive requests from anywhere. We’ve seen that, too.)

    + +

    Also, one common issue that warrants repeating is to make sure that you do +not trust data downloaded from HTTP or other insecure protocols. This includes +validation of input in WebView and +any responses to intents issued against HTTP.

    + +

    Using Telephony Networking

    + +

    SMS is the telephony protocol most frequently used by Android developers. +Developers should keep in mind that this protocol was primarily designed for +user-to-user communication and is not well-suited for some application +purposes. Due to the limitations of SMS, we strongly recommend the use of C2DM and IP networking for +sending data messages to devices.

    + +

    Many developers do not realize that SMS is not encrypted or strongly +authenticated on the network or on the device. In particular, any SMS receiver +should expect that a malicious user may have sent the SMS to your application +-- do not rely on unauthenticated SMS data to perform sensitive commands. +Also, you should be aware that SMS may be subject to spoofing and/or +interception on the network. On the Android-powered device itself, SMS +messages are transmitted as Broadcast intents, so they may be read or captured +by other applications that have the READ_SMS permission.

    + + +

    Dynamically Loading Code

    + +

    We strongly discourage loading code from outside of the application APK. +Doing so significantly increases the likelihood of application compromise due +to code injection or code tampering. It also adds complexity around version +management and application testing. Finally, it can make it impossible to +verify the behavior of an application, so it may be prohibited in some +environments.

    + +

    If your application does dynamically load code, the most important thing to +keep in mind about dynamically loaded code is that it runs with the same +security permissions as the application APK. The user made a decision to +install your application based on your identity, and they are expecting that +you provide any code run within the application, including code that is +dynamically loaded.

    + +

    The major security risk associated with dynamically loading code is that the +code needs to come from a verifiable source. If the modules are included +directly within your APK, then they cannot be modified by other applications. +This is true whether the code is a native library or a class being loaded using + +DexClassLoader. We have seen many instances of applications +attempting to load code from insecure locations, such as downloaded from the +network over unencrypted protocols or from world writable locations such as +external storage. These locations could allow someone on the network to modify +the content in transit, or another application on a users device to modify the +content, respectively.

    + + +

    Using WebView

    + +

    Since WebView consumes web content that can include HTML and JavaScript, +improper use can introduce common web security issues such as cross-site-scripting (JavaScript injection). Android includes a number of mechanisms to reduce +the scope of these potential issues by limiting the capability of WebView to +the minimum functionality required by your application.

    + +

    If your application does not directly use JavaScript within a WebView, do +not call + +setJavaScriptEnabled(). We have seen this method invoked +in sample code that might be repurposed in production application -- so +remove it if necessary. By default, WebView does +not execute JavaScript so cross-site-scripting is not possible.

    + +

    Use addJavaScriptInterface() with +particular care because it allows JavaScript to invoke operations that are +normally reserved for Android applications. Only expose addJavaScriptInterface() to +sources from which all input is trustworthy. If untrusted input is allowed, +untrusted JavaScript may be able to invoke Android methods. In general, we +recommend only exposing addJavaScriptInterface() to +JavaScript that is contained within your application APK.

    + +

    Do not trust information downloaded over HTTP, use HTTPS instead. Even if +you are connecting only to a single website that you trust or control, HTTP is +subject to MiTM attacks +and interception of data. Sensitive capabilities using addJavaScriptInterface() should +not ever be exposed to unverified script downloaded over HTTP. Note that even +with the use of HTTPS, +addJavaScriptInterface() +increases the attack surface of your application to include the server +infrastructure and all CAs trusted by the Android-powered device.

    + +

    If your application accesses sensitive data with a WebView, you +may want to use the +clearCache() method to delete any files stored locally. Server side +headers like no-cache can also be used to indicate that an application should +not cache particular content.

    + + +

    Performing Input Validation

    + +

    Insufficient input validation is one of the most common security problems +affecting applications, regardless of what platform they run on. Android does +have platform-level countermeasures that reduce the exposure of applications to +input validation issues, you should use those features where possible. Also +note that selection of type-safe languages tends to reduce the likelihood of +input validation issues. We strongly recommend building your applications with +the Android SDK.

    + +

    If you are using native code, then any data read from files, received over +the network, or received from an IPC has the potential to introduce a security +issue. The most common problems are buffer overflows, use after +free, and off-by-one errors. +Android provides a number of technologies like ASLR and DEP that reduce the +exploitability of these errors, but they do not solve the underlying problem. +These can be prevented by careful handling of pointers and managing of +buffers.

    + +

    Dynamic, string based languages such as JavaScript and SQL are also subject +to input validation problems due to escape characters and script injection.

    + +

    If you are using data within queries that are submitted to SQL Database or a +Content Provider, SQL Injection may be an issue. The best defense is to use +parameterized queries, as is discussed in the ContentProviders section. +Limiting permissions to read-only or write-only can also reduce the potential +for harm related to SQL Injection.

    + +

    If you are using WebView, then +you must consider the possibility of XSS. If your application does not +directly use JavaScript within a WebView, do +not call setJavaScriptEnabled() and XSS is no longer possible. If you must +enable JavaScript then the WebView section provides other security best +practices.

    + +

    If you cannot use the security features above, we strongly recommend the use +of well-structured data formats and verifying that the data conforms to the +expected format. While blacklisting of characters or character-replacement can +be an effective strategy, these techniques are error-prone in practice and +should be avoided when possible.

    + + +

    Handling User Data

    + +

    In general, the best approach is to minimize use of APIs that access +sensitive or personal user data. If you have access to data and can avoid +storing or transmitting the information, do not store or transmit the data. +Finally, consider if there is a way that your application logic can be +implemented using a hash or non-reversible form of the data. For example, your +application might use the hash of an an email address as a primary key, to +avoid transmitting or storing the email address. This reduces the chances of +inadvertently exposing data, and it also reduces the chance of attackers +attempting to exploit your application.

    + +

    If your application accesses personal information such as passwords or +usernames, keep in mind that some jurisdictions may require you to provide a +privacy policy explaining your use and storage of that data. So following the +security best practice of minimizing access to user data may also simplify +compliance.

    + +

    You should also consider whether your application might be inadvertently +exposing personal information to other parties such as third-party components +for advertising or third-party services used by your application. If you don't +know why a component or service requires a personal information, don’t +provide it. In general, reducing the access to personal information by your +application will reduce the potential for problems in this area.

    + +

    If access to sensitive data is required, evaluate whether that information +must be transmitted to a server, or whether the operation can be performed on +the client. Consider running any code using sensitive data on the client to +avoid transmitting user data.

    + +

    Also, make sure that you do not inadvertently expose user data to other +application on the device through overly permissive IPC, world writable files, +or network sockets. This is a special case of permission redelegation, +discussed in the Requesting Permissions section.

    + +

    If a GUID is required, create a large, unique number and store it. Do not +use phone identifiers such as the phone number or IMEI which may be associated +with personal information. This topic is discussed in more detail in the Android Developer Blog.

    + +

    Application developers should be careful writing to on-device logs. +In Android, logs are a shared resource, and are available +to an application with the + +READ_LOGS permission. Even though the phone log data +is temporary and erased on reboot, inappropriate logging of user information +could inadvertently leak user data to other applications.

    + + +

    Handling Credentials

    + +

    In general, we recommend minimizing the frequency of asking for user +credentials -- to make phishing attacks more conspicuous, and less likely to be +successful. Instead use an authorization token and refresh it.

    + +

    Where possible, username and password should not be stored on the device. +Instead, perform initial authentication using the username and password +supplied by the user, and then use a short-lived, service-specific +authorization token.

    + +

    Services that will be accessible to multiple applications should be accessed +using + +AccountManager. If possible, use the +AccountManager class to invoke a cloud-based service and do not store +passwords on the device.

    + +

    After using +AccountManager to retrieve an Account, check the CREATOR + before passing in any credentials, so that you do not inadvertently pass +credentials to the wrong application.

    + +

    If credentials are to be used only by applications that you create, then you +can verify the application which accesses the +AccountManager using checkSignature(). +Alternatively, if only one application will use the credential, you might use a +KeyStore for +storage.

    + + +

    Using Cryptography

    + +

    In addition to providing data isolation, supporting full-filesystem +encryption, and providing secure communications channels Android provides a +wide array of algorithms for protecting data using cryptography.

    + +

    In general, try to use the highest level of pre-existing framework +implementation that can support your use case. If you need to securely +retrieve a file from a known location, a simple HTTPS URI may be adequate and +require no knowledge of cryptography on your part. If you need a secure +tunnel, consider using + +HttpsURLConnection or SSLSocket, +rather than writing your own protocol.

    + +

    If you do find yourself needing to implement your own protocol, we strongly +recommend that you not implement your own cryptographic algorithms. Use +existing cryptographic algorithms such as those in the implementation of AES or +RSA provided in the Cipher class.

    + +

    Use a secure random number generator ( + +SecureRandom) to initialize any cryptographic keys ( +KeyGenerator). Use of a key that is not generated with a secure random +number generator significantly weakens the strength of the algorithm, and may +allow offline attacks.

    + +

    If you need to store a key for repeated use, use a mechanism like KeyStore that +provides a mechanism for long term storage and retrieval of cryptographic +keys.

    + +

    Conclusion

    + +

    Android provides developers with the ability to design applications with a +broad range of security requirements. These best practices will help you make +sure that your application takes advantage of the security benefits provided by +the platform.

    + +

    You can receive more information on these topics and discuss security best +practices with other developers in the Android Security +Discuss Google Group

    diff --git a/docs/html/guide/topics/sensors/index.jd b/docs/html/guide/topics/sensors/index.jd index 43903dcf735a..a0458994d36d 100644 --- a/docs/html/guide/topics/sensors/index.jd +++ b/docs/html/guide/topics/sensors/index.jd @@ -1,88 +1,40 @@ -page.title=Sensors -@jd:body - -
    -
    -

    Topics

    -
      -
    1. Sensors Overview
    2. -
    3. Motion Sensors
    4. -
    5. Position - Sensors
    6. -
    7. Environment - Sensors
    8. -
    -

    Key classes and interfaces

    -
      -
    1. {@link android.hardware.Sensor}
    2. -
    3. {@link android.hardware.SensorEvent}
    4. -
    5. {@link android.hardware.SensorManager}
    6. -
    7. {@link android.hardware.SensorEventListener}
    8. -
    -

    Related samples

    -
      -
    1. Accelerometer - Play
    2. -
    3. -API Demos (OS - RotationVectorDemo)
    4. -
    5. API Demos -(OS - Sensors)
    6. -
    -
    -
    +page.title=Location and Sensors +page.landing=true +page.landing.intro=Use sensors on the device to add rich location and motion capabilities to your app, from GPS or network location to accelerometer, gyroscope, temperature, barometer, and more. +page.landing.image= -

    Most Android-powered devices have built-in sensors that measure motion, orientation, -and various environmental conditions. These sensors are capable of providing raw data with high -precision and accuracy, and are useful if you want to monitor three-dimensional device movement or -positioning, or you want to monitor changes in the ambient environment near a device. For example, a -game might track readings from a device's gravity sensor to infer complex user gestures -and motions, such as tilt, shake, rotation, or swing. Likewise, a weather application might use a -device's temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel -application might use the geomagnetic field sensor and accelerometer to report a compass -bearing.

    +@jd:body -

    The Android platform supports three broad categories of sensors:

    +
    -
      -
    • Motion sensors -

      These sensors measure acceleration forces and rotational forces along three axes. This - category includes accelerometers, gravity sensors, gyroscopes, and rotational vector - sensors.

      -
    • -
    • Environmental sensors -

      These sensors measure various environmental parameters, such as ambient air temperature - and pressure, illumination, and humidity. This category includes barometers, photometers, and - thermometers.

      -
    • -
    • Position sensors -

      These sensors measure the physical position of a device. This category includes - orientation sensors and magnetometers.

      -
    • -
    + -

    To access these sensors, you can use the Android sensor framework. The sensor framework provides -several classes and interfaces that help you perform a wide variety of sensor-related tasks. To -learn more about the framework and the sensors that are supported on the Android system, read the -following documents:

    + -
    -
    Sensors - Overview
    -
    Learn how to list the sensors that are on a device, set up sensor event listeners, and - acquire sensor data. Also learn best practices for accessing and using sensors.
    -
    Motion - Sensors
    -
    Learn how to use the sensors that provide acceleration data, such as the accelerometer, - gravity sensor, and linear acceleration sensor. Also learn how to use the sensors that - provide rotational data, such as gyroscopes and rotational vector sensors.
    -
    Position - Sensors
    -
    Learn how to use the sensors that provide orientation and compass data, such as the - orientation sensor and the geomagnetic field sensor.
    -
    Environment - Sensors
    -
    Learn how to use the sensors that provide environmental data, such as the light, - humidity, pressure, temperature, and proximity sensors.
    -
    +
    \ No newline at end of file diff --git a/docs/html/guide/topics/sensors/sensors_overview.jd b/docs/html/guide/topics/sensors/sensors_overview.jd index 543872ce57fb..e38a8430a878 100644 --- a/docs/html/guide/topics/sensors/sensors_overview.jd +++ b/docs/html/guide/topics/sensors/sensors_overview.jd @@ -50,13 +50,39 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/os/Senso -

    Most Android-powered devices have sensors that let you monitor changes in device -position and motion. Many devices also have sensors that let you determine ambient environmental -conditions, such as temperature, pressure, humidity, and lighting. You can access these -sensors and acquire raw sensor data by using the Android sensor framework.

    +

    Most Android-powered devices have built-in sensors that measure motion, orientation, +and various environmental conditions. These sensors are capable of providing raw data with high +precision and accuracy, and are useful if you want to monitor three-dimensional device movement or +positioning, or you want to monitor changes in the ambient environment near a device. For example, a +game might track readings from a device's gravity sensor to infer complex user gestures +and motions, such as tilt, shake, rotation, or swing. Likewise, a weather application might use a +device's temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel +application might use the geomagnetic field sensor and accelerometer to report a compass +bearing.

    + +

    The Android platform supports three broad categories of sensors:

    -

    The sensor framework provides several classes and interfaces that help you perform a wide variety -of sensor-related tasks. For example, you can use the sensor framework to do the following:

    + + + +

    You can access sensors available on the device and acquire raw sensor data by using the Android +sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide +variety of sensor-related tasks. For example, you can use the sensor framework to do the following:

    - +

    Figure 1. Action bar from the Honeycomb Gallery app (on a landscape handset), showing the logo on the left, navigation tabs, and an action item on the @@ -510,7 +503,7 @@ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

    For more information about these flags and other back stack behaviors, read the Tasks and Back Stack +href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack developer guide.

    Note: If you're using the icon to navigate to the home @@ -955,7 +948,7 @@ when the screen is too narrow, as shown in figures 9 and 10.

    To switch between fragments using the tabs, you must perform a fragment transaction each time a tab is selected. If you're not familiar with how to change fragments using {@link android.app.FragmentTransaction}, first read the Fragments developer guide.

    +href="{@docRoot}guide/components/fragments.html">Fragments developer guide.

    To get started, your layout must include a {@link android.view.ViewGroup} in which you place each {@link android.app.Fragment} associated with a tab. Be sure the {@link android.view.ViewGroup} has a @@ -1092,7 +1085,7 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/Frag

    If your activity stops, you should retain the currently selected tab with the saved instance +href="{@docRoot}guide/components/activities.html#SavingActivityState">saved instance state so you can open the appropriate tab when the user returns. When it's time to save the state, you can query the currently selected tab with {@link android.app.ActionBar#getSelectedNavigationIndex()}. This returns the index position of the selected @@ -1101,7 +1094,7 @@ tab.

    Caution: It's important that you save the state of each fragment as necessary, so that when users switch fragments with the tabs and then return to a previous fragment, it looks the way it did when they left. For information about saving the state of your -fragment, see the Fragments +fragment, see the Fragments developer guide.

    diff --git a/docs/html/guide/topics/ui/binding.jd b/docs/html/guide/topics/ui/binding.jd index 26364ee8e4c9..e8b49d553ebc 100644 --- a/docs/html/guide/topics/ui/binding.jd +++ b/docs/html/guide/topics/ui/binding.jd @@ -1,4 +1,4 @@ -page.title=Binding to Data with AdapterView +page.title=AdapterView parent.title=User Interface parent.link=index.html @jd:body @@ -20,32 +20,7 @@ parent.link=index.html -

    The {@link android.widget.AdapterView} is a ViewGroup subclass whose child Views are determined by an {@link android.widget.Adapter Adapter} that -binds to data of some type. AdapterView is useful whenever you need to display stored data (as opposed to resource strings or drawables) in your layout.

    -

    {@link android.widget.Gallery Gallery}, {@link android.widget.ListView ListView}, and {@link android.widget.Spinner Spinner} are examples of AdapterView subclasses that you can use to bind to a specific type of data and display it in a certain way.

    - - -

    AdapterView objects have two main responsibilities:

    -
      -
    • Filling the layout with data -
    • -
    • Handling user selections -
    • -
    - - -

    Filling the Layout with Data

    -

    Inserting data into the layout is typically done by binding the AdapterView class to an {@link -android.widget.Adapter}, which retrieves data from an external source (perhaps a list that -the code supplies or query results from the device's database).

    -

    The following code sample does the following:

    -
      -
    1. Creates a {@link android.widget.Spinner Spinner} with an existing View and binds it to a new ArrayAdapter -that reads an array of colors from the local resources.
    2. -
    3. Creates another Spinner object from a View and binds it to a new SimpleCursorAdapter that will read -people's names from the device contacts (see {@link android.provider.Contacts.People}).
    4. -
     // Get a Spinner and bind it to an ArrayAdapter that 
    diff --git a/docs/html/guide/topics/ui/controls.jd b/docs/html/guide/topics/ui/controls.jd
    new file mode 100644
    index 000000000000..83bb0c8e64fa
    --- /dev/null
    +++ b/docs/html/guide/topics/ui/controls.jd
    @@ -0,0 +1,92 @@
    +page.title=Input Controls
    +parent.title=User Interface
    +parent.link=index.html
    +@jd:body
    +
    +
    + +
    + +

    Input controls are the interactive components in your app's user interface. Android provides a +wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, +checkboxes, zoom buttons, toggle buttons, and many more.

    + +

    Adding an input control to your UI is as simple as adding an XML element to your XML layout. For example, here's a +layout with a text field and button:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent"
    +    android:orientation="horizontal">
    +    <EditText android:id="@+id/edit_message"
    +        android:layout_weight="1"
    +        android:layout_width="0dp"
    +        android:layout_height="wrap_content"
    +        android:hint="@string/edit_message" />
    +    <Button android:id="@+id/button_send"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:text="@string/button_send"
    +        android:onClick="sendMessage" />
    +</LinearLayout>
    +
    + +

    Each input control supports a specific set of input events so you can handle events such as when +the user enters text or touches a button.

    + + +

    Common Controls

    +

    Here's a list of some common controls that you can use in your app. Follow the links to learn +more about using each one.

    + +

    Note: Android provides several more controls than are listed +here. Browse the {@link android.widget} package to discover more. If your app requires a +specific kind of input control, you can build your own custom components.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Control TypeDescriptionRelated Classes
    ButtonA push-button that can be pressed, or clicked, by the user to perform an action.{@link android.widget.Button Button}
    Text fieldAn editable text field. You can use the AutoCompleteTextView widget to create a text entry widget that provides auto-complete suggestions{@link android.widget.EditText EditText}, {@link android.widget.AutoCompleteTextView}
    CheckboxAn on/off switch that can be toggled by the user. You should use checkboxes when presenting users with a group of selectable options that are not mutually exclusive.{@link android.widget.CheckBox CheckBox}
    Radio buttonSimilar to checkboxes, except that only one option can be selected in the group.{@link android.widget.RadioGroup RadioGroup} +
    {@link android.widget.RadioButton RadioButton}
    Toggle buttonAn on/off button with a light indicator.{@link android.widget.ToggleButton ToggleButton}
    SpinnerA drop-down list that allows users to select one value from a set.{@link android.widget.Spinner Spinner}
    PickersA dialog for users to select a single value for a set by using up/down buttons or via a swipe gesture. Use a DatePickercode> widget to enter the values for the date (month, day, year) or a TimePicker widget to enter the values for a time (hour, minute, AM/PM), which will be formatted automatically for the user's locale.{@link android.widget.DatePicker}, {@link android.widget.TimePicker}
    diff --git a/docs/html/guide/topics/ui/controls/button.jd b/docs/html/guide/topics/ui/controls/button.jd new file mode 100644 index 000000000000..8d48e9cb5dac --- /dev/null +++ b/docs/html/guide/topics/ui/controls/button.jd @@ -0,0 +1,245 @@ +page.title=Buttons +parent.title=Input Controls +parent.link=../controls.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. Responding to Click Events +
        +
      1. Using an OnClickListener
      2. +
      +
    2. +
    3. Styling Your Button +
        +
      1. Borderless button
      2. +
      3. Custom background
      4. +
      +
    4. +
    +

    Key classes

    +
      +
    1. {@link android.widget.Button}
    2. +
    3. {@link android.widget.ImageButton}
    4. +
    +
    +
    + + +

    A button consists of text or an icon (or both text and an icon) that communicates what action +occurs when the user touches it.

    + + + +

    Depending on whether you want a button with text, an icon, or both, you can create the +button in your layout in three ways:

    +
      +
    • With text, using the {@link android.widget.Button} class: +
      +<Button
      +    android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
      +    android:text="@string/button_text"
      +    ... />
      +
      +
    • +
    • With an icon, using the {@link android.widget.ImageButton} class: +
      +<ImageButton
      +    android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
      +    android:src="@drawable/button_icon"
      +    ... />
      +
      +
    • +
    • With text and an icon, using the {@link android.widget.Button} class with the {@code +android:drawableLeft} attribute: +
      +<Button
      +    android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
      +    android:text="@string/button_text"
      +    android:drawableLeft="@drawable/button_icon"
      +    ... />
      +
      +
    • +
    + +

    Responding to Click Events

    + +

    When the user clicks a button, the {@link android.widget.Button} object receives +an on-click event.

    + +

    To define the click event handler for a button, add the {@link +android.R.attr#onClick android:onClick} attribute to the {@code <Button>} element in your XML +layout. The value for this attribute must be the name of the method you want to call in response +to a click event. The {@link android.app.Activity} hosting the layout must then implement the +corresponding method.

    + +

    For example, here's a layout with a button using {@link +android.R.attr#onClick android:onClick}:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<Button xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:id="@+id/button_send"
    +    android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
    +    android:text="@string/button_send"
    +    android:onClick="sendMessage" />
    +
    + +

    Within the {@link android.app.Activity} that hosts this layout, the following method handles +the click event:

    + +
    +/** Called when the user touches the button */
    +public void sendMessage(View view) {
    +    // Do something in response to button click
    +}
    +
    + +

    The method you declare in the {@link android.R.attr#onClick android:onClick} attribute must have +a signature exactly as shown above. Specifically, the method must:

    +
      +
    • Be public
    • +
    • Return void
    • +
    • Define a {@link android.view.View} as its only parameter (this will be the {@link +android.view.View} that was clicked)
    • +
    + + +

    Using an OnClickListener

    + +

    You can also declare the click event handler pragmatically rather than in an XML layout. This +might be necessary if you instantiate the {@link android.widget.Button} at runtime or you need to +declare the click behavior in a {@link android.app.Fragment} subclass.

    + +

    To declare the event handler programmatically, create an {@link +android.view.View.OnClickListener} object and assign it to the button by calling {@link +android.view.View#setOnClickListener}. For example:

    + +
    +Button button = (Button) findViewById(R.id.button_send);
    +button.setOnClickListener(new View.OnClickListener() {
    +    public void onClick(View v) {
    +        // Do something in response to button click
    +    }
    +});
    +
    + + +

    Styling Your Button

    + +

    The appearance of your button (background image and font) may vary from one device to +another, because devices by different manufacturers often have different default styles for +input controls.

    + +

    You can control exactly how your controls are styled using a theme that you apply to your +entire application. For instance, to ensure that all devices running Android 4.0 and higher use +the Holo theme in your app, declare {@code android:theme="@android:style/Theme.Holo"} in your +manifest's {@code <application>} element. Also read the blog post, Holo Everywhere +for information about using the Holo theme while supporting older devices.

    + +

    To customize individual buttons with a different background, specify the {@link +android.R.attr#background android:background} attribute with a drawable or color resource. +Alternatively, you can apply a style for the button, which works in a manner similar to +HTML styles to define multiple style properties such as the background, font, size, and others. +For more information about applying styles, see Styles and Themes.

    + + +

    Borderless button

    + +

    One design that can be useful is a "borderless" button. Borderless buttons resemble +basic buttons except that they have no borders or background but still change appearance during +different states, such as when clicked.

    + +

    To create a borderless button, apply the {@link android.R.attr#borderlessButtonStyle} +style to the button. For example:

    + +
    +<Button
    +    android:id="@+id/button_send"
    +    android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
    +    android:text="@string/button_send"
    +    android:onClick="sendMessage"
    +    style="?android:attr/borderlessButtonStyle" />
    +
    + + + +

    Custom background

    + +

    If you want to truly redefine the appearance of your button, you can specify a custom +background. Instead of supplying a simple bitmap or color, however, your background should be a +state list resource that changes appearance depending on the button's current state.

    + +

    You can define the state list in an XML file that defines three different images or colors to use +for the different button states.

    + +

    To create a state list drawable for your button background:

    + +
      +
    1. Create three bitmaps for the button background that represent the default, pressed, and +focused button states. +

      To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.

      +
    2. +
    3. Place the bitmaps into the res/drawable/ directory of +your project. Be sure each bitmap is named properly to reflect the button state that they each +represent, such as {@code button_default.9.png}, {@code button_pressed.9.png}, and {@code +button_focused.9.png}.
    4. +
    5. Create a new XML file in the res/drawable/ directory (name it something like +button_custom.xml). Insert the following XML: +
      +<?xml version="1.0" encoding="utf-8"?>
      +<selector xmlns:android="http://schemas.android.com/apk/res/android">
      +    <item android:drawable="@drawable/button_pressed"
      +          android:state_pressed="true" />
      +    <item android:drawable="@drawable/button_focused"
      +          android:state_focused="true" />
      +    <item android:drawable="@drawable/button_default" />
      +</selector>
      +
      +

      This defines a single drawable resource, which will change its image based on the current +state of the button.

      +
        +
      • The first <item> defines the bitmap to use when the button is +pressed (activated).
      • +
      • The second <item> defines the bitmap to use when the button is +focused (when the button is highlighted using the trackball or directional +pad).
      • +
      • The third <item> defines the bitmap to use when the button is in the +default state (it's neither pressed nor focused).
      • +
      +

      Note: The order of the <item> elements is +important. When this drawable is referenced, the <item> elements are traversed +in-order to determine which one is appropriate for the current button state. Because the default +bitmap is last, it is only applied when the conditions android:state_pressed and +android:state_focused have both evaluated as false.

      +

      This XML file now represents a single +drawable resource and when referenced by a {@link android.widget.Button} for its background, +the image displayed will change based on these three states.

      +
    6. +
    7. Then simply apply the drawable XML file as the button background: +
      +<Button
      +    android:id="@+id/button_send"
      +    android:layout_width="wrap_content"
      +    android:layout_height="wrap_content"
      +    android:text="@string/button_send"
      +    android:onClick="sendMessage"
      +    android:background="@drawable/button_custom"  />
      +
      +
    + +

    For more information about this XML syntax, including how to define a disabled, hovered, or +other button states, read about State List +Drawable.

    \ No newline at end of file diff --git a/docs/html/guide/topics/ui/controls/checkbox.jd b/docs/html/guide/topics/ui/controls/checkbox.jd new file mode 100644 index 000000000000..35b8f560b15c --- /dev/null +++ b/docs/html/guide/topics/ui/controls/checkbox.jd @@ -0,0 +1,101 @@ +page.title=Checkboxes +parent.title=Input Controls +parent.link=../controls.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. Responding to Click Events
    2. +
    + +

    Key classes

    +
      +
    1. {@link android.widget.CheckBox}
    2. +
    +
    +
    + +

    Checkboxes allow the user to select one or more options from a set. Typically, you should +present each checkbox option in a vertical list.

    + + + +

    To create each checkbox option, create a {@link android.widget.CheckBox} in your layout. Because +a set of checkbox options allows the user to select multiple items, each checkbox is managed +separately and you must register a click listener for each one.

    + +

    Responding to Click Events

    + +

    When the user selects a checkbox, the {@link android.widget.CheckBox} object receives an +on-click event.

    + +

    To define the click event handler for a checkbox, add the android:onClick attribute to the +<CheckBox> element in your XML +layout. The value for this attribute must be the name of the method you want to call in response +to a click event. The {@link android.app.Activity} hosting the layout must then implement the +corresponding method.

    + +

    For example, here are a couple {@link android.widget.CheckBox} objects in a list:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:orientation="vertical"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent">
    +    <CheckBox android:id="@+id/checkbox_meat"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:text="@string/meat"
    +        android:onClick="onCheckboxClicked"/>
    +    <CheckBox android:id="@+id/checkbox_cheese"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:text="@string/cheese"
    +        android:onClick="onCheckboxClicked"/>
    +</LinearLayout>
    +
    + +

    Within the {@link android.app.Activity} that hosts this layout, the following method handles the +click event for both checkboxes:

    + +
    +public void onCheckboxClicked(View view) {
    +    // Is the view now checked?
    +    boolean checked = (CheckBox) view).isChecked();
    +    
    +    // Check which checkbox was clicked
    +    switch(view.getId()) {
    +        case R.id.checkbox_meat:
    +            if (checked)
    +                // Put some meat on the sandwich
    +            else
    +                // Remove the meat
    +            break;
    +        case R.id.checkbox_cheese:
    +            if (checked)
    +                // Cheese me
    +            else
    +                // I'm lactose intolerant
    +            break;
    +        // TODO: Veggie sandwich
    +    }
    +}
    +
    + +

    The method you declare in the {@link android.R.attr#onClick android:onClick} attribute +must have a signature exactly as shown above. Specifically, the method must:

    +
      +
    • Be public
    • +
    • Return void
    • +
    • Define a {@link android.view.View} as its only parameter (this will be the {@link +android.view.View} that was clicked)
    • +
    + +

    Tip: If you need to change the radio button state +yourself (such as when loading a saved {@link android.preference.CheckBoxPreference}), +use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link +android.widget.CompoundButton#toggle()} method.

    \ No newline at end of file diff --git a/docs/html/guide/topics/ui/controls/pickers.jd b/docs/html/guide/topics/ui/controls/pickers.jd new file mode 100644 index 000000000000..cf90f1d6d482 --- /dev/null +++ b/docs/html/guide/topics/ui/controls/pickers.jd @@ -0,0 +1,259 @@ +page.title= Pickers +parent.title=Form Controls +parent.link=controls-form.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. Creating a Time Picker +
        +
      1. Extending DialogFragment for a time picker
      2. +
      3. Showing the time picker
      4. +
      +
    2. +
    3. Creating a Date Picker +
        +
      1. Extending DialogFragment for a date picker
      2. +
      3. Showing the date picker
      4. +
      +
    4. +
    +

    Key classes

    +
      +
    1. {@link android.app.DatePickerDialog}
    2. +
    3. {@link android.app.TimePickerDialog}
    4. +
    5. {@link android.support.v4.app.DialogFragment}
    6. +
    +

    See also

    +
      +
    1. Fragments
    2. +
    +
    +
    + +

    Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs. +Each picker provides controls for selecting each part of the time (hour, minute, AM/PM) or date +(month, day, year). Using these pickers helps ensure that your users can pick a time or date that +is valid, formatted correctly, and adjusted to the user's locale.

    + + + +

    We recommend that you use {@link android.support.v4.app.DialogFragment} to host each time or date +picker. The {@link android.support.v4.app.DialogFragment} manages the dialog lifecycle for you and +allows you to display the pickers in different layout configurations, +such as in a basic dialog on handsets or as an embedded part of the layout on large screens.

    + +

    Although {@link android.app.DialogFragment} was first added to the platform in Android 3.0 (API +level 11), if your app supports versions of Android older than 3.0—even as low as Android +1.6—you can use the {@link android.support.v4.app.DialogFragment} class that's available in +the support library for backward +compatibility.

    + +

    Note: The code samples below show how to create dialogs for a time +picker and date picker using the support +library APIs for {@link android.support.v4.app.DialogFragment}. If your app's {@code minSdkVersion} is 11 or +higher, you can instead use the platform version of {@link android.app.DialogFragment}.

    + + + +

    Creating a Time Picker

    + +

    To display a {@link android.app.TimePickerDialog} using {@link +android.support.v4.app.DialogFragment}, you need to define a fragment class that extends {@link +android.support.v4.app.DialogFragment} and return a {@link android.app.TimePickerDialog} from the +fragment's {@link android.support.v4.app.DialogFragment#onCreateDialog onCreateDialog()} method.

    + +

    Note: If your app supports versions of Android older than 3.0, +be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a +Library.

    + +

    Extending DialogFragment for a time picker

    + +

    To define a {@link +android.support.v4.app.DialogFragment} for a {@link android.app.TimePickerDialog}, you +must:

    +
      +
    • Define the {@link android.support.v4.app.DialogFragment#onCreateDialog onCreateDialog()} +method to return an instance of {@link android.app.TimePickerDialog}
    • +
    • Implement the +{@link android.app.TimePickerDialog.OnTimeSetListener} interface to receive a callback when the user +sets the time.
    • +
    + +

    Here's an example:

    + +
    +public static class TimePickerFragment extends DialogFragment
    +                            implements TimePickerDialog.OnTimeSetListener {
    +
    +    @Override
    +    public Dialog onCreateDialog(Bundle savedInstanceState) {
    +        // Use the current time as the default values for the picker
    +        final Calendar c = Calendar.getInstance();
    +        int hour = c.get(Calendar.HOUR_OF_DAY);
    +        int minute = c.get(Calendar.MINUTE);
    +
    +        // Create a new instance of TimePickerDialog and return it
    +        return new TimePickerDialog(getActivity(), this, hour, minute,
    +                DateFormat.is24HourFormat(getActivity()));
    +    }
    +
    +    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    +        // Do something with the time chosen by the user
    +    }
    +}
    +
    + +

    See the {@link android.app.TimePickerDialog} class for information about the constructor +arguments.

    + +

    Now all you need is an event that adds an instance of this fragment to your activity.

    + + +

    Showing the time picker

    + +

    Once you've defined a {@link android.support.v4.app.DialogFragment} like the one shown above, +you can display the time picker by creating an instance of the {@link +android.support.v4.app.DialogFragment} and calling {@link +android.support.v4.app.DialogFragment#show show()}.

    + +

    For example, here's a button that, when clicked, calls a method to show the dialog:

    + +
    +<Button 
    +    android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content"
    +    android:text="@string/pick_time" 
    +    android:onClick="showTimePickerDialog" />
    +
    + +

    When the user clicks this button, the system calls the following method:

    + +
    +public void showTimePickerDialog(View v) {
    +    DialogFragment newFragment = new TimePickerFragment();
    +    newFragment.show(getSupportFragmentManager(), "timePicker");
    +}
    +
    + +

    This method calls {@link +android.support.v4.app.DialogFragment#show show()} on a new instance of the {@link +android.support.v4.app.DialogFragment} defined above. The {@link +android.support.v4.app.DialogFragment#show show()} method requires an instance of {@link +android.support.v4.app.FragmentManager} and a unique tag name for the fragment.

    + +

    Caution: If your app supports versions of Android lower than +3.0, be sure that you call {@link +android.support.v4.app.FragmentActivity#getSupportFragmentManager()} to acquire an instance of +{@link android.support.v4.app.FragmentManager}. Also make sure that your activity that displays the +time picker extends {@link android.support.v4.app.FragmentActivity} instead of the standard {@link +android.app.Activity} class.

    + + + + + + + + + +

    Creating a Date Picker

    + +

    Creating a {@link android.app.DatePickerDialog} is just like creating a {@link +android.app.TimePickerDialog}. The only difference is the dialog you create for the fragment.

    + +

    To display a {@link android.app.DatePickerDialog} using {@link +android.support.v4.app.DialogFragment}, you need to define a fragment class that extends {@link +android.support.v4.app.DialogFragment} and return a {@link android.app.DatePickerDialog} from the +fragment's {@link android.support.v4.app.DialogFragment#onCreateDialog onCreateDialog()} method.

    + +

    Note: If your app supports versions of Android older than 3.0, +be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a +Library.

    + +

    Extending DialogFragment for a date picker

    + +

    To define a {@link +android.support.v4.app.DialogFragment} for a {@link android.app.DatePickerDialog}, you +must:

    +
      +
    • Define the {@link android.support.v4.app.DialogFragment#onCreateDialog onCreateDialog()} +method to return an instance of {@link android.app.DatePickerDialog}
    • +
    • Implement the +{@link android.app.DatePickerDialog.OnDateSetListener} interface to receive a callback when the user +sets the date.
    • +
    + +

    Here's an example:

    + +
    +public static class DatePickerFragment extends DialogFragment
    +                            implements DatePickerDialog.OnDateSetListener {
    +
    +    @Override
    +    public Dialog onCreateDialog(Bundle savedInstanceState) {
    +        // Use the current date as the default date in the picker
    +        final Calendar c = Calendar.getInstance();
    +        int year = c.get(Calendar.YEAR);
    +        int month = c.get(Calendar.MONTH);
    +        int day = c.get(Calendar.DAY_OF_MONTH);
    +
    +        // Create a new instance of DatePickerDialog and return it
    +        return new DatePickerDialog(getActivity(), this, year, month, day);
    +    }
    +
    +    public void onDateSet(DatePicker view, int year, int month, int day) {
    +        // Do something with the date chosen by the user
    +    }
    +}
    +
    + +

    See the {@link android.app.DatePickerDialog} class for information about the constructor +arguments.

    + +

    Now all you need is an event that adds an instance of this fragment to your activity.

    + + +

    Showing the date picker

    + +

    Once you've defined a {@link android.support.v4.app.DialogFragment} like the one shown above, +you can display the date picker by creating an instance of the {@link +android.support.v4.app.DialogFragment} and calling {@link +android.support.v4.app.DialogFragment#show show()}.

    + +

    For example, here's a button that, when clicked, calls a method to show the dialog:

    + +
    +<Button 
    +    android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content"
    +    android:text="@string/pick_date" 
    +    android:onClick="showDatePickerDialog" />
    +
    + +

    When the user clicks this button, the system calls the following method:

    + +
    +public void showDatePickerDialog(View v) {
    +    DialogFragment newFragment = new DatePickerFragment();
    +    newFragment.show(getSupportFragmentManager(), "datePicker");
    +}
    +
    + +

    This method calls {@link +android.support.v4.app.DialogFragment#show show()} on a new instance of the {@link +android.support.v4.app.DialogFragment} defined above. The {@link +android.support.v4.app.DialogFragment#show show()} method requires an instance of {@link +android.support.v4.app.FragmentManager} and a unique tag name for the fragment.

    + +

    Caution: If your app supports versions of Android lower than +3.0, be sure that you call {@link +android.support.v4.app.FragmentActivity#getSupportFragmentManager()} to acquire an instance of +{@link android.support.v4.app.FragmentManager}. Also make sure that your activity that displays the +time picker extends {@link android.support.v4.app.FragmentActivity} instead of the standard {@link +android.app.Activity} class.

    diff --git a/docs/html/guide/topics/ui/controls/radiobutton.jd b/docs/html/guide/topics/ui/controls/radiobutton.jd new file mode 100644 index 000000000000..f6f6d49f7294 --- /dev/null +++ b/docs/html/guide/topics/ui/controls/radiobutton.jd @@ -0,0 +1,103 @@ +page.title=Radio Buttons +parent.title=Input Controls +parent.link=../controls.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. Responding to Click Events
    2. +
    + +

    Key classes

    +
      +
    1. {@link android.widget.RadioButton}
    2. +
    3. {@link android.widget.RadioGroup}
    4. +
    +
    +
    + +

    Radio buttons allow the user to select one option from a set. You should use radio buttons for +optional sets that are mutually exclusive if you think that the user needs to see all available +options side-by-side. If it's not necessary to show all options side-by-side, use a spinner instead.

    + + + +

    To create each radio button option, create a {@link android.widget.RadioButton} in your layout. +However, because radio buttons are mutually exclusive, you must group them together inside a +{@link android.widget.RadioGroup}. By grouping them together, the system ensures that only one +radio button can be selected at a time.

    + +

    Responding to Click Events

    + +

    When the user selects one of the radio buttons, the corresponding {@link +android.widget.RadioButton} object receives an on-click event.

    + +

    To define the click event handler for a button, add the android:onClick attribute to the +<RadioButton> element in your XML +layout. The value for this attribute must be the name of the method you want to call in response +to a click event. The {@link android.app.Activity} hosting the layout must then implement the +corresponding method.

    + +

    For example, here are a couple {@link android.widget.RadioButton} objects:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="fill_parent"
    +    android:layout_height="wrap_content"
    +    android:orientation="vertical">
    +    <RadioButton android:id="@+id/radio_pirates"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:text="@string/pirates"
    +        android:onClick="onRadioButtonClicked"/>
    +    <RadioButton android:id="@+id/radio_ninjas"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:text="@string/ninjas"
    +        android:onClick="onRadioButtonClicked"/>
    +</RadioGroup>
    +
    + +

    Note: The {@link android.widget.RadioGroup} is a subclass of +{@link android.widget.LinearLayout} that has a vertical orientation by default.

    + +

    Within the {@link android.app.Activity} that hosts this layout, the following method handles the +click event for both radio buttons:

    + +
    +public void onRadioButtonClicked(View view) {
    +    // Is the button now checked?
    +    boolean checked = (RadioButton) view).isChecked();
    +    
    +    // Check which radio button was clicked
    +    switch(view.getId()) {
    +        case R.id.radio_pirates:
    +            if (checked)
    +                // Pirates are the best
    +            break;
    +        case R.id.radio_ninjas:
    +            if (checked)
    +                // Ninjas rule
    +            break;
    +    }
    +}
    +
    + +

    The method you declare in the {@link android.R.attr#onClick android:onClick} attribute +must have a signature exactly as shown above. Specifically, the method must:

    +
      +
    • Be public
    • +
    • Return void
    • +
    • Define a {@link android.view.View} as its only parameter (this will be the {@link +android.view.View} that was clicked)
    • +
    + +

    Tip: If you need to change the radio button state +yourself (such as when loading a saved {@link android.preference.CheckBoxPreference}), +use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link +android.widget.CompoundButton#toggle()} method.

    diff --git a/docs/html/guide/topics/ui/controls/spinner.jd b/docs/html/guide/topics/ui/controls/spinner.jd new file mode 100644 index 000000000000..deba3e609469 --- /dev/null +++ b/docs/html/guide/topics/ui/controls/spinner.jd @@ -0,0 +1,147 @@ +page.title= Spinners +parent.title=Input Controls +parent.link=../controls.html +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. Populate the Spinner with User Choices
    2. +
    3. Responding to User Selections
    4. +
    +

    Key classes

    +
      +
    1. {@link android.widget.Spinner}
    2. +
    3. {@link android.widget.SpinnerAdapter}
    4. +
    5. {@link android.widget.AdapterView.OnItemSelectedListener}
    6. +
    + +
    +
    + +

    Spinners provide a quick way to select one value from a set. In the default state, a spinner +shows its currently selected value. Touching the spinner displays a dropdown menu with all other +available values, from which the user can select a new one.

    + + + +

    You can add a spinner to your layout with the {@link android.widget.Spinner} object. You +should usually do so in your XML layout with a {@code <Spinner>} element. For example:

    + +
    +<Spinner
    +    android:id="@+id/planets_spinner"
    +    android:layout_width="fill_parent"
    +    android:layout_height="wrap_content" />
    +
    + +

    To populate the spinner with a list of choices, you then need to specify a {@link +android.widget.SpinnerAdapter} in your {@link android.app.Activity} or {@link android.app.Fragment} +source code.

    + +

    Populate the Spinner with User Choices

    + +

    The choices you provide for the spinner can come from any source, but must be provided through +an {@link android.widget.SpinnerAdapter}, such as an {@link android.widget.ArrayAdapter} if the +choices are available in an array or a {@link android.widget.CursorAdapter} if the choices are +available from a database query.

    + +

    For instance, if the available choices for your spinner are pre-determined, you can provide +them with a string array defined in a string +resource file:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<resources>
    +    <string-array name="planets_array">
    +        <item>Mercury</item>
    +        <item>Venus</item>
    +        <item>Earth</item>
    +        <item>Mars</item>
    +        <item>Jupiter</item>
    +        <item>Saturn</item>
    +        <item>Uranus</item>
    +        <item>Neptune</item>
    +    </string-array>
    +</resources>
    +
    + +

    With an array such as this one, you can use the following code in your {@link +android.app.Activity} or {@link android.app.Fragment} to supply the spinner with the array using +an instance of {@link android.widget.ArrayAdapter}: + +

    +Spinner spinner = (Spinner) findViewById(R.id.spinner);
    +// Create an ArrayAdapter using the string array and a default spinner layout
    +ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
    +        R.array.planets_array, android.R.layout.simple_spinner_item);
    +// Specify the layout to use when the list of choices appears
    +adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    +// Apply the adapter to the spinner
    +spinner.setAdapter(adapter);
    +
    + +

    The {@link +android.widget.ArrayAdapter#createFromResource(Context,int,int) createFromResource()} method allows +you to create an {@link android.widget.ArrayAdapter} from the string array. The third argument for +this method is a layout resource that defines how the selected choice appears in the +spinner control. The {@link android.R.layout#simple_spinner_item} layout is provided by the +platform and is the default layout you should use unless you'd like to define your own layout +for the spinner's appearance.

    + +

    You should then call {@link android.widget.ArrayAdapter#setDropDownViewResource(int)} to specify +the layout the adapter should use to display the list of spinner choices ({@link +android.R.layout#simple_spinner_dropdown_item} is another standard layout defined by the +platform).

    + +

    Call {@link android.widget.AdapterView#setAdapter setAdapter()} to apply the adapter to your +{@link android.widget.Spinner}.

    + + +

    Responding to User Selections

    + +

    When the user selects an item from the drop-down, the {@link android.widget.Spinner} object +receives an on-item-selected event.

    + +

    To define the selection event handler for a spinner, implement the {@link +android.widget.AdapterView.OnItemSelectedListener} interface and the corresponding {@link +android.widget.AdapterView.OnItemSelectedListener#onItemSelected onItemSelected()} callback method. +For example, here's an implementation of the interface in an {@link android.app.Activity}:

    + +
    +public class SpinnerActivity extends Activity implements OnItemSelectedListener {
    +    ...
    +    
    +    public void onItemSelected(AdapterView<?> parent, View view, 
    +            int pos, long id) {
    +        // An item was selected. You can retrieve the selected item using
    +        // parent.getItemAtPosition(pos)
    +    }
    +
    +    public void onNothingSelected(AdapterView<?> parent) {
    +        // Another interface callback
    +    }
    +}
    +
    + +

    The {@link android.widget.AdapterView.OnItemSelectedListener} requires the {@link +android.widget.AdapterView.OnItemSelectedListener#onItemSelected(AdapterView,View,int,long) +onItemSelected()} and {@link +android.widget.AdapterView.OnItemSelectedListener#onNothingSelected(AdapterView) +onNothingSelected()} callback methods.

    + +

    Then you need to specify the interface implementation by calling {@link +android.widget.AdapterView#setOnItemSelectedListener setOnItemSelectedListener()}:

    + +
    +Spinner spinner = (Spinner) findViewById(R.id.spinner);
    +spinner.setOnItemSelectedListener(this);
    +
    + +

    If you implement the {@link +android.widget.AdapterView.OnItemSelectedListener} interface with your {@link +android.app.Activity} or {@link android.app.Fragment} (such as in the example above), you can pass +this as the interface instance.

    \ No newline at end of file diff --git a/docs/html/guide/topics/ui/controls/text.jd b/docs/html/guide/topics/ui/controls/text.jd new file mode 100644 index 000000000000..2d9d2158f1ad --- /dev/null +++ b/docs/html/guide/topics/ui/controls/text.jd @@ -0,0 +1,306 @@ +page.title=Text Fields +parent.title=Input Controls +parent.link=../controls.html +@jd:body + +
    +
    + +

    In this document

    +
      +
    1. Specifying the Keyboard Type +
        +
      1. Controlling other behaviors
      2. +
      +
    2. +
    3. Specifying Keyboard Actions +
        +
      1. Responding to action button events
      2. +
      3. Setting a custom action button label
      4. +
      +
    4. +
    5. Adding Other Keyboard Flags
    6. +
    7. Providing Auto-complete Suggestions
    8. +
    +

    Key classes

    +
      +
    1. {@link android.widget.EditText}
    2. +
    3. {@link android.widget.AutoCompleteTextView}
    4. +
    + +
    +
    + +

    A text field allows the user to type text into your app. It can be either single line or +multi-line. Touching a text field places the cursor and automatically displays the keyboard. In +addition to typing, text fields allow for a variety of other activities, such as text selection +(cut, copy, paste) and data look-up via auto-completion.

    + +

    You can add a text field to you layout with the {@link android.widget.EditText} object. You +should usually do so in your XML layout with a {@code <EditText>} element.

    + + + + + +

    Specifying the Keyboard Type

    + +
    + +

    Figure 1. The default {@code text} input type.

    +
    + +
    + +

    Figure 2. The {@code textEmailAddress} input type.

    +
    + +
    + +

    Figure 3. The {@code phone} input type.

    +
    + +

    Text fields can have different input types, such as number, date, password, or email address. The +type determines what kind of characters are allowed inside the field, and may prompt the virtual +keyboard to optimize its layout for frequently used characters.

    + +

    You can specify the type of keyboard you want for your {@link android.widget.EditText} object +with the {@code +android:inputType} attribute. For example, if you want the user to input an email address, you +should use the {@code textEmailAddress} input type:

    + +
    +<EditText
    +    android:id="@+id/email_address"
    +    android:layout_width="fill_parent"
    +    android:layout_height="wrap_content"
    +    android:hint="@string/email_hint"
    +    android:inputType="textEmailAddress" />
    +
    + + +

    There are several different input types available for different situations. You can find +them all listed with the documentation for {@code +android:inputType}.

    + +

    Tip: To allow users to input long strings of text with line +breaks, use the {@code "textMultiLine"} input type. By default, an {@link android.widget.EditText} +object is restricted to one line of text and scrolls horizontally when the text exceeds the +available width.

    + + +

    Controlling other behaviors

    + +

    The {@code +android:inputType} also allows you to specify certain keyboard behaviors, such as whether to +capitalize all new words or use features like auto-complete and spelling suggestions.

    + +

    The {@code +android:inputType} attribute allows bitwise combinations so you can specify both a keyboard +layout and one or more behaviors at once. For example, here's how you can collect a postal +address, capitalize each word, and disable text suggestions:

    + +
    +<EditText
    +    android:id="@+id/postal_address"
    +    android:layout_width="fill_parent"
    +    android:layout_height="wrap_content"
    +    android:hint="@string/postal_address_hint"
    +    android:inputType="textPostalAddress|
    +                       textCapWords|
    +                       textNoSuggestions" />
    +
    + +

    All behaviors are also listed with the {@code +android:inputType} documentation.

    + + +

    Specifying Keyboard Actions

    + +
    + +

    Figure 4. If you declare {@code +android:imeOptions="actionSend"}, the keyboard includes the Send action.

    +
    + +

    In addition to changing the keyboard's input type, Android allows you to specify an action to be +made when users have completed their input. The action specifies the button that appears in place of +the carriage return key and the action to be made, such as "Search" or "Send."

    + +

    You can specify the action by setting the {@code +android:imeOptions} attribute. For example, here's how you can specify the Send action:

    + +
    +<EditText
    +    android:id="@+id/search"
    +    android:layout_width="fill_parent"
    +    android:layout_height="wrap_content"
    +    android:hint="@string/search_hint"
    +    android:inputType="text"
    +    android:imeOptions="actionSend" />
    +
    + +

    If you do not explicitly specify an input action then the system attempts to determine if there +are any subsequent {@code +android:focusable} fields. If any focusable fields are found following this one, the system +applies the (@code actionNext} action to the current {@link android.widget.EditText} so the user can +select Next to move to the next field. If there's no subsequent focusable field, the system applies +the {@code "actionDone"} action. You can override this by setting the {@code +android:imeOptions} attribute to any other value such as {@code "actionSend"} or {@code +"actionSearch"} or suppress the default behavior by using the {@code "actionNone"} action.

    + + +

    Responding to action button events

    + +

    If you have specified a keyboard action for the input method using {@code +android:imeOptions} attribute (such as {@code "actionSend"}), you can listen for the specific +action event using an {@link android.widget.TextView.OnEditorActionListener}. The {@link +android.widget.TextView.OnEditorActionListener} interface provides a callback method called {@link +android.widget.TextView.OnEditorActionListener#onEditorAction onEditorAction()} that indicates the +action type invoked with an action ID such as {@link +android.view.inputmethod.EditorInfo#IME_ACTION_SEND} or {@link +android.view.inputmethod.EditorInfo#IME_ACTION_SEARCH}.

    + +

    For example, here's how you can listen for when the user clicks the Send button on the +keyboard:

    + +
    +EditText editText = (EditText) findViewById(R.id.search);
    +editText.setOnEditorActionListener(new OnEditorActionListener() {
    +    @Override
    +    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    +        boolean handled = false;
    +        if (actionId == EditorInfo.IME_ACTION_SEND) {
    +            // Send the user message
    +            handled = true;
    +        }
    +        return handled;
    +    }
    +});
    +
    + + +

    Setting a custom action button label

    + +

    If the keyboard is too large to reasonably share space with the underlying application (such as +when a handset device is in landscape orientation) then fullscreen ("extract mode") is triggered. In +this mode, a labeled action button is displayed next to the input. You can customize the text of +this button by setting the {@code +android:imeActionLabel} attribute:

    + +
    +<EditText
    +    android:id="@+id/launch_codes"
    +    android:layout_width="fill_parent"
    +    android:layout_height="wrap_content"
    +    android:hint="@string/enter_launch_codes"
    +    android:inputType="number"
    +    android:imeActionLabel="@string/launch" />
    +
    + + +

    Figure 5. A custom action label with {@code +android:imeActionLabel}.

    + + + +

    Adding Other Keyboard Flags

    + +

    In addition to the actions you can specify with the {@code +android:imeOptions} attribute, you can add additional flags to specify other keyboard +behaviors. All available flags are listed along with the actions in the {@code +android:imeOptions} documentation.

    + +

    For example, figure 5 shows how the system enables a fullscreen text field when a handset device +is in landscape orientation (or the screen space is otherwise constrained for space). You can +disable the fullscreen input mode with {@code flagNoExtractUi} in the {@code +android:imeOptions} attribute, as shown in figure 6.

    + + +

    Figure 6. The fullscreen text field ("extract mode") is +disabled with {@code android:imeOptions="flagNoExtractUi"}.

    + + + + +

    Providing Auto-complete Suggestions

    + +

    If you want to provide suggestions to users as they type, you can use a subclass of {@link +android.widget.EditText} called {@link android.widget.AutoCompleteTextView}. To implement +auto-complete, you must specify an (@link android.widget.Adapter) that provides the text +suggestions. There are several kinds of adapters available, depending on where the data is coming +from, such as from a database or an array.

    + + +

    Figure 7. Example of {@link +android.widget.AutoCompleteTextView} with text suggestions.

    + +

    The following procedure describes how to set up an {@link android.widget.AutoCompleteTextView} +that provides suggestions from an array, using {@link android.widget.ArrayAdapter}: + +

      +
    1. Add the {@link android.widget.AutoCompleteTextView} to your layout. Here's a +layout with only the text field: +
      +<?xml version="1.0" encoding="utf-8"?>
      +<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android" 
      +    android:id="@+id/autocomplete_country"
      +    android:layout_width="fill_parent"
      +    android:layout_height="wrap_content" />
      +
      +
    2. + +
    3. Define the array that contains all text suggestions. For example, here's an array of country +names that's defined in an XML resource file ({@code res/values/strings.xml}): +
      +<?xml version="1.0" encoding="utf-8"?>
      +<resources>
      +    <string-array name="countries_array">
      +        <item>Afghanistan</item>
      +        <item>Albania</item>
      +        <item>Algeria</item>
      +        <item>American Samoa</item>
      +        <item>Andorra</item>
      +        <item>Angola</item>
      +        <item>Anguilla</item>
      +        <item>Antarctica</item>
      +        ...
      +    </string-array>
      +</resources>
      +
      +
    4. + +
    5. In your {@link android.app.Activity} or {@link android.app.Fragment}, use the following +code to specify the adapter that supplies the suggestions: +
      +// Get a reference to the AutoCompleteTextView in the layout
      +AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
      +// Get the string array
      +String[] countries = getResources().getStringArray(R.array.countries_array);
      +// Create the adapter and set it to the AutoCompleteTextView 
      +ArrayAdapter<String> adapter = 
      +        new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
      +textView.setAdapter(adapter);
      +
      + +

      Here, a new {@link +android.widget.ArrayAdapter} is initialized to bind each item in the COUNTRIES +string array to a {@link android.widget.TextView} that exists in the {@code simple_list_item_1} +layout (this is a layout provided by Android that provides a standard appearance for text in a +list).

      +

      Then assign the adapter to the {@link android.widget.AutoCompleteTextView} by +calling {@link android.widget.AutoCompleteTextView#setAdapter setAdapter()}.

      +
    6. +
    + diff --git a/docs/html/guide/topics/ui/controls/togglebutton.jd b/docs/html/guide/topics/ui/controls/togglebutton.jd new file mode 100644 index 000000000000..dd7634be3e60 --- /dev/null +++ b/docs/html/guide/topics/ui/controls/togglebutton.jd @@ -0,0 +1,124 @@ +page.title=Toggle Buttons +parent.title=Input Controls +parent.link=../controls.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. Responding to Click Events +
        +
      1. Using an OnCheckedChangeListener
      2. +
      +
    2. +
    +

    Key classes

    +
      +
    1. {@link android.widget.ToggleButton}
    2. +
    3. {@link android.widget.Switch}
    4. +
    +
    +
    + +

    A toggle button allows the user to change a setting between two states.

    + +

    You can add a basic toggle button to your layout with the {@link android.widget.ToggleButton} +object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that +provides a slider control, which you can add with a {@link android.widget.Switch} object.

    + +
    + +

    Toggle buttons

    +
    + +
    + +

    Switches (in Android 4.0+)

    +
    + +

    The {@link android.widget.ToggleButton} and {@link android.widget.Switch} +controls are subclasses of {@link android.widget.CompoundButton} and function in the same manner, so +you can implement their behavior the same way.

    + +

    Responding to Click Events

    + +

    When the user selects a {@link android.widget.ToggleButton} and {@link android.widget.Switch}, +the object receives an on-click event.

    + +

    To define the click event handler, add the android:onClick attribute to the +<ToggleButton> or <Switch> element in your XML +layout. The value for this attribute must be the name of the method you want to call in response +to a click event. The {@link android.app.Activity} hosting the layout must then implement the +corresponding method.

    + +

    For example, here's a {@link android.widget.ToggleButton} with the android:onClick attribute:

    + +
    +<ToggleButton 
    +    android:id="@+id/togglebutton"
    +    android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
    +    android:textOn="Vibrate on"
    +    android:textOff="Vibrate off"
    +    android:onClick="onToggleClicked"/>
    +
    + +

    Within the {@link android.app.Activity} that hosts this layout, the following method handles the +click event:

    + +
    +public void onToggleClicked(View view) {
    +    // Is the toggle on?
    +    boolean on = ((ToggleButton) view).isChecked();
    +    
    +    if (on) {
    +        // Enable vibrate
    +    } else {
    +        // Disable vibrate
    +    }
    +}
    +
    + +

    The method you declare in the {@link android.R.attr#onClick android:onClick} attribute +must have a signature exactly as shown above. Specifically, the method must:

    +
      +
    • Be public
    • +
    • Return void
    • +
    • Define a {@link android.view.View} as its only parameter (this will be the {@link +android.view.View} that was clicked)
    • +
    + +

    Tip: If you need to change the state +yourself, +use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link +android.widget.CompoundButton#toggle()} method to change the state.

    + + + +

    Using an OnCheckedChangeListener

    + +

    You can also declare a click event handler pragmatically rather than in an XML layout. This +might be necessary if you instantiate the {@link android.widget.ToggleButton} or {@link +android.widget.Switch} at runtime or you need to +declare the click behavior in a {@link android.app.Fragment} subclass.

    + +

    To declare the event handler programmatically, create an {@link +android.widget.CompoundButton.OnCheckedChangeListener} object and assign it to the button by calling +{@link +android.widget.CompoundButton#setOnCheckedChangeListener}. For example:

    + +
    +ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
    +toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    +    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    +        if (isChecked) {
    +            // The toggle is enabled
    +        } else {
    +            // The toggle is disabled
    +        }
    +    }
    +});
    +
    diff --git a/docs/html/guide/topics/ui/declaring-layout.jd b/docs/html/guide/topics/ui/declaring-layout.jd index 8af4a1cd143e..3c9faa8b2cee 100644 --- a/docs/html/guide/topics/ui/declaring-layout.jd +++ b/docs/html/guide/topics/ui/declaring-layout.jd @@ -1,4 +1,4 @@ -page.title=XML Layouts +page.title=Layouts parent.title=User Interface parent.link=index.html @jd:body @@ -6,18 +6,25 @@ parent.link=index.html

    In this document

    -
      -
    1. Write the XML
    2. -
    3. Load the XML Resource
    4. -
    5. Attributes -
        -
      1. ID
      2. -
      3. Layout Parameters
      4. -
      -
    6. -
    7. Position
    8. -
    9. Size, Padding and Margins
    10. -
    +
      +
    1. Write the XML
    2. +
    3. Load the XML Resource
    4. +
    5. Attributes +
        +
      1. ID
      2. +
      3. Layout Parameters
      4. +
      +
    6. +
    7. Layout Position
    8. +
    9. Size, Padding and Margins
    10. +
    11. Common Layouts
    12. +
    13. Building Layouts with an Adapter +
        +
      1. Filling an adapter view with data
      2. +
      3. Handling click events
      4. +
      +
    14. +

    Key classes

      @@ -43,15 +50,15 @@ application can create View and ViewGroup objects (and manipulate their properti @@ -125,7 +132,7 @@ public void onCreate(Bundle savedInstanceState) {

      The onCreate() callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the -Activities +Activities document).

      @@ -300,5 +307,213 @@ Available Resources document.

      + + + + + + + + + +

      Common Layouts

      + +

      Each subclass of the {@link android.view.ViewGroup} class provides a unique way to display +the views you nest within it. Below are some of the more common layout types that are built +into the Android platform.

      + +

      Note: Although you can nest one or more layouts within another +layout to acheive your UI design, you should strive to keep your layout hierarchy as shallow as +possible. Your layout draws faster if it has fewer nested layouts (a wide view hierarchy is +better than a deep view hierarchy).

      + + + + +
      +

      Linear Layout

      + +

      A layout that organizes its children into a single horizontal or vertical row. It + creates a scrollbar if the length of the window exceeds the length of the screen.

      +
      + +
      +

      Relative Layout

      + +

      Enables you to specify the location of child objects relative to each other (child A to +the left of child B) or to the parent (aligned to the top of the parent).

      +
      + + + +
      +

      Web View

      + +

      Displays web pages.

      +
      + + + + +

      Building Layouts with an Adapter

      + +

      When the content for your layout is dynamic or not pre-determined, you can use a layout that +subclasses {@link android.widget.AdapterView} to populate the layout with views at runtime. A +subclass of the {@link android.widget.AdapterView} class uses an {@link android.widget.Adapter} to +bind data to its layout. The {@link android.widget.Adapter} behaves as a middle-man between the data +source and the {@link android.widget.AdapterView} layout—the {@link android.widget.Adapter} +retreives the data (from a source such as an array or a database query) and converts each entry +into a view that can be added into the {@link android.widget.AdapterView} layout.

      + +

      Common layouts backed by an adapter include:

      + +
      +

      List View

      + +

      Displays a scrolling single column list.

      +
      + +
      +

      Grid View

      + +

      Displays a scrolling grid of columns and rows.

      +
      + + + +

      Filling an adapter view with data

      + +

      You can populate an {@link android.widget.AdapterView} such as {@link android.widget.ListView} or +{@link android.widget.GridView} by binding the {@link android.widget.AdapterView} instance to an +{@link android.widget.Adapter}, which retrieves data from an external source and creates a {@link +android.view.View} that represents each data entry.

      + +

      Android provides several subclasses of {@link android.widget.Adapter} that are useful for +retrieving different kinds of data and building views for an {@link android.widget.AdapterView}. The +two most common adapters are:

      + +
      +
      {@link android.widget.ArrayAdapter}
      +
      Use this adapter when your data source is an array. By default, {@link +android.widget.ArrayAdapter} creates a view for each array item by calling {@link +java.lang.Object#toString()} on each item and placing the contents in a {@link +android.widget.TextView}. +

      For example, if you have an array of strings you want to display in a {@link +android.widget.ListView}, initialize a new {@link android.widget.ArrayAdapter} using a +constructor to specify the layout for each string and the string array:

      +
      +ArrayAdapter adapter = new ArrayAdapter<String>(this, 
      +        android.R.layout.simple_list_item_1, myStringArray);
      +
      +

      The arguments for this constructor are:

      +
        +
      • Your app {@link android.content.Context}
      • +
      • The layout that contains a {@link android.widget.TextView} for each string in the array
      • +
      • The string array
      • +
      +

      Then simply call +{@link android.widget.ListView#setAdapter setAdapter()} on your {@link android.widget.ListView}:

      +
      +ListView listView = (ListView) findViewById(R.id.listview);
      +listView.setAdapter(adapter);
      +
      + +

      To customize the appearance of each item you can override the {@link +java.lang.Object#toString()} method for the objects in your array. Or, to create a view for each +item that's something other than a {@link android.widget.TextView} (for example, if you want an +{@link android.widget.ImageView} for each array item), extend the {@link +android.widget.ArrayAdapter} class and override {@link android.widget.ArrayAdapter#getView +getView()} to return the type of view you want for each item.

      + +
      + +
      {@link android.widget.SimpleCursorAdapter}
      +
      Use this adapter when your data comes from a {@link android.database.Cursor}. When +using {@link android.widget.SimpleCursorAdapter}, you must specify a layout to use for each +row in the {@link android.database.Cursor} and which columns in the {@link android.database.Cursor} +should be inserted into which views of the layout. For example, if you want to create a list of +people's names and phone numbers, you can perform a query that returns a {@link +android.database.Cursor} containing a row for each person and columns for the names and +numbers. You then create a string array specifying which columns from the {@link +android.database.Cursor} you want in the layout for each result and an integer array specifying the +corresponding views that each column should be placed:

      +
      +String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, 
      +                        ContactsContract.CommonDataKinds.Phone.NUMBER};
      +int[] toViews = {R.id.display_name, R.id.phone_number};
      +
      +

      When you instantiate the {@link android.widget.SimpleCursorAdapter}, pass the layout to use for +each result, the {@link android.database.Cursor} containing the results, and these two arrays:

      +
      +SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      +        R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
      +ListView listView = getListView();
      +listView.setAdapter(adapter);
      +
      +

      The {@link android.widget.SimpleCursorAdapter} then creates a view for each row in the +{@link android.database.Cursor} using the provided layout by inserting each {@code +fromColumns} item into the corresponding {@code toViews} view.

      .
      +
      + + +

      If, during the course of your application's life, you change the underlying data that is read by +your adapter, you should call {@link android.widget.ArrayAdapter#notifyDataSetChanged()}. This will +notify the attached view that the data has been changed and it should refresh itself.

      + + + +

      Handling click events

      + +

      You can respond to click events on each item in an {@link android.widget.AdapterView} by +implementing the {@link android.widget.AdapterView.OnItemClickListener} interface. For example:

      + +
      +// Create a message handling object as an anonymous class.
      +private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
      +    public void onItemClick(AdapterView parent, View v, int position, long id) {
      +        // Do something in response to the click
      +    }
      +};
      +
      +listView.setOnItemClickListener(mMessageClickedHandler); 
      +
      + diff --git a/docs/html/guide/topics/ui/dialogs.jd b/docs/html/guide/topics/ui/dialogs.jd index 82cbfd161b6b..9c2805817288 100644 --- a/docs/html/guide/topics/ui/dialogs.jd +++ b/docs/html/guide/topics/ui/dialogs.jd @@ -313,7 +313,7 @@ Activity, the selection is lost.

      Note: To save the selection when the user leaves or pauses the Activity, you must properly save and restore the setting throughout -the activity lifecycle. +the activity lifecycle. To permanently save the selections, even when the Activity process is completely shutdown, you need to save the settings with one of the Data diff --git a/docs/html/guide/topics/ui/images/android_focused.png b/docs/html/guide/topics/ui/images/android_focused.png new file mode 100644 index 000000000000..f84d0fe4a5e4 Binary files /dev/null and b/docs/html/guide/topics/ui/images/android_focused.png differ diff --git a/docs/html/guide/topics/ui/images/android_normal.png b/docs/html/guide/topics/ui/images/android_normal.png new file mode 100644 index 000000000000..94a708425300 Binary files /dev/null and b/docs/html/guide/topics/ui/images/android_normal.png differ diff --git a/docs/html/guide/topics/ui/images/android_pressed.png b/docs/html/guide/topics/ui/images/android_pressed.png new file mode 100644 index 000000000000..fe81ff9e279c Binary files /dev/null and b/docs/html/guide/topics/ui/images/android_pressed.png differ diff --git a/docs/html/guide/topics/ui/images/hello-gallery.png b/docs/html/guide/topics/ui/images/hello-gallery.png new file mode 100755 index 000000000000..22d1eaf6d145 Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-gallery.png differ diff --git a/docs/html/guide/topics/ui/images/hello-gridview.png b/docs/html/guide/topics/ui/images/hello-gridview.png new file mode 100755 index 000000000000..2def0df666a4 Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-gridview.png differ diff --git a/docs/html/guide/topics/ui/images/hello-linearlayout.png b/docs/html/guide/topics/ui/images/hello-linearlayout.png new file mode 100755 index 000000000000..dfef819ef9d1 Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-linearlayout.png differ diff --git a/docs/html/guide/topics/ui/images/hello-listview.png b/docs/html/guide/topics/ui/images/hello-listview.png new file mode 100644 index 000000000000..165b1ac69725 Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-listview.png differ diff --git a/docs/html/guide/topics/ui/images/hello-mapview.png b/docs/html/guide/topics/ui/images/hello-mapview.png new file mode 100644 index 000000000000..6bd97400c29b Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-mapview.png differ diff --git a/docs/html/guide/topics/ui/images/hello-relativelayout.png b/docs/html/guide/topics/ui/images/hello-relativelayout.png new file mode 100755 index 000000000000..ec4d9d44b0c6 Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-relativelayout.png differ diff --git a/docs/html/guide/topics/ui/images/hello-tablelayout.png b/docs/html/guide/topics/ui/images/hello-tablelayout.png new file mode 100755 index 000000000000..3d80e7f8a55a Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-tablelayout.png differ diff --git a/docs/html/guide/topics/ui/images/hello-tabwidget.png b/docs/html/guide/topics/ui/images/hello-tabwidget.png new file mode 100644 index 000000000000..6580c5b067ff Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-tabwidget.png differ diff --git a/docs/html/guide/topics/ui/images/hello-webview.png b/docs/html/guide/topics/ui/images/hello-webview.png new file mode 100644 index 000000000000..248c6d4d1ff5 Binary files /dev/null and b/docs/html/guide/topics/ui/images/hello-webview.png differ diff --git a/docs/html/guide/topics/ui/images/ic_tab_artists_grey.png b/docs/html/guide/topics/ui/images/ic_tab_artists_grey.png new file mode 100644 index 000000000000..9baa30eac584 Binary files /dev/null and b/docs/html/guide/topics/ui/images/ic_tab_artists_grey.png differ diff --git a/docs/html/guide/topics/ui/images/ic_tab_artists_white.png b/docs/html/guide/topics/ui/images/ic_tab_artists_white.png new file mode 100644 index 000000000000..3b010d536ade Binary files /dev/null and b/docs/html/guide/topics/ui/images/ic_tab_artists_white.png differ diff --git a/docs/html/guide/topics/ui/index.jd b/docs/html/guide/topics/ui/index.jd index be07249a4e1e..f342b0652f5b 100644 --- a/docs/html/guide/topics/ui/index.jd +++ b/docs/html/guide/topics/ui/index.jd @@ -1,236 +1,61 @@ page.title=User Interface -@jd:body - -

      -
      - -

      In this document

      -
        -
      1. View Hierarchy
      2. -
      3. Layout
      4. -
      5. Widgets
      6. -
      7. Input Events
      8. -
      9. Menus
      10. -
      11. Advanced Topics -
          -
        1. Adapters
        2. -
        3. Styles and Themes
        4. -
        -
      12. -
      - -

      Key classes

      -
        -
      1. {@link android.view.View}
      2. -
      3. {@link android.view.ViewGroup}
      4. -
      5. {@link android.widget Widget classes}
      6. -
      -
      -
      - -

      In an Android application, the user interface is built using {@link android.view.View} and -{@link android.view.ViewGroup} objects. There are many types of views and view groups, each of which -is a descendant of the {@link android.view.View} class.

      - -

      View objects are the basic units of user interface expression on the Android platform. -The View class serves as the base for subclasses called "widgets," which offer fully implemented -UI objects, like text fields and buttons. The ViewGroup class serves as the base for subclasses called "layouts," -which offer different kinds of layout architecture, like linear, tabular and relative.

      - -

      A View object is a data structure whose properties store the layout parameters and content for a specific -rectangular area of the screen. A View object handles its own measurement, layout, drawing, focus change, -scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides. As an -object in the user interface, a View is also a point of interaction for the user and the receiver -of the interaction events.

      - - -

      View Hierarchy

      - -

      On the Android platform, you define an Activity's UI using a hierarchy of View and ViewGroup nodes, -as shown in the diagram below. This hierarchy tree can be as simple or complex as you need it to be, and you -can build it up using Android's set of predefined widgets and layouts, or with custom Views that you -create yourself.

      +page.landing=true +page.landing.intro=Your app's user interface is everything that the user can see and interact with. Android provides a variety of pre-build UI components such as structured layout objects and UI controls that allow you to build the graphical user interface for your app. Android also provides other UI modules for special interfaces such as dialogs, notifications, and menus. +page.landing.image=images/ui/ui_index.png +page.landing.next=overview.html - - -

      -In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the -{@link android.app.Activity#setContentView(int) setContentView()} -method and pass a reference to the root node object. The Android system -receives this reference and uses it to invalidate, measure, and draw the tree. The root node of the hierarchy requests -that its child nodes draw themselves — in turn, each view group node is responsible for calling -upon each of its own child views to draw themselves. -The children may request a size and location within the parent, but the parent object has the final -decision on where how big each child can be. Android parses -the elements of your layout in-order (from the top of the hierarchy tree), instantiating the Views and -adding them to their parent(s). Because these are drawn in-order, if there are elements that -overlap positions, the last one to be drawn will lie on top of others previously drawn to that space.

      - -

      For a more detailed discussion on how view hierarchies are measured -and drawn, read How Android Draws Views.

      - - -

      Layout

      - -

      The most common way to define your layout and express the view hierarchy is with an XML layout file. -XML offers a human-readable structure for the layout, much like HTML. Each element in XML is -either a View or ViewGroup object (or descendant thereof). View objects are leaves in the tree, -ViewGroup objects are branches in the tree (see the View Hierarchy figure above).

      -

      The name of an XML element -is respective to the Java class that it represents. So a <TextView> element creates -a {@link android.widget.TextView} in your UI, and a <LinearLayout> element creates -a {@link android.widget.LinearLayout} view group. When you load a layout resource, -the Android system initializes these run-time objects, corresponding to the elements in your layout.

      - -

      For example, a simple vertical layout with a text view and a button looks like this:

      -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -              android:layout_width="fill_parent" 
      -              android:layout_height="fill_parent"
      -              android:orientation="vertical" >
      -    <TextView android:id="@+id/text"
      -              android:layout_width="wrap_content"
      -              android:layout_height="wrap_content"
      -              android:text="Hello, I am a TextView" />
      -    <Button android:id="@+id/button"
      -            android:layout_width="wrap_content"
      -            android:layout_height="wrap_content"
      -            android:text="Hello, I am a Button" />
      -</LinearLayout>
      -
      - -

      Notice that the LinearLayout element contains both the TextView and the Button. You can nest -another LinearLayout (or other type of view group) inside here, to lengthen the view hierarchy and create a more -complex layout.

      +@jd:body -

      For more on building a UI layout, read XML Layouts. +

      + + + + - -

      There are a variety of ways in which you can layout your views. Using more and different kinds of view groups, -you can structure child views and view groups in an infinite number of ways. -Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, -TableLayout, GridLayout and others. Each offers a unique set of layout parameters that are used to define the -positions of child views and layout structure.

      -

      To learn about some of the different kinds of view groups used for a layout, -read Common Layout Objects.

      - - -

      Widgets

      - -

      A widget is a View object that serves as an interface for interaction with the user. -Android provides a set of fully implemented -widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI. -Some widgets provided by Android are more complex, like a date picker, a clock, and zoom controls. -But you're not limited to the kinds of widgets provided by the Android platform. If you'd -like to do something more customized and create your own actionable elements, you can, by defining your own -View object or by extending and combining existing widgets.

      -

      Read more in the Custom Components developer guide.

      - -

      For a list of the widgets provided by Android, see the {@link android.widget} package.

      - - -

      Input Events

      - -

      Once you've added some Views/widgets to the UI, you probably want to know about the -user's interaction with them, so you can perform actions. To be informed of user input events, you -need to do one of two things:

      -
        -
      • Define an event listener and register it with the View. More often than not, -this is how you'll listen for events. The View class contains a collection of nested interfaces named -On<something>Listener, each with a callback method called On<something>(). -For example, {@link android.view.View.OnClickListener} (for handling "clicks" on a View), -{@link android.view.View.OnTouchListener} (for handling touch screen events in a View), and -{@link android.view.View.OnKeyListener} if you want to handle hardware key presses within a View. So if you want your View -to be notified when it is "clicked" (such as when a button is selected), implement OnClickListener and define -its onClick() callback method (where you perform the action upon click), and register it -to the View with {@link android.view.View#setOnClickListener(View.OnClickListener) setOnClickListener()}. -
      • -
      • Override an existing callback method for the View. This is -what you should do when you've implemented your own View class and want to listen for specific events -that occur within it. Example events you can handle include when the -screen is touched ({@link android.view.View#onTouchEvent(MotionEvent) onTouchEvent()}), when -the trackball is moved ({@link android.view.View#onTrackballEvent(MotionEvent) onTrackballEvent()}), -or when a hardware key on the device is pressed ({@link android.view.View#onKeyDown(int, KeyEvent) -onKeyDown()}). This allows you to define the default behavior for each event inside your custom View and determine -whether the event should be passed on to some other child View. Again, these are callbacks to the View class, -so your only chance to define them is when you -build a custom component. -
      • -
      - -

      Continue reading about handling user interaction with Views in the Input Events document.

      - - - - -

      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 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.

      - -

      Menus are also structured using a View hierarchy, but you don't define this structure yourself. Instead, -you define the {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} or -{@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenu.ContextMenuInfo) onCreateContextMenu()} -callback methods for your Activity and declare the items that you want to include in your menu. -At the appropriate time, Android will automatically create the necessary View hierarchy for the menu and -draw each of your menu items in it.

      - -

      Menus also handle their own events, so there's no need to register event listeners on the items in your menu. -When an item in your menu is selected, the {@link android.app.Activity#onOptionsItemSelected(MenuItem) -onOptionsItemSelected()} or -{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()} -method will be called by the framework.

      - -

      And just like your application layout, you have the option to declare the items for you menu in an XML file.

      - -

      Read Menus to learn more.

      - - -

      Advanced Topics

      - -

      Once you've grappled the fundamentals of creating a user interface, you can explore -some advanced features for creating a more complex application interface.

      - -

      Adapters

      - -

      Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, -you want to bind your view to an external source of data. To do this, you use an AdapterView as -your view group and each child View is initialized and populated with data from the Adapter.

      -

      The AdapterView object is an implementation of ViewGroup that determines its child views -based on a given Adapter object. The Adapter acts like a courier between your data source (perhaps an -array of external strings) and the AdapterView, which displays it. There are several implementations -of the Adapter class, for specific tasks, such as the CursorAdapter for reading database data from a Cursor, -or an ArrayAdapter for reading from an arbitrary array.

      -

      To learn more about using an Adapter to populate your views, read -Binding to Data with AdapterView.

      - - -

      Styles and Themes

      - -

      Perhaps you're not satisfied with the look of the standard widgets. To revise them, you can create some -of your own styles and themes.

      - -
        -
      • A style is a set of one or more formatting attributes that you can apply as a unit to individual elements -in your layout. For example, you could define a style that specifies a certain text size and color, then -apply it to only specific View elements.
      • -
      • A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in -an application, or just a single activity. For example, you could define a theme that sets specific colors for -the window frame and the panel background, and sets text sizes and colors for menus. This theme can then be -applied to specific activities or the entire application.
      • -
      - -

      Styles and themes are resources. Android provides some default style and theme resources that you can use, -or you can declare your own custom style and theme resources.

      -

      Learn more about using styles and themes in the -Styles and Themes document.

      diff --git a/docs/html/guide/topics/ui/layout-objects.jd b/docs/html/guide/topics/ui/layout-objects.jd index e251fe980b0a..1d15ad60c079 100644 --- a/docs/html/guide/topics/ui/layout-objects.jd +++ b/docs/html/guide/topics/ui/layout-objects.jd @@ -1,291 +1,6 @@ -page.title=Common Layout Objects +page.title=Layouts parent.title=User Interface parent.link=index.html @jd:body - - -

      This section describes some of the more common types of layout objects -to use in your applications. Like all layouts, they are subclasses of {@link android.view.ViewGroup ViewGroup}.

      - -

      Also see the Hello Views tutorials for -some guidance on using more Android View layouts.

      - -

      FrameLayout

      -

      {@link android.widget.FrameLayout FrameLayout} is the simplest type of layout -object. It's basically a blank space on your screen that you can -later fill with a single object — for example, a picture that you'll swap in and out. -All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot -specify a different location for a child view. Subsequent child views will simply be drawn over previous ones, -partially or totally obscuring them (unless the newer object is transparent). -

      - - -

      LinearLayout

      -

      {@link android.widget.LinearLayout LinearLayout} aligns all children in a -single direction — vertically or horizontally, depending on how you -define the orientation attribute. All children are -stacked one after the other, so a vertical list will only have one child per -row, no matter how wide they are, and a horizontal list will only be one row -high (the height of the tallest child, plus padding). A {@link -android.widget.LinearLayout LinearLayout} respects margins between children -and the gravity (right, center, or left alignment) of each child.

      - -

      {@link android.widget.LinearLayout LinearLayout} also supports assigning a -weight to individual children. This attribute assigns an "importance" value to a view, -and allows it to expand to fill any remaining space in the parent view. -Child views can specify an integer weight value, and then any remaining space in the view group is -assigned to children in the proportion of their declared weight. Default -weight is zero. For example, if there are three text boxes and two of -them declare a weight of 1, while the other is given no weight (0), the third text box without weight -will not grow and will only occupy the area required by its content. -The other two will expand equally to fill the space remaining after all three boxes are measured. -If the third box is then given a weight of 2 (instead of 0), then it is now declared -"more important" than both the others, so it gets half the total remaining space, while the first two -share the rest equally.

      - - - -

      The following two forms represent a {@link android.widget.LinearLayout LinearLayout} with a set of elements: a -button, some labels and text boxes. The text boxes have their width set to fill_parent; other -elements are set to wrap_content. The gravity, by default, is left. -The difference between the two versions of the form is that the form -on the left has weight values unset (0 by default), while the form on the right has -the comments text box weight set to 1. If the Name textbox had also been set -to 1, the Name and Comments text boxes would be the same height.

      - - - -

      Within a horizontal {@link android.widget.LinearLayout LinearLayout}, items are aligned by the position of -their text base line (the first line of the first list element — topmost or -leftmost — is considered the reference line). This is so that people scanning -elements in a form shouldn't have to jump up and down to read element text in -neighboring elements. This can be turned off by setting -android:baselineAligned="false" in the layout XML.

      - -

      To view other sample code, see the -Hello LinearLayout tutorial.

      - - -

      TableLayout

      -

      {@link android.widget.TableLayout} positions its children into rows - and columns. TableLayout containers do not display border lines for their rows, columns, - or cells. The table will have as many columns as the row with the most cells. A table can leave -cells empty, but cells cannot span columns, as they can in HTML.

      -

      {@link android.widget.TableRow} objects are the child views of a TableLayout -(each TableRow defines a single row in the table). -Each row has zero or more cells, each of which is defined by any kind of other View. So, the cells of a row may be -composed of a variety of View objects, like ImageView or TextView objects. -A cell may also be a ViewGroup object (for example, you can nest another TableLayout as a cell).

      -

      The following sample layout has two rows and two cells in each. The accompanying screenshot shows the -result, with cell borders displayed as dotted lines (added for visual effect).

      - - - - - - -
      -
      -<?xml version="1.0" encoding="utf-8"?>
      -<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent"
      -    android:stretchColumns="1">
      -    <TableRow>
      -        <TextView
      -            android:text="@string/table_layout_4_open"
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="@string/table_layout_4_open_shortcut"
      -            android:gravity="right"
      -            android:padding="3dip" />
      -    </TableRow>
      -
      -    <TableRow>
      -        <TextView
      -            android:text="@string/table_layout_4_save"
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="@string/table_layout_4_save_shortcut"
      -            android:gravity="right"
      -            android:padding="3dip" />
      -    </TableRow>
      -</TableLayout>
      -
      - -

      Columns can be hidden, marked to stretch and fill the available screen space, - or can be marked as shrinkable to force the column to shrink until the table - fits the screen. See the {@link android.widget.TableLayout TableLayout reference} -documentation for more details.

      - -

      To view sample code, see the Hello -TableLayout tutorial.

      - - -

      RelativeLayout

      -

      {@link android.widget.RelativeLayout} lets child views specify their - position relative to the parent view or to each other (specified by ID). So you can - align two elements by right border, or make one below another, centered in - the screen, centered left, and so on. Elements are rendered in the order given, so if the first element - is centered in the screen, other elements aligning themselves to that element - will be aligned relative to screen center. Also, because of this ordering, if using XML to specify this layout, - the element that you will reference (in order to position other view objects) must be listed in the XML -file before you refer to it from the other views via its reference ID.

      -

      The example below shows an XML file and the resulting screen in the UI. -Note that the attributes that refer to relative elements (e.g., layout_toLeft) -refer to the ID using the syntax of a relative resource -(@id/id).

      - - - - - - -
      -
      -<?xml version="1.0" encoding="utf-8"?>
      -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -                android:layout_width="fill_parent" 
      -                android:layout_height="wrap_content"
      -                android:background="@drawable/blue"
      -                android:padding="10px" >
      -
      -    <TextView android:id="@+id/label" 
      -              android:layout_width="fill_parent" 
      -              android:layout_height="wrap_content" 
      -              android:text="Type here:" />
      -
      -    <EditText android:id="@+id/entry" 
      -              android:layout_width="fill_parent" 
      -              android:layout_height="wrap_content" 
      -              android:background="@android:drawable/editbox_background"
      -              android:layout_below="@id/label" />
      -  
      -    <Button android:id="@+id/ok" 
      -            android:layout_width="wrap_content" 
      -            android:layout_height="wrap_content" 
      -            android:layout_below="@id/entry"
      -            android:layout_alignParentRight="true"
      -            android:layout_marginLeft="10px"
      -            android:text="OK" />
      -
      -    <Button android:layout_width="wrap_content" 
      -            android:layout_height="wrap_content"
      -            android:layout_toLeftOf="@id/ok"
      -            android:layout_alignTop="@id/ok"
      -            android:text="Cancel" />
      -</RelativeLayout>
      -
      - - -

      Some of these properties are supported directly by - the element, and some are supported by its LayoutParams member (subclass RelativeLayout - for all the elements in this screen, because all elements are children of a RelativeLayout - parent object). The defined RelativeLayout parameters are: width, height, - below, alignTop, toLeft, padding[Bottom|Left|Right|Top], - and margin[Bottom|Left|Right|Top]. Note that some of these parameters specifically support - relative layout positions — their values must be the ID of the element to which you'd like this view laid relative. - For example, assigning the parameter toLeft="my_button" to a TextView would place the TextView to - the left of the View with the ID my_button (which must be written in the XML before the TextView).

      - -

      To view this sample code, see the Hello -RelativeLayout tutorial.

      - - -

      Summary of Important View Groups

      -

      These objects all hold child UI elements. Some provide their own form of a visible UI, while others - are invisible structures that only manage the layout of their child views.

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      ClassDescription
      {@link android.widget.FrameLayout FrameLayout}Layout that acts as a view frame to display - a single object.
      {@link android.widget.Gallery Gallery} A horizontal scrolling display of images, from a bound list.
      {@link android.widget.GridView GridView} Displays a scrolling grid of m columns and n rows.
      {@link android.widget.LinearLayout LinearLayout} A layout that organizes its children into a single horizontal or vertical - row. It creates a scrollbar if the length of the window exceeds the length - of the screen.
      {@link android.widget.ListView ListView} Displays a scrolling single column list.
      {@link android.widget.RelativeLayout RelativeLayout} Enables you to specify the location of child objects relative to each - other (child A to the left of child B) or to the parent (aligned to the - top of the parent).
      {@link android.widget.ScrollView ScrollView} A vertically scrolling column of elements.
      {@link android.widget.Spinner Spinner} Displays a single item at a time from a bound list, inside a one-row - textbox. Rather like a one-row listbox that can scroll either horizontally - or vertically.
      {@link android.view.SurfaceView SurfaceView} Provides direct access to a dedicated drawing surface. It can hold child - views layered on top of the surface, but is intended for applications - that need to draw pixels, rather than using widgets.
      {@link android.widget.TabHost TabHost} Provides a tab selection list that monitors clicks and enables the application - to change the screen whenever a tab is clicked.
      {@link android.widget.TableLayout TableLayout} A tabular layout with an arbitrary number of rows and columns, each cell - holding the widget of your choice. The rows resize to fit the largest - column. The cell borders are not - visible.
      {@link android.widget.ViewFlipper ViewFlipper} A list that displays one item at a time, inside a one-row textbox. It - can be set to swap items at timed intervals, like a slide show.
      {@link android.widget.ViewSwitcher ViewSwitcher} Same as ViewFlipper.
      +

      You should have been redirected to Layouts.

      \ No newline at end of file diff --git a/docs/html/guide/topics/ui/layout/grid.jd b/docs/html/guide/topics/ui/layout/grid.jd new file mode 100644 index 000000000000..52f453bb6a33 --- /dev/null +++ b/docs/html/guide/topics/ui/layout/grid.jd @@ -0,0 +1,187 @@ +page.title=Table +parent.title=Layouts +parent.link=layout-objects.html +@jd:body + +
      +
      +

      In this document

      +
        +
      1. Example
      2. +
      +

      Key classes

      +
        +
      1. {@link android.widget.TableLayout}
      2. +
      3. {@link android.widget.TableRow}
      4. +
      5. {@link android.widget.TextView}
      6. +
      +
      +
      +

      {@link android.widget.TableLayout} is a {@link android.view.ViewGroup} that +displays child {@link android.view.View} elements in rows and columns.

      + + + + +

      {@link android.widget.TableLayout} positions its children into rows + and columns. TableLayout containers do not display border lines for their rows, columns, + or cells. The table will have as many columns as the row with the most cells. A table can leave +cells empty, but cells cannot span columns, as they can in HTML.

      +

      {@link android.widget.TableRow} objects are the child views of a TableLayout +(each TableRow defines a single row in the table). +Each row has zero or more cells, each of which is defined by any kind of other View. So, the cells of a row may be +composed of a variety of View objects, like ImageView or TextView objects. +A cell may also be a ViewGroup object (for example, you can nest another TableLayout as a cell).

      +

      The following sample layout has two rows and two cells in each. The accompanying screenshot shows the +result, with cell borders displayed as dotted lines (added for visual effect).

      + + + + + + +
      +
      +<?xml version="1.0" encoding="utf-8"?>
      +<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      +    android:layout_width="fill_parent"
      +    android:layout_height="fill_parent"
      +    android:stretchColumns="1">
      +    <TableRow>
      +        <TextView
      +            android:text="@string/table_layout_4_open"
      +            android:padding="3dip" />
      +        <TextView
      +            android:text="@string/table_layout_4_open_shortcut"
      +            android:gravity="right"
      +            android:padding="3dip" />
      +    </TableRow>
      +
      +    <TableRow>
      +        <TextView
      +            android:text="@string/table_layout_4_save"
      +            android:padding="3dip" />
      +        <TextView
      +            android:text="@string/table_layout_4_save_shortcut"
      +            android:gravity="right"
      +            android:padding="3dip" />
      +    </TableRow>
      +</TableLayout>
      +
      + +

      Columns can be hidden, marked to stretch and fill the available screen space, + or can be marked as shrinkable to force the column to shrink until the table + fits the screen. See the {@link android.widget.TableLayout TableLayout reference} +documentation for more details.

      + + +

      Example

      +
        +
      1. Start a new project named HelloTableLayout.
      2. +
      3. Open the res/layout/main.xml file and insert the following: +
        +<?xml version="1.0" encoding="utf-8"?>
        +<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        +    android:layout_width="fill_parent"
        +    android:layout_height="fill_parent"
        +    android:stretchColumns="1">
        +
        +    <TableRow>
        +        <TextView
        +            android:layout_column="1"
        +            android:text="Open..."
        +            android:padding="3dip" />
        +        <TextView
        +            android:text="Ctrl-O"
        +            android:gravity="right"
        +            android:padding="3dip" />
        +    </TableRow>
        +
        +    <TableRow>
        +        <TextView
        +            android:layout_column="1"
        +            android:text="Save..."
        +            android:padding="3dip" />
        +        <TextView
        +            android:text="Ctrl-S"
        +            android:gravity="right"
        +            android:padding="3dip" />
        +    </TableRow>
        +
        +    <TableRow>
        +        <TextView
        +            android:layout_column="1"
        +            android:text="Save As..."
        +            android:padding="3dip" />
        +        <TextView
        +            android:text="Ctrl-Shift-S"
        +            android:gravity="right"
        +            android:padding="3dip" />
        +    </TableRow>
        +
        +    <View
        +        android:layout_height="2dip"
        +        android:background="#FF909090" />
        +
        +    <TableRow>
        +        <TextView
        +            android:text="X"
        +            android:padding="3dip" />
        +        <TextView
        +            android:text="Import..."
        +            android:padding="3dip" />
        +    </TableRow>
        +
        +    <TableRow>
        +        <TextView
        +            android:text="X"
        +            android:padding="3dip" />
        +        <TextView
        +            android:text="Export..."
        +            android:padding="3dip" />
        +        <TextView
        +            android:text="Ctrl-E"
        +            android:gravity="right"
        +            android:padding="3dip" />
        +    </TableRow>
        +
        +    <View
        +        android:layout_height="2dip"
        +        android:background="#FF909090" />
        +
        +    <TableRow>
        +        <TextView
        +            android:layout_column="1"
        +            android:text="Quit"
        +            android:padding="3dip" />
        +    </TableRow>
        +</TableLayout>
        +
        +

        Notice how this resembles the structure of an HTML table. The {@link android.widget.TableLayout} +element is like the HTML <table> element; {@link android.widget.TableRow} is like +a ><tr>> element; +but for the cells, you can use any kind of {@link android.view.View} element. In this example, a +{@link android.widget.TextView} is used for each cell. In between some of the rows, there is also a +basic {@link android.view.View}, which is used to draw a horizontal line.

        + +
      4. +
      5. Make sure your HelloTableLayout Activity loads this layout in the +{@link android.app.Activity#onCreate(Bundle) onCreate()} method: +
        +public void onCreate(Bundle savedInstanceState) {
        +    super.onCreate(savedInstanceState);
        +    setContentView(R.layout.main);
        +}
        +
        +

        The {@link android.app.Activity#setContentView(int)} method loads the +layout file for the {@link android.app.Activity}, specified by the resource +ID — R.layout.main refers to the res/layout/main.xml layout +file.

        +
      6. +
      7. Run the application.
      8. +
      +

      You should see the following:

      + + + + diff --git a/docs/html/guide/topics/ui/layout/gridview.jd b/docs/html/guide/topics/ui/layout/gridview.jd new file mode 100644 index 000000000000..284a25a5271b --- /dev/null +++ b/docs/html/guide/topics/ui/layout/gridview.jd @@ -0,0 +1,191 @@ +page.title=Grid +parent.title=Layouts +parent.link=layout-objects.html +@jd:body +
      +
      +

      In this document

      +
        +
      1. Example
      2. +
      +

      Key classes

      +
        +
      1. {@link android.widget.GridView}
      2. +
      3. {@link android.widget.ImageView}
      4. +
      5. {@link android.widget.BaseAdapter}
      6. +
      7. {@link android.widget.AdapterView.OnItemClickListener}
      8. +
      +
      +
      +

      {@link android.widget.GridView} is a {@link android.view.ViewGroup} that displays items in a +two-dimensional, +scrollable grid. The grid items are automatically inserted to the layout using a {@link +android.widget.ListAdapter}.

      + + + + +

      Example

      +

      In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a +toast message will display the position of the image.

      + + +
        +
      1. Start a new project named HelloGridView.
      2. +
      3. Find some photos you'd like to use, or download these sample images. Save the image files +into the project's +res/drawable/ directory.
      4. +
      5. Open the res/layout/main.xml file and insert the following: +
        +<?xml version="1.0" encoding="utf-8"?>
        +<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
        +    android:id="@+id/gridview"
        +    android:layout_width="fill_parent" 
        +    android:layout_height="fill_parent"
        +    android:columnWidth="90dp"
        +    android:numColumns="auto_fit"
        +    android:verticalSpacing="10dp"
        +    android:horizontalSpacing="10dp"
        +    android:stretchMode="columnWidth"
        +    android:gravity="center"
        +/>
        +
        +

        This {@link android.widget.GridView} will fill the entire screen. The attributes are rather +self explanatory. For more information about valid attributes, see the {@link +android.widget.GridView} reference.

        +
      6. +
      7. Open HelloGridView.java and insert the following code for the +{@link android.app.Activity#onCreate(Bundle) onCreate()} method: +
        +public void onCreate(Bundle savedInstanceState) {
        +    super.onCreate(savedInstanceState);
        +    setContentView(R.layout.main);
        +
        +    GridView gridview = (GridView) findViewById(R.id.gridview);
        +    gridview.setAdapter(new ImageAdapter(this));
        +
        +    gridview.setOnItemClickListener(new OnItemClickListener() {
        +        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        +            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        +        }
        +    });
        +}
        +
        +

        After the {@code main.xml} layout is set for the content view, the +{@link android.widget.GridView} is captured from the layout with {@link +android.app.Activity#findViewById(int)}. The {@link +android.widget.GridView#setAdapter(T) setAdapter()} method then sets a custom adapter ({@code +ImageAdapter}) as the source for all items to be displayed in the grid. The {@code ImageAdapter} is +created in the next step.

        +

        To do something when an item in the grid is clicked, the {@link +android.widget.AdapterView#setOnItemClickListener(OnItemClickListener) setOnItemClickListener()} +method is passed a new {@link android.widget.AdapterView.OnItemClickListener}. This anonymous +instance defines the {@link +android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long) +onItemClick()} callback method to show a {@link android.widget.Toast} that displays the index +position (zero-based) of the selected item (in a real world scenario, the position could be used to +get the full sized +image for some other task).

        + +
      8. +
      9. Create a new class called ImageAdapter that extends {@link +android.widget.BaseAdapter}: +
        +public class ImageAdapter extends BaseAdapter {
        +    private Context mContext;
        +
        +    public ImageAdapter(Context c) {
        +        mContext = c;
        +    }
        +
        +    public int getCount() {
        +        return mThumbIds.length;
        +    }
        +
        +    public Object getItem(int position) {
        +        return null;
        +    }
        +
        +    public long getItemId(int position) {
        +        return 0;
        +    }
        +
        +    // create a new ImageView for each item referenced by the Adapter
        +    public View getView(int position, View convertView, ViewGroup parent) {
        +        ImageView imageView;
        +        if (convertView == null) {  // if it's not recycled, initialize some attributes
        +            imageView = new ImageView(mContext);
        +            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        +            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        +            imageView.setPadding(8, 8, 8, 8);
        +        } else {
        +            imageView = (ImageView) convertView;
        +        }
        +
        +        imageView.setImageResource(mThumbIds[position]);
        +        return imageView;
        +    }
        +
        +    // references to our images
        +    private Integer[] mThumbIds = {
        +            R.drawable.sample_2, R.drawable.sample_3,
        +            R.drawable.sample_4, R.drawable.sample_5,
        +            R.drawable.sample_6, R.drawable.sample_7,
        +            R.drawable.sample_0, R.drawable.sample_1,
        +            R.drawable.sample_2, R.drawable.sample_3,
        +            R.drawable.sample_4, R.drawable.sample_5,
        +            R.drawable.sample_6, R.drawable.sample_7,
        +            R.drawable.sample_0, R.drawable.sample_1,
        +            R.drawable.sample_2, R.drawable.sample_3,
        +            R.drawable.sample_4, R.drawable.sample_5,
        +            R.drawable.sample_6, R.drawable.sample_7
        +    };
        +}
        +
        +

        First, this implements some required methods inherited from {@link +android.widget.BaseAdapter}. The constructor and {@link +android.widget.Adapter#getCount()} are self-explanatory. Normally, {@link +android.widget.Adapter#getItem(int)} should return the actual object at the specified position in +the adapter, but it's ignored for this example. Likewise, {@link +android.widget.Adapter#getItemId(int)} should return the row id of the item, but it's not +needed here.

        + +

        The first method necessary is {@link android.widget.Adapter#getView(int,View,ViewGroup) +getView()}. This method creates a new {@link android.view.View} for each image added to the {@code +ImageAdapter}. When this is called, a {@link android.view.View} is passed in, which is normally a +recycled object (at least after this has been called once), so there's a check to see if the +object is null. If it is null, an {@link android.widget.ImageView} is instantiated and +configured with desired properties for the image presentation:

        +
          +
        • {@link android.view.View#setLayoutParams(ViewGroup.LayoutParams)} sets +the height and width for the View—this ensures that, no matter the size of the drawable, each +image is resized and cropped to fit in these dimensions, as appropriate.
        • +
        • {@link android.widget.ImageView#setScaleType(ImageView.ScaleType)} declares that images should +be cropped toward the center (if necessary).
        • +
        • {@link android.widget.ImageView#setPadding(int,int,int,int)} defines the padding for all +sides. (Note that, if the images have different aspect-ratios, then less +padding will cause for more cropping of the image if it does not match +the dimensions given to the ImageView.)
        • +
        + +

        If the {@link android.view.View} passed to {@link +android.widget.Adapter#getView(int,View,ViewGroup) getView()} is not null, then the local +{@link android.widget.ImageView} is initialized with the recycled {@link android.view.View} +object.

        + +

        At the end of the {@link android.widget.Adapter#getView(int,View,ViewGroup) getView()} method, +the {@code +position} integer passed into the method is used to select an image from the {@code mThumbIds} +array, which is set as the image resource for the {@link android.widget.ImageView}.

        +

        All that's left is to define the {@code mThumbIds} array of drawable resources.

        +
      10. +
      11. Run the application.
      12. +
      + +

      Try experimenting with the behaviors of the {@link android.widget.GridView} and {@link +android.widget.ImageView} elements by adjusting their properties. For example, instead of using +{@link android.view.View#setLayoutParams(ViewGroup.LayoutParams)}, try using +{@link android.widget.ImageView#setAdjustViewBounds(boolean)}.

      + + diff --git a/docs/html/guide/topics/ui/layout/linear.jd b/docs/html/guide/topics/ui/layout/linear.jd new file mode 100644 index 000000000000..8e3370642e31 --- /dev/null +++ b/docs/html/guide/topics/ui/layout/linear.jd @@ -0,0 +1,116 @@ +page.title=Linear Layout +parent.title=Layouts +parent.link=layout-objects.html +@jd:body + +
      +
      +

      In this document

      +
        +
      1. Layout Weight
      2. +
      3. Example
      4. +
      + +

      Key classes

      +
        +
      1. {@link android.widget.LinearLayout}
      2. +
      3. {@link android.widget.LinearLayout.LayoutParams}
      4. +
      +
      +
      + +

      {@link android.widget.LinearLayout} is a view group that aligns all children in a single +direction, vertically or horizontally. You can specify the layout direction with the +{@code +android:orientation} attribute.

      + + + +

      All children of a {@link android.widget.LinearLayout} are +stacked one after the other, so a vertical list will only have one child per +row, no matter how wide they are, and a horizontal list will only be one row +high (the height of the tallest child, plus padding). A {@link +android.widget.LinearLayout LinearLayout} respects margins between children +and the gravity (right, center, or left alignment) of each child.

      + + +

      Layout Weight

      + + + + +

      {@link android.widget.LinearLayout} also supports assigning a +weight to individual children with the {@code android:layout_weight} attribute. +This attribute assigns an "importance" value to a view in +terms of how much space is should occupy on the screen. A larger weight value allows it to expand +to fill any remaining space in the parent view. +Child views can specify a weight value, and then any remaining space in the view group is +assigned to children in the proportion of their declared weight. Default +weight is zero.

      + +

      For example, if there are three text fields and two of them declare a weight of 1, while the +other is given no weight, the third text field without weight will not grow and will only occupy the +area required by its content. The other two will expand equally to fill the space remaining after +all three fields are measured. If the third field is then given a weight of 2 (instead of 0), then +it is now declared more important than both the others, so it gets half the total remaining space, +while the first two +share the rest equally.

      + + +

      Example

      + +
      + +
      + +
      +<?xml version="1.0" encoding="utf-8"?>
      +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      +    android:layout_width="fill_parent"
      +    android:layout_height="fill_parent"
      +    android:paddingLeft="16dp"
      +    android:paddingRight="16dp"
      +    android:orientation="vertical" >
      +    <EditText
      +        android:layout_width="fill_parent"
      +        android:layout_height="wrap_content"
      +        android:hint="@string/to" />
      +    <EditText
      +        android:layout_width="fill_parent"
      +        android:layout_height="wrap_content"
      +        android:hint="@string/subject" />
      +    <EditText
      +        android:layout_width="fill_parent"
      +        android:layout_height="0dp"
      +        android:layout_weight="1"
      +        android:gravity="top"
      +        android:hint="@string/message" />
      +    <Button
      +        android:layout_width="100dp"
      +        android:layout_height="wrap_content"
      +        android:layout_gravity="right"
      +        android:text="@string/send" />
      +</LinearLayout>
      +
      + +

      For details about the attributes available to each child view of a {@link +android.widget.LinearLayout}, see {@link android.widget.LinearLayout.LayoutParams}.

      + + diff --git a/docs/html/guide/topics/ui/layout/listview.jd b/docs/html/guide/topics/ui/layout/listview.jd new file mode 100644 index 000000000000..26a75979988d --- /dev/null +++ b/docs/html/guide/topics/ui/layout/listview.jd @@ -0,0 +1,151 @@ +page.title=List View +parent.title=Layouts +parent.link=declaring-layout.html +@jd:body +
      +
      +

      In this document

      +
        +
      1. Using a Loader
      2. +
      3. Example
      4. +
      +

      Key classes

      +
        +
      1. {@link android.widget.ListView}
      2. +
      3. {@link android.widget.Adapter}
      4. +
      5. {@link android.support.v4.content.CursorLoader}
      6. +
      +

      See also

      +
        +
      1. Loaders
      2. +
      +
      +
      + +

      {@link android.widget.ListView} is a view group that displays a list of +scrollable items. The list items are automatically inserted to the list using an {@link +android.widget.Adapter} that pulls content from a source such as an array or database query and +converts each item result into a view that's placed into the list.

      + + + +

      Using a Loader

      + +

      Using a {@link +android.support.v4.content.CursorLoader} is the standard way to query a {@link +android.database.Cursor} as an asynchronous task in order to avoid blocking your app's main thread +with the query. When the {@link android.support.v4.content.CursorLoader} receives the {@link +android.database.Cursor} result, the {@link android.support.v4.app.LoaderManager.LoaderCallbacks +LoaderCallbacks} receives a callback to {@link +android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished onLoadFinished()}, which is +where you update your {@link +android.widget.Adapter} with the new {@link android.database.Cursor} and the list view then +displays the results.

      + +

      Although the {@link android.support.v4.content.CursorLoader} APIs were first introduced in +Android 3.0 (API level 11), they are also available in the Support Library so that your app may use them +while supporting devices running Android 1.6 or higher.

      + +

      For more information about using a {@link +android.support.v4.content.Loader} to asynchronously load data, see the Loaders guide.

      + + +

      Example

      + +

      The following example uses {@link android.app.ListActivity}, which is an activity that includes +a {@link android.widget.ListView} as its only layout element by default. It performs a query to +the Contacts +Provider for a list of names and phone numbers.

      + +

      The activity implements the {@link android.support.v4.app.LoaderManager.LoaderCallbacks +LoaderCallbacks} interface in order to use a {@link android.support.v4.content.CursorLoader} that +dynamically loads the data for the list view.

      + +
      +public class ListViewLoader extends ListActivity
      +        implements LoaderManager.LoaderCallbacks<Cursor> {
      +
      +    // This is the Adapter being used to display the list's data
      +    SimpleCursorAdapter mAdapter;
      +
      +    // These are the Contacts rows that we will retrieve
      +    static final String[] PROJECTION = new String[] {ContactsContract.Data._ID,
      +            ContactsContract.Data.DISPLAY_NAME};
      +
      +    // This is the select criteria
      +    static final String SELECTION = "((" + 
      +            ContactsContract.Data.DISPLAY_NAME + " NOTNULL) AND (" +
      +            ContactsContract.Data.DISPLAY_NAME + " != '' ))";
      +
      +    @Override
      +    protected void onCreate(Bundle savedInstanceState) {
      +        super.onCreate(savedInstanceState);
      +
      +        // Create a progress bar to display while the list loads
      +        ProgressBar progressBar = new ProgressBar(this);
      +        progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
      +                LayoutParams.WRAP_CONTENT, Gravity.CENTER));
      +        progressBar.setIndeterminate(true);
      +        getListView().setEmptyView(progressBar);
      +
      +        // Must add the progress bar to the root of the layout
      +        ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
      +        root.addView(progressBar);
      +
      +        // For the cursor adapter, specify which columns go into which views
      +        String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME};
      +        int[] toViews = {android.R.id.text1}; // The TextView in simple_list_item_1
      +
      +        // Create an empty adapter we will use to display the loaded data.
      +        // We pass null for the cursor, then update it in onLoadFinished()
      +        mAdapter = new SimpleCursorAdapter(this, 
      +                android.R.layout.simple_list_item_1, null,
      +                fromColumns, toViews, 0);
      +        setListAdapter(mAdapter);
      +
      +        // Prepare the loader.  Either re-connect with an existing one,
      +        // or start a new one.
      +        getLoaderManager().initLoader(0, null, this);
      +    }
      +
      +    // Called when a new Loader needs to be created
      +    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
      +        // Now create and return a CursorLoader that will take care of
      +        // creating a Cursor for the data being displayed.
      +        return new CursorLoader(this, ContactsContract.Data.CONTENT_URI,
      +                PROJECTION, SELECTION, null, null);
      +    }
      +
      +    // Called when a previously created loader has finished loading
      +    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
      +        // Swap the new cursor in.  (The framework will take care of closing the
      +        // old cursor once we return.)
      +        mAdapter.swapCursor(data);
      +    }
      +
      +    // Called when a previously created loader is reset, making the data unavailable
      +    public void onLoaderReset(Loader<Cursor> loader) {
      +        // This is called when the last Cursor provided to onLoadFinished()
      +        // above is about to be closed.  We need to make sure we are no
      +        // longer using it.
      +        mAdapter.swapCursor(null);
      +    }
      +
      +    @Override 
      +    public void onListItemClick(ListView l, View v, int position, long id) {
      +        // Do something when a list item is clicked
      +    }
      +}
      +
      + +

      Note: Because this sample performs a query on the Contacts +Provider, if you want to +try this code, your app must request the {@link android.Manifest.permission#READ_CONTACTS} +permission in the manifest file:
      +<uses-permission android:name="android.permission.READ_CONTACTS" />

      + diff --git a/docs/html/guide/topics/ui/layout/relative.jd b/docs/html/guide/topics/ui/layout/relative.jd new file mode 100644 index 000000000000..ee6cf02bd642 --- /dev/null +++ b/docs/html/guide/topics/ui/layout/relative.jd @@ -0,0 +1,118 @@ +page.title=Relative Layout +parent.title=Layouts +parent.link=layout-objects.html +@jd:body + +
      +
      +

      In this document

      +
        +
      1. Positioning Views
      2. +
      3. Example
      4. +
      +

      Key classes

      +
        +
      1. {@link android.widget.RelativeLayout}
      2. +
      3. {@link android.widget.RelativeLayout.LayoutParams}
      4. +
      +
      +
      + +

      {@link android.widget.RelativeLayout} is a view group that displays child views in relative +positions. The position of each view can be specified as relative to sibling elements (such as to +the left-of or below another view) or in positions relative to the parent {@link +android.widget.RelativeLayout} area (such as aligned to the bottom, left of center).

      + + + +

      A {@link android.widget.RelativeLayout} is a very powerful utility for designing a user interface +because it can eliminate nested view groups and keep your layout hierarchy flat, which improves +performance. If you find yourself using several nested {@link android.widget.LinearLayout} groups, +you may be able to replace them with a single {@link android.widget.RelativeLayout}.

      + + +

      Positioning Views

      + +

      {@link android.widget.RelativeLayout} lets child views specify their position relative to the +parent view or to each other (specified by ID). So you can align two elements by right border, or +make one below another, centered in the screen, centered left, and so on. By default, all child +views are drawn at the top-left of the layout, so you must define the position of each view +using the various layout properties available from {@link +android.widget.RelativeLayout.LayoutParams}.

      + +

      Some of the many layout properties available to views in a {@link android.widget.RelativeLayout} +include:

      +
      +
      {@code android:layout_alignParentTop}
      +
      If {@code "true"}, makes the top edge of this view match the top edge of the parent.
      +
      {@code android:layout_centerVertical}
      +
      If {@code "true"}, centers this child vertically within its parent.
      +
      {@code android:layout_below}
      +
      Positions the top edge of this view below the view specified with a resource ID.
      +
      {@code android:layout_toRightOf}
      +
      Positions the left edge of this view to the right of the view specified with a resource ID.
      +
      + +

      These are just a few examples. All layout attributes are documented at {@link +android.widget.RelativeLayout.LayoutParams}.

      + +

      The value for each layout property is either a boolean to +enable a layout position relative to the parent {@link android.widget.RelativeLayout} or an ID that +references another view in the layout against which the view should be positioned.

      + +

      In your XML layout, dependencies against other views in the layout can be declared in any order. +For example, you can declare that "view1" be positioned below "view2" even if "view2" is the last +view declared in the hierarchy. The example below demonstrates such a scenario.

      + + +

      Example

      + +

      Each of the attributes that control the relative position of each view are emphasized.

      +
      + +
      + +
      +<?xml version="1.0" encoding="utf-8"?>
      +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      +    android:layout_width="fill_parent"
      +    android:layout_height="fill_parent"
      +    android:paddingLeft="16dp"
      +    android:paddingRight="16dp" >
      +    <EditText
      +        android:id="@+id/name"
      +        android:layout_width="fill_parent"
      +        android:layout_height="wrap_content"
      +        android:hint="@string/reminder" />
      +    <Spinner
      +        android:id="@+id/dates"
      +        android:layout_width="0dp"
      +        android:layout_height="wrap_content"
      +        android:layout_below="@id/name"
      +        android:layout_alignParentLeft="true"
      +        android:layout_toLeftOf="@+id/times" />
      +    <Spinner
      +        android:id="@id/times"
      +        android:layout_width="96dp"
      +        android:layout_height="wrap_content"
      +        android:layout_below="@id/name"
      +        android:layout_alignParentRight="true" />
      +    <Button
      +        android:layout_width="96dp"
      +        android:layout_height="wrap_content"
      +        android:layout_below="@id/times"
      +        android:layout_alignParentRight="true"
      +        android:text="@string/done" />
      +</RelativeLayout>
      +
      + +

      For details about all the layout attributes available to each child view of a {@link +android.widget.RelativeLayout}, see {@link android.widget.RelativeLayout.LayoutParams}.

      \ No newline at end of file diff --git a/docs/html/guide/topics/ui/layout/tabs.jd b/docs/html/guide/topics/ui/layout/tabs.jd new file mode 100644 index 000000000000..62663de8a84d --- /dev/null +++ b/docs/html/guide/topics/ui/layout/tabs.jd @@ -0,0 +1,219 @@ +page.title=Tabbed +parent.title=Layouts +parent.link=layout-objects.html +@jd:body +
      +
      +

      In this document

      +
        +
      1. Example
      2. +
      +

      Key classes

      +
        +
      1. {@link android.widget.TabWidget}
      2. +
      3. {@link android.widget.TabHost}
      4. +
      5. {@link android.widget.TabHost.TabSpec}
      6. +
      7. {@link android.widget.FrameLayout}
      8. +
      +
      +
      +

      To create a tabbed UI, you need to use a {@link android.widget.TabHost} and a {@link +android.widget.TabWidget}. The {@link android.widget.TabHost} must be the root node for the layout, +which contains both the {@link android.widget.TabWidget} for displaying the tabs and a {@link +android.widget.FrameLayout} for displaying the tab content.

      + + + +

      You can implement your tab content in one of two ways: use the tabs to swap +{@link android.view.View}s within the same {@link android.app.Activity}, or use the tabs to change +between entirely separate activities. Which method you want for your application will depend on your +demands, but if each tab provides a distinct user activity, then it probably makes sense to use +a separate {@link android.app.Activity} for each tab, so that you can better manage the application +in discrete groups, rather than one massive application and layout.

      +

      Example

      +

      In this tutorial, you'll create a tabbed UI that uses a separate {@link +android.app.Activity} for each tab.

      + +
        +
      1. Start a new project named HelloTabWidget.
      2. +
      3. First, create three separate {@link android.app.Activity} classes in your project: +ArtistsActivity, AlbumsActivity, and SongsActivity. These +will each represent a separate tab. For now, make each one display a simple message using a {@link +android.widget.TextView}. For example: +
        +public class ArtistsActivity extends Activity {
        +    public void onCreate(Bundle savedInstanceState) {
        +        super.onCreate(savedInstanceState);
        +
        +        TextView textview = new TextView(this);
        +        textview.setText("This is the Artists tab");
        +        setContentView(textview);
        +    }
        +}
        +
        +

        Notice that this doesn't use a layout file. Just create a {@link +android.widget.TextView}, give it some text and set that as the content. Duplicate this for +each of the three activities, and add the corresponding <activity/> tags to the Android Manifest file.

        + +
      4. You need an icon for each of your tabs. For each icon, you should create two versions: one +for when the tab is selected and one for when it is unselected. The +general design recommendation is for the selected icon to be a dark color (grey), and the +unselected icon to be a light color (white). (See the Icon Design +Guidelines.) For example: +

        + + +

        +

        For this tutorial, you can copy these images and use them for all three tabs. (When you +create tabs in your own application, you should create customized tab icons.)

        +

        Now create a state-list drawable +that specifies which image to use for each tab state:

        +
          +
        1. Save the icon images in your project res/drawable/ directory.
        2. +
        3. Create a new XML file in res/drawable/ +named ic_tab_artists.xml and insert the following: +
          +<?xml version="1.0" encoding="utf-8"?>
          +<selector xmlns:android="http://schemas.android.com/apk/res/android">
          +    <!-- When selected, use grey -->
          +    <item android:drawable="@drawable/ic_tab_artists_grey"
          +          android:state_selected="true" />
          +    <!-- When not selected, use white-->
          +    <item android:drawable="@drawable/ic_tab_artists_white" />
          +</selector>
          +
          +

          This is a state-list drawable, +which you will apply as the tab image. When the tab state changes, the tab icon will +automatically switch between the images defined here.

          +
        4. +
        +
      5. + +
      6. Open the res/layout/main.xml file and insert the following: +
        +<?xml version="1.0" encoding="utf-8"?>
        +<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
        +    android:id="@android:id/tabhost"
        +    android:layout_width="fill_parent"
        +    android:layout_height="fill_parent">
        +    <LinearLayout
        +        android:orientation="vertical"
        +        android:layout_width="fill_parent"
        +        android:layout_height="fill_parent"
        +        android:padding="5dp">
        +        <TabWidget
        +            android:id="@android:id/tabs"
        +            android:layout_width="fill_parent"
        +            android:layout_height="wrap_content" />
        +        <FrameLayout
        +            android:id="@android:id/tabcontent"
        +            android:layout_width="fill_parent"
        +            android:layout_height="fill_parent"
        +            android:padding="5dp" />
        +    </LinearLayout>
        +</TabHost>
        +
        +

        This is the layout that will display the tabs and provide navigation between each {@link + android.app.Activity} created above.

        +

        The {@link android.widget.TabHost} requires that a {@link android.widget.TabWidget} and a +{@link android.widget.FrameLayout} both live somewhere within it. To position the {@link +android.widget.TabWidget} and {@link android.widget.FrameLayout} vertically, a {@link +android.widget.LinearLayout} is used. The {@link android.widget.FrameLayout} is where the content +for each tab goes, which is empty now because the {@link android.widget.TabHost} will automatically +embed each {@link android.app.Activity} within it.

        +

        Notice that the {@link android.widget.TabWidget} and the {@link android.widget.FrameLayout} + elements have the IDs {@code tabs} and {@code tabcontent}, respectively. These names + must be used so that the {@link android.widget.TabHost} can retrieve references to each of + them. It expects exactly these names.

        +
      7. + +
      8. Now open HelloTabWidget.java and make it extend {@link + android.app.TabActivity}:

        +
        +public class HelloTabWidget extends TabActivity {
        +
        +
      9. +
      10. Use the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} + method: +
        +public void onCreate(Bundle savedInstanceState) {
        +    super.onCreate(savedInstanceState);
        +    setContentView(R.layout.main);
        +
        +    Resources res = getResources(); // Resource object to get Drawables
        +    TabHost tabHost = getTabHost();  // The activity TabHost
        +    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        +    Intent intent;  // Reusable Intent for each tab
        +
        +    // Create an Intent to launch an Activity for the tab (to be reused)
        +    intent = new Intent().setClass(this, ArtistsActivity.class);
        +
        +    // Initialize a TabSpec for each tab and add it to the TabHost
        +    spec = tabHost.newTabSpec("artists").setIndicator("Artists",
        +                      res.getDrawable(R.drawable.ic_tab_artists))
        +                  .setContent(intent);
        +    tabHost.addTab(spec);
        +
        +    // Do the same for the other tabs
        +    intent = new Intent().setClass(this, AlbumsActivity.class);
        +    spec = tabHost.newTabSpec("albums").setIndicator("Albums",
        +                      res.getDrawable(R.drawable.ic_tab_albums))
        +                  .setContent(intent);
        +    tabHost.addTab(spec);
        +
        +    intent = new Intent().setClass(this, SongsActivity.class);
        +    spec = tabHost.newTabSpec("songs").setIndicator("Songs",
        +                      res.getDrawable(R.drawable.ic_tab_songs))
        +                  .setContent(intent);
        +    tabHost.addTab(spec);
        +
        +    tabHost.setCurrentTab(2);
        +}
        +
        +

        This sets up each tab with their text and icon, and assigns each one an {@link +android.app.Activity}.

        +

        A reference to the {@link android.widget.TabHost} is first captured with {@link +android.app.TabActivity#getTabHost()}. Then, for +each tab, a {@link android.widget.TabHost.TabSpec} is created to define the tab properties. The +{@link android.widget.TabHost#newTabSpec(String)} method creates a new {@link +android.widget.TabHost.TabSpec} identified by the given string tag. For each +{@link android.widget.TabHost.TabSpec}, {@link +android.widget.TabHost.TabSpec#setIndicator(CharSequence,Drawable)} is called to set the text and +icon for the tab, and {@link android.widget.TabHost.TabSpec#setContent(Intent)} is called to specify +the {@link android.content.Intent} to open the appropriate {@link android.app.Activity}. Each +{@link android.widget.TabHost.TabSpec} is then added to the {@link android.widget.TabHost} by +calling {@link android.widget.TabHost#addTab(TabHost.TabSpec)}.

        + +

        At the very end, {@link + android.widget.TabHost#setCurrentTab(int)} opens the tab to be displayed by default, specified + by the index position of the tab.

        + +

        Notice that not once was the {@link android.widget.TabWidget} object referenced. This is + because a {@link android.widget.TabWidget} must always be a child of a {@link + android.widget.TabHost}, which is what you use for almost all interaction with the tabs. So when + a tab is added to the {@link android.widget.TabHost}, it's automatically added to the child + {@link android.widget.TabWidget}.

        +
      11. + +
      12. Now open the Android Manifest file and add the NoTitleBar theme to the +HelloTabWidget's + <activity> tag. This will remove the default application title from the top + of the layout, leaving more space for the tabs, which effectively operate as their own titles. + The <activity> tag should look like this: +
        +<activity android:name=".HelloTabWidget" android:label="@string/app_name"
        +          android:theme="@android:style/Theme.NoTitleBar">
        +
        +
      13. + +
      14. Run the application.
      15. +
      + + +

      Your application should look like this (though your icons may be different):

      + + + diff --git a/docs/html/guide/topics/ui/menus.jd b/docs/html/guide/topics/ui/menus.jd index d51a378cb4a3..01d373ef2e86 100644 --- a/docs/html/guide/topics/ui/menus.jd +++ b/docs/html/guide/topics/ui/menus.jd @@ -1040,7 +1040,7 @@ category. For example:

    Read more about writing intent filters in the -Intents and Intent Filters document.

    +Intents and Intent Filters document.

    For a sample application using this technique, see the Note diff --git a/docs/html/guide/topics/ui/notifiers/index.jd b/docs/html/guide/topics/ui/notifiers/index.jd index c61d4f010f35..caf0df70edd1 100644 --- a/docs/html/guide/topics/ui/notifiers/index.jd +++ b/docs/html/guide/topics/ui/notifiers/index.jd @@ -21,7 +21,7 @@ the application should show a hovering progress wheel or bar.

    @@ -44,16 +44,16 @@ out, and does not accept interaction events. Because a toast can be created from when you're fairly certain the user is paying attention to the screen. A toast can not accept user interaction events; if you'd like the user to respond and take action, consider using a -Status Bar Notification instead.

    +Status Notification instead.

    For more information, refer to Toast Notifications.

    -

    Status Bar Notification

    +

    Status Notification

    -

    A status bar notification adds an icon to the system's status bar +

    A status notification adds an icon to the system's status bar (with an optional ticker-text message) and an expanded message in the "Notifications" window. When the user selects the expanded message, Android fires an {@link android.content.Intent} that is defined by the notification (usually to launch an @@ -68,7 +68,7 @@ while your Activity is still in focus, consider using a Dialog Notification instead.

    For more information, refer to -Status Bar Notifications.

    +Status Notifications.

    Dialog Notification

    diff --git a/docs/html/guide/topics/ui/notifiers/notifications.jd b/docs/html/guide/topics/ui/notifiers/notifications.jd index d104b4bccd14..52092f9409cf 100644 --- a/docs/html/guide/topics/ui/notifiers/notifications.jd +++ b/docs/html/guide/topics/ui/notifiers/notifications.jd @@ -1,4 +1,4 @@ -page.title=Status Bar Notifications +page.title=Status Notifications parent.title=Notifications parent.link=index.html @jd:body @@ -7,7 +7,7 @@ parent.link=index.html

    Quickview

      -
    • A status bar notification allows your application to notify the user of an event +
    • A status notification allows your application to notify the user of an event without interupting their current activity
    • You can attach an intent to your notification that the system will initiate when the user clicks it
    • @@ -43,7 +43,7 @@ Design: Notifications
    -

    A status bar notification adds an icon to the system's status bar +

    A status notification adds an icon to the system's status bar (with an optional ticker-text message) and a notification message in the notifications window. When the user selects the notification, Android fires an {@link android.content.Intent} that is defined by the {@link android.app.Notification} (usually to @@ -51,11 +51,11 @@ launch an {@link android.app.Activity}). You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.

    -

    A status bar notification should be used for any case in +

    A status notification should be used for any case in which a background service needs to alert the user about an event that requires a response. A background service should never launch an activity on its own in order to receive user interaction. -The service should instead create a status bar notification that will launch the activity +The service should instead create a status notification that will launch the activity when selected by the user.

    Figure 1 shows the status bar with a notification icon on the left side.

    @@ -78,9 +78,9 @@ href="{@docRoot}design/patterns/notifications.html">Notifications guide.

    The Basics

    -

    An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar +

    An {@link android.app.Activity} or {@link android.app.Service} can initiate a status notification. Because an activity can perform actions only while it is -running in the foreground and its window has focus, you will usually create status bar notifications +running in the foreground and its window has focus, you will usually create status notifications from a service. This way, the notification can be created from the background, while the user is using another application or @@ -88,9 +88,9 @@ while the device is asleep. To create a notification, you must use two classes: {@link android.app.Notification} and {@link android.app.NotificationManager}.

    Use an instance of the {@link android.app.Notification} class to define the properties of your -status bar notification, such as the status bar icon, the notification message, and extra settings +status notification, such as the status icon, the notification message, and extra settings such as a sound to play. The {@link android.app.NotificationManager} is an Android system service -that executes and manages all status bar notifications. You do not instantiate the +that executes and manages all status notifications. You do not instantiate the {@link android.app.NotificationManager} directly. In order to give it your {@link android.app.Notification}, you must retrieve a reference to the {@link android.app.NotificationManager} with @@ -98,7 +98,7 @@ to give it your {@link android.app.Notification}, you must retrieve a reference then, when you want to notify the user, pass it your {@link android.app.Notification} with {@link android.app.NotificationManager#notify(int,Notification) notify()}.

    -

    To create a status bar notification:

    +

    To create a status notification:

    1. Get a reference to the {@link android.app.NotificationManager}:
      @@ -277,7 +277,7 @@ String ns = Context.NOTIFICATION_SERVICE;
       NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
       
      -

      When you want to deliver your status bar notification, pass the {@link android.app.Notification} +

      When you want to deliver your status notification, pass the {@link android.app.Notification} to the {@link android.app.NotificationManager} with {@link android.app.NotificationManager#notify(int,Notification)}. The first parameter is the unique ID for the notification and the second is the {@link @@ -287,7 +287,7 @@ application. The ID is necessary if you need to update the notification or (if your application manages different kinds of notifications) select the appropriate action when the user returns to your application via the intent defined in the notification.

      -

      To clear the status bar notification when the user selects it from the notifications +

      To clear the status notification when the user selects it from the notifications window, add the "FLAG_AUTO_CANCEL" flag to your {@link android.app.Notification}. You can also clear it manually with {@link android.app.NotificationManager#cancel(int)}, passing it the notification ID, or clear all your notifications with {@link @@ -300,14 +300,14 @@ android.app.NotificationManager#cancelAll()}.

      message that is displayed in the status bar and notifications window, and any other alert settings, such as sounds and blinking lights.

      -

      A status bar notification requires all of the following:

      +

      A status notification requires all of the following:

      • An icon for the status bar
      • A title and message, unless you define a custom notification layout
      • A {@link android.app.PendingIntent}, to be fired when the notification is selected
      -

      Optional settings for the status bar notification include:

      +

      Optional settings for the status notification include:

      • A ticker-text message for the status bar
      • An alert sound
      • @@ -339,7 +339,7 @@ notification.setLatestEventInfo(context, contentTitle, contentText, contentInten

        Updating the notification

        -

        You can update the information in your status bar notification as events +

        You can update the information in your status notification as events continue to occur in your application. For example, when a new SMS text message arrives before previous messages have been read, the Messaging application updates the existing notification to display the total number of new messages received. @@ -484,7 +484,7 @@ following:

        your notification is on-going.
        {@link android.app.Notification#number} field
        This value indicates the current number of events represented by the notification. - The appropriate number is overlaid on top of the status bar icon. + The appropriate number is overlaid on top of the status icon. If you intend to use this field, then you must start with "1" when the Notification is first created. (If you change the value from zero to anything greater during an update, the number is not shown.)
        diff --git a/docs/html/guide/topics/ui/overview.jd b/docs/html/guide/topics/ui/overview.jd new file mode 100644 index 000000000000..41f7cc7b3f01 --- /dev/null +++ b/docs/html/guide/topics/ui/overview.jd @@ -0,0 +1,74 @@ +page.title=UI Overview +@jd:body + + +

        All user interface elements in an Android app are built using {@link android.view.View} and +{@link android.view.ViewGroup} objects. A {@link android.view.View} is an object that draws +something on the screen that the user can interact with. A {@link android.view.ViewGroup} is an +object that holds other {@link android.view.View} (and {@link android.view.ViewGroup}) objects in +order to define the layout of the interface.

        + +

        Android provides a collection of both {@link android.view.View} and {@link +android.view.ViewGroup} subclasses that offer you common input controls (such as buttons and text +fields) and various layout models (such as a linear or relative layout).

        + + +

        User Interface Layout

        + +

        The user interface for each component of your app is defined using a hierarchy of {@link +android.view.View} and {@link android.view.ViewGroup} objects, as shown in figure 1. Each view group +is an invisible container that organizes child views, while the child views may be input +controls or other widgets that +draw some part of the UI. This hierarchy tree can be as simple or complex as you need +it to be (but simplicity is best for performance).

        + + +

        Figure 1. Illustration of a view hierarchy, which defines a +UI layout.

        + +

        To declare your layout, you can instantiate {@link android.view.View} objects in code and start +building a tree, but the easiest and most effective way to define your layout is with an XML file. +XML offers a human-readable structure for the layout, similar to HTML.

        + +

        The name of an XML element for a view is respective to the Android class it represents. So a +<TextView> element creates a {@link android.widget.TextView} widget in your UI, +and a <LinearLayout> element creates a {@link android.widget.LinearLayout} view +group.

        + +

        For example, a simple vertical layout with a text view and a button looks like this:

        +
        +<?xml version="1.0" encoding="utf-8"?>
        +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        +              android:layout_width="fill_parent" 
        +              android:layout_height="fill_parent"
        +              android:orientation="vertical" >
        +    <TextView android:id="@+id/text"
        +              android:layout_width="wrap_content"
        +              android:layout_height="wrap_content"
        +              android:text="I am a TextView" />
        +    <Button android:id="@+id/button"
        +            android:layout_width="wrap_content"
        +            android:layout_height="wrap_content"
        +            android:text="I am a Button" />
        +</LinearLayout>
        +
        + +

        When you load a layout resource in your app, Android initializes each node of the layout into a +runtime object you can use to define additional behaviors, query the object state, or modify the +layout.

        + +

        For a complete guide to creating a UI layout, see XML +Layouts. + + +

        User Interface Components

        + +

        You don't have to build all of your UI using {@link android.view.View} and {@link +android.view.ViewGroup} objects. Android provides several app components that offer +a standard UI layout for which you simply need to define the content. These UI components each +have a unique set of APIs that are described in their respective documents, such as Action Bar, Dialogs, and Status Notifications.

        + + diff --git a/docs/html/guide/topics/ui/sharables/sample_images.zip b/docs/html/guide/topics/ui/sharables/sample_images.zip new file mode 100644 index 000000000000..007a68aca79e Binary files /dev/null and b/docs/html/guide/topics/ui/sharables/sample_images.zip differ diff --git a/docs/html/guide/topics/usb/accessory.jd b/docs/html/guide/topics/usb/accessory.jd deleted file mode 100644 index 8b74bc0d6429..000000000000 --- a/docs/html/guide/topics/usb/accessory.jd +++ /dev/null @@ -1,462 +0,0 @@ -page.title=USB Accessory -@jd:body - - - -

        USB accessory mode allows users to connect - USB host hardware specifically designed for Android-powered devices. The accessories must adhere - to the Android accessory protocol outlined in the Android Accessory Development Kit documentation. - This allows Android-powered devices that cannot act as a USB host to still interact with USB - hardware. When an Android-powered device is in USB accessory mode, the attached Android USB - accessory acts as the host, provides power to the USB bus, and enumerates connected devices. - Android 3.1 (API level 12) supports USB accessory mode and the feature is also backported to - Android 2.3.4 (API level 10) to enable support for a broader range of devices.

        - -

        Choosing the Right USB Accessory APIs

        - -

        Although the USB accessory APIs were introduced to the platform in Android 3.1, they are also - available in Android 2.3.4 using the Google APIs add-on library. Because these APIs were - backported using an external library, there are two packages that you can import to support USB - accessory mode. Depending on what Android-powered devices you want to support, you might have to - use one over the other:

        - -
          -
        • com.android.future.usb: To support USB accessory mode in Android 2.3.4, the - Google APIs add-on - library includes the backported USB accessory APIs and they are contained in this - namespace. Android 3.1 also supports importing and calling the classes within this namespace to - support applications written with the add-on library. This add-on library is a thin wrapper - around the {@link android.hardware.usb} accessory APIs and does not support USB host mode. If - you want to support the widest range of devices that support USB accessory mode, use the add-on - library and import this package. It is important to note that not all Android 2.3.4 devices are - required to support the USB accessory feature. Each individual device manufacturer decides - whether or not to support this capability, which is why you must declare it in your manifest - file.
        • - -
        • {@link android.hardware.usb}: This namespace contains the classes that support USB - accessory mode in Android 3.1. This package is included as part of the framework APIs, so - Android 3.1 supports USB accessory mode without the use of an add-on library. Use this package - if you only care about Android 3.1 or newer devices that have hardware support for USB - accessory mode, which you can declare in your manifest file.
        • -
        - -

        Installing the Google APIs add-on library

        - -

        If you want to install the add-on, you can do so by installing the Google APIs Android API 10 - package with the SDK Manager. See Installing the Google APIs - Add-on for more information on installing the add-on library.

        - -

        API Overview

        - -

        Because the add-on library is a wrapper for the framework APIs, the classes that support the - USB accessory feature are similar. You can use the reference documentation for the {@link - android.hardware.usb} even if you are using the add-on library.

        - -

        Note: There is, however, a minor usage - difference between the add-on library and framework APIs that you should be aware of.

        - -

        The following table describes the classes that support the USB accessory APIs:

        - - - - - - - - - - - - - - - - - - - -
        ClassDescription
        {@link android.hardware.usb.UsbManager}Allows you to enumerate and communicate with connected USB accessories.
        {@link android.hardware.usb.UsbAccessory}Represents a USB accessory and contains methods to access its identifying - information.
        - -

        Usage differences between the add-on library and platform APIs

        - -

        There are two usage differences between using the Google APIs add-on library and the platform - APIs.

        - -

        If you are using the add-on library, you must obtain the {@link - android.hardware.usb.UsbManager} object in the following manner:

        -
        -UsbManager manager = UsbManager.getInstance(this);
        -
        - -

        If you are not using the add-on library, you must obtain the {@link - android.hardware.usb.UsbManager} object in the following manner:

        -
        -UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        -
        - -

        When you filter for a connected accessory with an intent filter, the {@link - android.hardware.usb.UsbAccessory} object is contained inside the intent that is passed to your - application. If you are using the add-on library, you must obtain the {@link - android.hardware.usb.UsbAccessory} object in the following manner:

        -
        -UsbAccessory accessory = UsbManager.getAccessory(intent);
        -
        - -

        If you are not using the add-on library, you must obtain the {@link - android.hardware.usb.UsbAccessory} object in the following manner:

        -
        -UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        -
        - -

        Android Manifest requirements

        - -

        The following list describes what you need to add to your application's manifest file before - working with the USB accesory APIs. The manifest and resource file - examples show how to declare these items:

        - -
          -
        • Because not all Android-powered devices are guaranteed to support the USB accessory APIs, - include a <uses-feature> element that declares that your application uses - the android.hardware.usb.accessory feature.
        • - -
        • If you are using the - add-on library, - add the <uses-library> element specifying - com.android.future.usb.accessory for the library.
        • - -
        • Set the minimum SDK of the application to API Level 10 if you are using the add-on library - or 12 if you are using the {@link android.hardware.usb} package.
        • - -
        • -

          If you want your application to be notified of an attached USB accessory, specify an - <intent-filter> and <meta-data> element pair for the - android.hardware.usb.action.USB_ACCESSORY_ATTACHED intent in your main activity. - The <meta-data> element points to an external XML resource file that - declares identifying information about the accessory that you want to detect.

          - -

          In the XML resource file, declare <usb-accessory> elements for the - accessories that you want to filter. Each <usb-accessory> can have the - following attributes:

          - -
            -
          • manufacturer
          • - -
          • model
          • - -
          • version
          • -
          - -

          Save the resource file in the res/xml/ directory. The resource file name - (without the .xml extension) must be the same as the one you specified in the - <meta-data> element. The format for the XML resource file is also shown in - the example below.

          -
        • -
        - -

        Manifest and resource file examples

        - -

        The following example shows a sample manifest and its corresponding resource file:

        -
        -<manifest ...>
        -    <uses-feature android:name="android.hardware.usb.accessory" />
        -    
        -    <uses-sdk android:minSdkVersion="<version>" />
        -    ...
        -    <application>
        -      <uses-library android:name="com.android.future.usb.accessory" />
        -        <activity ...>
        -            ...
        -            <intent-filter>
        -                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
        -            </intent-filter>
        -
        -            <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
        -                android:resource="@xml/accessory_filter" />
        -        </activity>
        -    </application>
        -</manifest>
        -
        - -

        In this case, the following resource file should be saved in - res/xml/accessory_filter.xml and specifies that any accessory that has the - corresponding model, manufacturer, and version should be filtered. The accessory sends these - attributes the Android-powered device:

        -
        -<?xml version="1.0" encoding="utf-8"?>
        -
        -<resources>
        -    <usb-accessory model="DemoKit" manufacturer="Google" version="1.0"/>
        -</resources>
        -
        - -

        Working with Accessories

        - -

        When users connect USB accessories to an Android-powered device, the Android system can - determine whether your application is interested in the connected accessory. If so, you can set - up communication with the accessory if desired. To do this, your application has to:

        - -
          -
        1. Discover connected accessories by using an intent filter that filters for accessory - attached events or by enumerating connected accessories and finding the appropriate one.
        2. - -
        3. Ask the user for permission to communicate with the accessory, if not already - obtained.
        4. - -
        5. Communicate with the accessory by reading and writing data on the appropriate interface - endpoints.
        6. -
        - -

        Discovering an accessory

        - -

        Your application can discover accessories by either using an intent filter to be notified when - the user connects an accessory or by enumerating accessories that are already connected. Using an - intent filter is useful if you want to be able to have your application automatically detect a - desired accessory. Enumerating connected accessories is useful if you want to get a list of all - connected accessories or if your application did not filter for an intent.

        - -

        Using an intent filter

        - -

        To have your application discover a particular USB accessory, you can specify an intent filter - to filter for the android.hardware.usb.action.USB_ACCESSORY_ATTACHED intent. Along - with this intent filter, you need to specify a resource file that specifies properties of the USB - accessory, such as manufacturer, model, and version. When users connect an accessory that matches - your accessory filter,

        - -

        The following example shows how to declare the intent filter:

        -
        -<activity ...>
        -    ...
        -    <intent-filter>
        -        <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
        -    </intent-filter>
        -
        -    <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
        -        android:resource="@xml/accessory_filter" />
        -</activity>
        -
        - -

        The following example shows how to declare the corresponding resource file that specifies the - USB accessories that you're interested in:

        -
        -<?xml version="1.0" encoding="utf-8"?>
        -
        -<resources>
        -    <usb-accessory manufacturer="Google, Inc." model="DemoKit" version="1.0" />
        -</resources>
        -
        - -

        In your activity, you can obtain the {@link android.hardware.usb.UsbAccessory} that represents - the attached accessory from the intent like this (with the add-on library):

        -
        -UsbAccessory accessory = UsbManager.getAccessory(intent);
        -
        - -

        or like this (with the platform APIs):

        -
        -UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        -
        - -

        Enumerating accessories

        - -

        You can have your application enumerate accesories that have identified themselves while your - application is running.

        - -

        Use the {@link android.hardware.usb.UsbManager#getAccessoryList() getAccessoryList()} method - to get an array all the USB accessories that are connected:

        -
        -UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        -UsbAccessory[] accessoryList = manager.getAcccessoryList();
        -
        - -

        Note: Currently, only one connected accessory is supported at - one time, but the API is designed to support multiple accessories in the future.

        - -

        Obtaining permission to communicate with an accessory

        - -

        Before communicating with the USB accessory, your applicaton must have permission from your - users.

        - -

        Note: If your application uses an - intent filter to discover accessories as they're connected, it automatically receives - permission if the user allows your application to handle the intent. If not, you must request - permission explicitly in your application before connecting to the accessory.

        - -

        Explicitly asking for permission might be neccessary in some situations such as when your - application enumerates accessories that are already connected and then wants to communicate with - one. You must check for permission to access an accessory before trying to communicate with it. - If not, you will receive a runtime error if the user denied permission to access the - accessory.

        - -

        To explicitly obtain permission, first create a broadcast receiver. This receiver listens for - the intent that gets broadcast when you call {@link - android.hardware.usb.UsbManager#requestPermission requestPermission()}. The call to {@link - android.hardware.usb.UsbManager#requestPermission requestPermission()} displays a dialog to the - user asking for permission to connect to the accessory. The following sample code shows how to - create the broadcast receiver:

        -
        -private static final String ACTION_USB_PERMISSION =
        -    "com.android.example.USB_PERMISSION";
        -private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        - 
        -    public void onReceive(Context context, Intent intent) {
        -        String action = intent.getAction();
        -        if (ACTION_USB_PERMISSION.equals(action)) {
        -            synchronized (this) {
        -                UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        -
        -                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
        -                    if(accessory != null){
        -                        //call method to set up accessory communication
        -                    }
        -                }
        -                else {
        -                    Log.d(TAG, "permission denied for accessory " + accessory);
        -                }
        -            }
        -        }
        -    }
        -};
        -
        - -

        To register the broadcast receiver, put this in your onCreate() method in your - activity:

        -
        -UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        -private static final String ACTION_USB_PERMISSION =
        -    "com.android.example.USB_PERMISSION";
        -...
        -mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        -IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        -registerReceiver(mUsbReceiver, filter);
        -
        - -

        To display the dialog that asks users for permission to connect to the accessory, call the - {@link android.hardware.usb.UsbManager#requestPermission requestPermission()} method:

        -
        -UsbAccessory accessory;
        -...
        -mUsbManager.requestPermission(accessory, mPermissionIntent);
        -
        - -

        When users reply to the dialog, your broadcast receiver receives the intent that contains the - {@link android.hardware.usb.UsbManager#EXTRA_PERMISSION_GRANTED} extra, which is a boolean - representing the answer. Check this extra for a value of true before connecting to the - accessory.

        - -

        Communicating with an accessory

        - -

        You can communicate with the accessory by using the {@link android.hardware.usb.UsbManager} to - obtain a file descriptor that you can set up input and output streams to read and write data to - descriptor. The streams represent the accessory's input and output bulk endpoints. You should set - up the communication between the device and accessory in another thread, so you don't lock the - main UI thread. The following example shows how to open an accessory to communicate with:

        -
        -UsbAccessory mAccessory;
        -ParcelFileDescriptor mFileDescriptor;
        -FileInputStream mInputStream;
        -FileOutputStream mOutputStream;
        -
        -...
        -
        -private void openAccessory() {
        -    Log.d(TAG, "openAccessory: " + accessory);
        -    mFileDescriptor = mUsbManager.openAccessory(mAccessory);
        -    if (mFileDescriptor != null) {
        -        FileDescriptor fd = mFileDescriptor.getFileDescriptor();
        -        mInputStream = new FileInputStream(fd);
        -        mOutputStream = new FileOutputStream(fd);
        -        Thread thread = new Thread(null, this, "AccessoryThread");
        -        thread.start();
        -    }
        -}
        -
        - -

        In the thread's run() method, you can read and write to the accessory by using - the {@link java.io.FileInputStream} or {@link java.io.FileOutputStream} objects. When reading - data from an accessory with a {@link java.io.FileInputStream} object, ensure that the buffer that - you use is big enough to store the USB packet data. The Android accessory protocol supports - packet buffers up to 16384 bytes, so you can choose to always declare your buffer to be of this - size for simplicity.

        - -

        Note: At a lower level, the packets are 64 bytes for USB - full-speed accessories and 512 bytes for USB high-speed accessories. The Android accessory - protocol bundles the packets together for both speeds into one logical packet for simplicity.

        - -

        For more information about using threads in Android, see Processes and - Threads.

        - -

        Terminating communication with an accessory

        - -

        When you are done communicating with an accessory or if the accessory was detached, close the - file descriptor that you opened by calling {@link android.os.ParcelFileDescriptor#close close()}. - To listen for detached events, create a broadcast receiver like below:

        -
        -BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        -    public void onReceive(Context context, Intent intent) {
        -        String action = intent.getAction(); 
        -
        -        if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
        -            UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        -            if (accessory != null) {
        -                // call your method that cleans up and closes communication with the accessory
        -            }
        -        }
        -    }
        -};
        -
        - -

        Creating the broadcast receiver within the application, and not the manifest, allows your - application to only handle detached events while it is running. This way, detached events are - only sent to the application that is currently running and not broadcast to all applications.

        - diff --git a/docs/html/guide/topics/usb/adk.jd b/docs/html/guide/topics/usb/adk.jd deleted file mode 100644 index c8949a30bf48..000000000000 --- a/docs/html/guide/topics/usb/adk.jd +++ /dev/null @@ -1,916 +0,0 @@ -page.title=Android Open Accessory Development Kit -@jd:body - - - -

        The Android 3.1 platform (also backported to Android 2.3.4) introduces Android Open Accessory - support, which allows external USB hardware (an Android USB accessory) to interact with an - Android-powered device in a special "accessory" mode. When an Android-powered powered device is - in accessory mode, the connected accessory acts as the USB host (powers the bus and enumerates - devices) and the Android-powered device acts as the USB device. Android USB accessories are - specifically designed to attach to Android-powered devices and adhere to a simple protocol - (Android accessory protocol) that allows them to detect Android-powered devices that support - accessory mode. Accessories must also provide 500mA at 5V for charging power. Many previously - released Android-powered devices are only capable of acting as a USB device and cannot initiate - connections with external USB devices. Android Open Accessory support overcomes this limitation - and allows you to build accessories that can interact with an assortment of Android-powered - devices by allowing the accessory to initiate the connection.

        - -

        Note: Accessory mode is ultimately dependent on the device's - hardware and not all devices will support accessory mode. Devices that support accessory mode can - be filtered using a <uses-feature> element in your corresponding application's - Android manifest. For more information, see the USB Accessory Developer Guide.

        - -

        The following list of distributers are currently producing Android Open Accessory compatible - development boards:

        - -
          - -
        • The Arduino Store provides the Arduino Mega ADK - (in EU nations - or non-EU nations) - that is based on the ATmega2560 and supports the ADK firmware.
        • - -
        • DIY - Drones provides an Arduino-compatible board geared towards RC (radio controlled) and UAV - (unmanned aerial vehicle) enthusiasts.
        • - -
        • mbed provides a microcontroller and a library - to develop accessories that support the Android accessory protocol. For more information, see - mbed with the Android ADK. -
        • - -
        • Microchip provides a PIC based USB - microcontroller board.
        • - -
        • Modern - Device provides an Arduino-compatible board that supports the ADK firmware.
        • - -
        • - RT Corp provides an Arduino-compatible board based on the Android ADK board design.
        • - -
        • - Seeed Studio provides an Arduino-compatible board that supports the ADK firmware.
        • - -
        • - SparkFun's IOIO board now has beta support for the ADK firmware.
        • - -
        - -

        We expect more hardware distributers to create a variety of kits, so please stay tuned for - further developments.

        - -

        ADK Components

        -

        The Android Open Accessory Development Kit (ADK) provides an implementation of an Android USB - accessory that is based on the Arduino open source electronics - prototyping platform, the accessory's hardware design files, code that implements the - accessory's firmware, and the Android application that interacts with the accessory. The hardware - design files and firmware code are contained in the ADK package download.

        -

        The main hardware and software components of the ADK include:

        - -
          -
        • A USB micro-controller board that is based on the Arduino Mega2560 and Circuits@Home USB - Host Shield designs (now referred to as the ADK board), which you will later implement as an - Android USB accessory. The ADK board provides input and output pins that you can implement - through the use of attachments called "shields." Custom firmware, written in C++, is installed - on the board to define the board's functionality and interaction with the attached shield and - Android-powered device. The hardware design files for the board are located in - hardware/ directory.
        • - -
        • An Android Demo Shield (ADK shield) that affixes atop the ADK board implements the input - and output points on the board. These implementations include a joystick, LED outputs, and - temperature and light sensors. You can create or buy your own shields or wire your own features - to the ADK board to implement custom functionality. The hardware design files for the shield - are located in hardware/.
        • - -
        • A library based on the Arduino USB Host Shield - library provides the logic for the USB micro-controller board to act as a USB Host. This allows - the board to initiate transactions with USB devices. Describing how to use this entire library - is out of the scope of this document. Where needed, this document points out important - interactions with the library. For more information, see the source code for the Arduino USB - Host Shield library in the firmware/arduino_libs/USB_Host_Shield directory.
        • - -
        • An Arduino sketch, firmware/demokit/demokit.pde, defines the firmware that - runs on the ADK board and is written in C++. The sketch calls the Android accessory protocol - library to interact with the Android-powered device. It also sends data from the ADK board and - shield to the Android application and receives data from the Android application and outputs it - to the ADK board and shield.
        • - -
        • The Android accessory protocol library, which is located in the - firmware/arduino_libs/AndroidAccessory directory. This library defines how to - enumerate the bus, find a connected Android-powered device that supports accessory mode, and - how to setup communication with the device.
        • - -
        • Other third party libraries to support the ADK board's functionality: - -
        • - -
        - -

        Getting Started with the ADK

        - -

        The following sections describe how to install the Arduino software on your computer, use the - Arduino software to install the ADK board's firmware, and install and run the accompanying - Android application for the ADK board. Before you begin, download the following items to set up - your development environment:

        - -
          -
        • Arduino Software: contains libraries - and an IDE for coding and installing firmware to the ADK board.
        • - -
        • CapSense library: contains the - libraries to sense human capacitance. This is needed for the capacative button that is located - on the ADK shield.
        • - -
        • The ADK package: contains the firmware for the ADK board and hardware design - files for the ADK board and shield.
        • -
        - -

        Installing the Arduino software and necessary libraries

        - -

        To install the Arduino software:

        - -
          -
        1. - Download and install the Arduino Software - as described on the Arduino website. - -

          Note: If you are on a Mac, install the FTDI USB Serial - Driver that is included in the Arduino package, even though the installation instructions say - otherwise.

          -
        2. - -
        3. Download and - extract the ADK package to a directory of your choice. You should have an app, - firmware, and hardware directories.
        4. - -
        5. Extract the CapSense download to a directory of your choice.
        6. - -
        7. Install the necessary libraries: - -

          On Windows:

          - -
            -
          1. Copy the firmware/arduino_libs/AndroidAccessory and - firmware/arduino_libs/USB_Host_Shield directories (the complete directories, - not just the files within) to the <arduino_installation_root>/libraries/ - directory.
          2. - -
          3. Create a CapSense directory in the - <arduino_installation_root>/libraries/ directory
          4. - -
          5. Copy CapSense.cpp and CapSense.h from the unzipped CapSense - download to the CapSense directory.
          6. -
          - -

          On Mac:

          - -
            -
          1. Create, if it does not already exist, an Arduino - directory inside your user account's Documents directory, and within - that, a libraries directory.
          2. - -
          3. Copy the firmware/arduino_libs/AndroidAccessory and - firmware/arduino_libs/USB_Host_Shield directories (the - complete directories, not just the files within) to your - Documents/Arduino/libraries/ directory.
          4. - -
          5. Create a CapSense directory in your - Documents/Arduino/libraries/ directory.
          6. - -
          7. Copy CapSense.cpp and CapSense.h from the unzipped CapSense - download to the CapSense directory.
          8. -
          - -

          On Linux (Ubuntu):

          - -
            -
          1. Copy the firmware/arduino_libs/AndroidAccessory and - firmware/arduino_libs/USB_Host_Shield directories (the complete directories, - not just the files within) to the <arduino_installation_root>/libraries/ - directory.
          2. - -
          3. Create a CapSense directory in the - <arduino_installation_root>/libraries/ directory.
          4. - -
          5. Copy CapSense.cpp and CapSense.h from the unzipped CapSense - download to the CapSense directory.
          6. - -
          7. Install the avr-libc library by entering sudo apt-get install avr-libc - from a shell prompt.
          8. -
          -
        8. -
        - -

        You should now have three new directories in the Arduino libraries directory: - AndroidAccessory, USB_Host_Shield, and CapSense.

        - -

        Installing the firmware to the ADK board

        - -

        To install the firmware to the ADK board:

        - -
          -
        1. Connect the ADK board to your computer using the micro-USB port, which allows two-way - communication and provides power to the ADK board.
        2. - -
        3. Launch Arduino.
        4. - -
        5. Click Tools > Board > Arduino Mega 2560 to specify the ADK board's - type.
        6. - -
        7. Select the appropriate USB port: - -
            -
          • On Windows: click Tools > Serial Port > COM# to specify the port - of communication. The COM port number varies depending on your computer. COM1 is usually - reserved for serial port connections. You most likely want COM2 or COM3.
          • - -
          • On Mac: Click Tools > Serial Port > dev/tty.usbserial-### to - specify the port of communication.
          • - -
          • On Linux (Ubuntu): Click Tools > Serial Port > dev/ttyUSB# to - specify the port of communication.
          • -
          -
        8. - -
        9. To open the firmware code (a sketch), click File > Open and select - firmware/demokit/demokit.pde.
        10. - -
        11. Click Sketch > Verify/Compile to ensure that the sketch has no - errors.
        12. - -
        13. Select File > Upload to I/O Board. When Arduino outputs Done - uploading., the board is ready to communicate with your Android-powered device.
        14. -
        - -

        Running the DemoKit Android application

        - -

        The DemoKit Android application runs on your Android-powered device and communicates with the - ADK board. The ADK board receives commands such as lighting up the board's LEDs or sends data - from the board such as joystick movement and temperature readings.

        - -

        To install and run the application in Eclipse:

        - -
          -
        1. Install the - Google APIs API Level 10 add-on library, which includes the Open Accessory library for - 2.3.4 devices that support accessory mode. This library is also forward compatible with Android - 3.1 or newer devices that support accessory mode. If you only care about Android 3.1 or newer - devices, all you need is API Level 12. For more information on deciding which API level to use, - see the USB Accessory - documentation.
        2. - -
        3. Click File > New > Project..., then select Android > - Android Project
        4. - -
        5. In the Project name: field, type DemoKit.
        6. - -
        7. Choose Create project from existing source, click Browse, - select the app directory, click Open to close that dialog and then - click Finish.
        8. - -
        9. For Build Target, select Google APIs (Platform 2.3.3, API Level 10). - -

          Note: Even though the add-on is labeled as - 2.3.3, the newest Google API add-on library for API level 10 adds USB Open - Accessory API support for 2.3.4 devices.

          -
        10. - -
        11. Click Finish.
        12. - -
        13. Install the application to your device.
        14. - -
        15. Connect the ADK board (USB-A) to your Android-powered device (micro-USB). Ensure that the - power cable to the accessory is plugged in or that the micro-USB port on the accesory is - connected to your computer for power (this also allows you to monitor the - ADK board). When connected, accept the prompt that asks for whether or not to open the - DemoKit application to connect to the accessory. If the prompt does not show up, connect and - reconnect the accessory.
        16. -
        - -

        You can now interact with the ADK board by moving the color LED or servo sliders (make sure - the servos are connected) or by pressing the relay buttons in the application. On the ADK shield, - you can press the buttons and move the joystick to see their outputs displayed in the - application.

        - -

        Monitoring the ADK Board

        - -

        The ADK firmware consists of a few files that you should be looking at if you want to build - your own accessory. The files in the firmware/arduino_libs/AndroidAccessory - directory are the most important files and have the logic to detect and connect to - Android-powered devices that support accessory mode. Feel free to add debug statements (Arduino - Serial.print() statements) to the code located in the - arduino_libraries_directory/AndroidAccessory directory and - firmware/demokit/demokit.pde sketch and re-upload the sketch to the ADK board to - discover more about how the firmware works.

        - -

        You can view the debug statements in the Arduino Serial Monitor by clicking Tools > - Serial Monitor and setting the baud to 115200. The following sections about how - accessories communicate with Android-powered devices describe much of what you should be doing in - your own accessory.

        - -

        Implementing the Android Accessory Protocol

        - -

        An Android USB accessory must adhere to Android Accessory Protocol, which defines how - an accessory detects and sets up communication with an Android-powered device. In general, an - accessory should carry out the following steps:

        - -
          -
        1. Wait for and detect connected devices
        2. - -
        3. Determine the device's accessory mode support
        4. - -
        5. Attempt to start the device in accessory mode if needed
        6. - -
        7. Establish communication with the device if it supports the Android accessory protocol
        8. -
        - -

        The following sections go into depth about how to implement these steps.

        - -

        Wait for and detect connected devices

        - -

        Your accessory should have logic to continuously check - for connected Android-powered devices. When a device is connected, your accessory should - determine if the device supports accessory mode.

        - -

        Determine the device's accessory mode support

        - - -

        When an Android-powered device is connected, it can be in one of three states:

        - -
          -
        1. The attached device supports Android accessory mode and is already in accessory mode.
        2. - -
        3. The attached device supports Android accessory mode, but it is not in accessory mode.
        4. - -
        5. The attached device does not support Android accessory mode.
        6. -
        - -

        During the initial connection, the accessory should check the vendor and product IDs of the - connected device's USB device descriptor. The vendor ID should match Google's ID (0x18D1) and the - product ID should be 0x2D00 or 0x2D01 if the device is already in accessory mode (case A). If so, - the accessory can now establish communication with the device through - bulk transfer endpoints with its own communication protocol. There is no need to start the device - in accessory mode.

        - -

        Note: 0x2D00 is reserved for Android-powered devices that - support accessory mode. 0x2D01 is reserved for devices that support accessory mode as well as the - ADB (Android Debug Bridge) protocol, which exposes a second interface with two bulk endpoints for - ADB. You can use these endpoints for debugging the accessory application if you are simulating - the accessory on a computer. In general, do not use this interface unless your accessory is - implementing a passthrough to ADB on the device.

        - -

        If the vendor and product ID do not match, there is no way to distinguish between states b and - c, so the accessory attempts to start the device in accessory mode to figure - out if the device is supported.

        - -

        Attempt to start the device in accessory mode

        - -

        If the vendor and product IDs do not correspond to an Android-powered device in accessory - mode, the accessory cannot discern whether the device supports accessory mode and is not in that - state, or if the device does not support accessory mode at all. This is because devices that - support accessory mode but aren't in it initially report the device's manufacturer vendor ID and - product ID, and not the special Android Open Accessory ones. In either case, the accessory should try to start - the device into accessory mode to figure out if the device supports it. The following steps - explain how to do this:

        - -
          -
        1. Send a 51 control request ("Get Protocol") to figure out if the device supports the Android - accessory protocol. A non-zero number is returned if the protocol is supported, which - represents the version of the protocol that the device supports (currently, only version 1 - exists). This request is a control request on endpoint 0 with the following characteristics: -
          -requestType:    USB_DIR_IN | USB_TYPE_VENDOR
          -request:        51
          -value:          0
          -index:          0
          -data:           protocol version number (16 bits little endian sent from the device to the accessory)
          -
          -
        2. - -
        3. If the device returns a proper protocol version, send identifying string information to the - device. This information allows the device to figure out an appropriate application for this - accessory and also present the user with a URL if an appropriate application does not exist. - These requests are control requests on endpoint 0 (for each string ID) with the following - characteristics: -
          -requestType:    USB_DIR_OUT | USB_TYPE_VENDOR
          -request:        52
          -value:          0
          -index:          string ID
          -data            zero terminated UTF8 string sent from accessory to device
          -
          - -

          The following string IDs are supported, with a maximum size of 256 bytes for each string - (must be zero terminated with \0).

          -
          -manufacturer name:  0
          -model name:         1
          -description:        2
          -version:            3
          -URI:                4
          -serial number:      5
          -
          -
        4. - -
        5. When the identifying strings are sent, request the device start up in accessory mode. This - request is a control request on endpoint 0 with the following characteristics: -
          -requestType:    USB_DIR_OUT | USB_TYPE_VENDOR
          -request:        53
          -value:          0
          -index:          0
          -data:           none
          -
          -
        6. -
        - -

        After sending the final control request, the connected USB device should re-introduce itself - on the bus in accessory mode and the accessory can re-enumerate the connected devices. The - algorithm jumps back to determining the device's accessory mode support - to check for the vendor and product ID. The vendor ID and product ID of the device will be - different if the device successfully switched to accessory mode and will now correspond to - Google's vendor and product IDs instead of the device manufacturer's IDs. The accessory can now - establish communication with the device.

        - -

        If at any point these steps fail, the device does not support Android accessory mode and the - accessory should wait for the next device to be connected.

        - -

        Establish communication with the device

        - -

        If an Android-powered device in accessory mode is detected, the accessory can query the - device's interface and endpoint descriptors to obtain the bulk endpoints to communicate with the - device. An Android-powered device that has a product ID of 0x2D00 has one interface with two bulk - endpoints for input and output communication. A device with product ID of 0x2D01 has two - interfaces with two bulk endpoints each for input and output communication. The first interface - is for standard communication while the second interface is for ADB communication. To communicate - on an interface, all you need to do is find the first bulk input and output endpoints, set the - device's configuration to a value of 1 with a SET_CONFIGURATION (0x09) device request, then - communicate using the endpoints.

        - -

        How the ADK board implements the Android Accessory protocol

        - -

        If you have access to the ADK board and shield, the following sections describe the firmware - code that you installed onto the ADK board. The firmware demonstrates a practical example of how - to implement the Android Accessory protocol. Even if you do not have the ADK board and shield, - reading through how the hardware detects and interacts with devices in accessory mode is still - useful if you want to port the code over for your own accessories.

        - -

        The important pieces of the firmware are the - accessory/demokit/demokit/demokit.pde sketch, which is the code that receives and - sends data to the DemoKit application running on the Android-powered device. The code to detect - and set up communication with the Android-powered device is contained in the - accessory/arduino_libs/AndroidAccessory/AndroidAccessory.h and - accessory/arduino_libs/AndroidAccessory/AndroidAccessory.cpp files. This code - includes most of the logic that will help you implement your own accessory's firmware. It might - be useful to have all three of these files open in a text editor as you read through these next - sections.

        - -

        The following sections describe the firmware code in the context of the algorithm described in - Implementing the Android Accessory Protocol.

        - -

        Wait for and detect connected devices

        - -

        In the firmware code (demokit.pde), the loop() function runs - repeatedly and calls AndroidAccessory::isConnected() to check for any connected - devices. If there is a connected device, it continuously updates the input and output streams - going to and from the board and application. If nothing is connected, it continuously checks for - a device to be connected:

        -
        -...
        -
        -AndroidAccessory acc("Google, Inc.",
        -                     "DemoKit",
        -                     "DemoKit Arduino Board",
        -                     "1.0",
        -                     "http://www.android.com",
        -                     "0000000012345678");
        -
        -...
        -void loop()
        -{
        -...
        -    if (acc.isConnected()) {
        -        //communicate with Android application
        -    }
        -    else{
        -        //set the accessory to its default state
        -    }
        -...
        -}
        -
        - -

        Determine the connected device's accessory mode support

        - -

        When a device is connected to the ADK board, it can already be in accessory mode, support - accessory mode and is not in that mode, or does not support accessory mode. The - AndroidAccessory::isConnected() method checks for these cases and responds - accordingly when the loop() function calls it. This function first checks to see if - the device that is connected hasn't already been handled. If not, it gets the connected device's - device descriptor to figure out if the device is already in accessory mode by calling - AndroidAccessory::isAccessoryDevice(). This method checks the vendor and product ID - of the device descriptor. A device in accessory mode has a vendor ID of 0x18D1 and a product ID - of 0x2D00 or 0x2D01. If the device is in accessory mode, then the ADK board can establish communication with the device. If not, the board attempts to start the device in accessory mode.

        -
        -bool AndroidAccessory::isConnected(void)
        -{
        -    USB_DEVICE_DESCRIPTOR *devDesc = (USB_DEVICE_DESCRIPTOR *) descBuff;
        -    byte err;
        -
        -    max.Task();
        -    usb.Task();
        -
        -    if (!connected &&
        -        usb.getUsbTaskState() >= USB_STATE_CONFIGURING &&
        -        usb.getUsbTaskState() != USB_STATE_RUNNING) {
        -        Serial.print("\nDevice addressed... ");
        -        Serial.print("Requesting device descriptor.");
        -
        -        err = usb.getDevDescr(1, 0, 0x12, (char *) devDesc);
        -        if (err) {
        -            Serial.print("\nDevice descriptor cannot be retrieved. Program Halted\n");
        -            while(1);
        -        }
        -
        -        if (isAccessoryDevice(devDesc)) {
        -            Serial.print("found android accessory device\n");
        -
        -            connected = configureAndroid();
        -        } else {
        -            Serial.print("found possible device. switching to serial mode\n");
        -            switchDevice(1);
        -        }
        -    } else if (usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
        -        connected = false;
        -    }
        -
        -    return connected;
        -}
        -
        - -

        Attempt to start the device in accessory mode

        - -

        If the device is not already in accessory mode, then the ADK board must determine whether or - not it supports it by sending control request 51 to check the version of the USB accessory - protocol that the device supports (see AndroidAccessory::getProtocol()). Protocol - version 1 is the only version for now, but this can be an integer greater than zero in the - future. If the appropriate protocol version is returned, the board sends control request 52 (one - for each string with AndroidAcessory:sendString()) to send it's identifying - information, and tries to start the device in accessory mode with control request 53. The - AndroidAccessory::switchDevice() method takes care of this:

        -
        -bool AndroidAccessory::switchDevice(byte addr)
        -{
        -    int protocol = getProtocol(addr);
        -    if (protocol == 1) {
        -        Serial.print("device supports protocol 1\n");
        -    } else {
        -        Serial.print("could not read device protocol version\n");
        -        return false;
        -    }
        -
        -    sendString(addr, ACCESSORY_STRING_MANUFACTURER, manufacturer);
        -    sendString(addr, ACCESSORY_STRING_MODEL, model);
        -    sendString(addr, ACCESSORY_STRING_DESCRIPTION, description);
        -    sendString(addr, ACCESSORY_STRING_VERSION, version);
        -    sendString(addr, ACCESSORY_STRING_URI, uri);
        -    sendString(addr, ACCESSORY_STRING_SERIAL, serial);
        -
        -    usb.ctrlReq(addr, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE,
        -                ACCESSORY_START, 0, 0, 0, 0, NULL);
        -    return true;
        -}
        -
        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 establishes communication with the device. - -

        Establish communication with the device

        - -

        If a device is detected as being in accessory mode, the accessory must find the proper bulk - endpoints and set up communication with the device. When the ADK board detects an Android-powered - device in accessory mode, it calls the AndroidAccessory::configureAndroid() - function:

        -
        -...
        -if (isAccessoryDevice(devDesc)) {
        -            Serial.print("found android acessory device\n");
        -
        -            connected = configureAndroid();
        -        }
        -...
        -
        - -

        which in turn calls the findEndpoints() function:

        -
        -...
        -bool AndroidAccessory::configureAndroid(void)
        -{
        -    byte err;
        -    EP_RECORD inEp, outEp;
        -
        -    if (!findEndpoints(1, &inEp, &outEp))
        -        return false;
        -...
        -
        - -

        The AndroidAccessory::findEndpoints() function queries the Android-powered - device's configuration descriptor and finds the bulk data endpoints in which to communicate with - the USB device. To do this, it first gets the device's first four bytes of the configuration - descriptor (only need descBuff[2] and descBuff[3]), which contains the information about the - total length of data returned by getting the descriptor. This data is used to determine whether - or not the descriptor can fit in the descriptor buffer. This descriptor also contains information - about all the interfaces and endpoint descriptors. If the descriptor is of appropriate size, the - method reads the entire configuration descriptor and fills the entire descriptor buffer with this - device's configuration descriptor. If for some reason the descriptor is no longer attainable, an - error is returned.

        -
        -...
        -
        -bool AndroidAccessory::findEndpoints(byte addr, EP_RECORD *inEp, EP_RECORD *outEp)
        -{
        -    int len;
        -    byte err;
        -    uint8_t *p;
        -
        -    err = usb.getConfDescr(addr, 0, 4, 0, (char *)descBuff);
        -    if (err) {
        -        Serial.print("Can't get config descriptor length\n");
        -        return false;
        -    }
        -
        -
        -    len = descBuff[2] | ((int)descBuff[3] << 8);
        -    if (len > sizeof(descBuff)) {
        -        Serial.print("config descriptor too large\n");
        -            /* might want to truncate here */
        -        return false;
        -    }
        -
        -    err = usb.getConfDescr(addr, 0, len, 0, (char *)descBuff);
        -    if (err) {
        -        Serial.print("Can't get config descriptor\n");
        -        return false;
        -    }
        -
        -...
        -
        - -

        Once the descriptor is in memory, a pointer is assigned to the first position of the buffer - and is used to index the buffer for reading. There are two endpoint pointers (input and output) - that are passed into AndroidAccessory::findEndpoints() and their addresses are set - to 0, because the code hasn't found any suitable bulk endpoints yet. A loop reads the buffer, - parsing each configuration, interface, or endpoint descriptor. For each descriptor, Position 0 - always contains the size of the descriptor in bytes and position 1 always contains the descriptor - type. Using these two values, the loop skips any configuration and interface descriptors and - increments the buffer with the descLen variable to get to the next descriptor.

        - -

        Note: An Android-powered device in accessory mode can - potentially have two interfaces, one for the default communication to the device and the other - for ADB communication. The default communication interface is always indexed first, so finding - the first input and output bulk endpoints will return the default communication endpoints, which - is what the demokit.pde sketch does. If you are writing your own firmware, the logic - to find the appropriate endpoints for your accessory might be different.

        - -

        When it finds the first input and output endpoint descriptors, it sets the endpoint pointers - to those addresses. If the findEndpoints() function finds both an input and output endpoint, it - returns true. It ignores any other endpoints that it finds (the endpoints for the ADB interface, - if present).

        -
        -...
        -    p = descBuff;
        -    inEp->epAddr = 0;
        -    outEp->epAddr = 0;
        -    while (p < (descBuff + len)){
        -        uint8_t descLen = p[0];
        -        uint8_t descType = p[1];
        -        USB_ENDPOINT_DESCRIPTOR *epDesc;
        -        EP_RECORD *ep;
        -
        -        switch (descType) {
        -        case USB_DESCRIPTOR_CONFIGURATION:
        -            Serial.print("config desc\n");
        -            break;
        -
        -        case USB_DESCRIPTOR_INTERFACE:
        -            Serial.print("interface desc\n");
        -            break;
        -
        -        case USB_DESCRIPTOR_ENDPOINT:
        -            epDesc = (USB_ENDPOINT_DESCRIPTOR *)p;
        -            if (!inEp->epAddr && (epDesc->bEndpointAddress & 0x80))
        -                ep = inEp;
        -            else if (!outEp->epAddr)
        -                ep = outEp;
        -            else
        -                ep = NULL;
        -
        -            if (ep) {
        -                ep->epAddr = epDesc->bEndpointAddress & 0x7f;
        -                ep->Attr = epDesc->bmAttributes;
        -                ep->MaxPktSize = epDesc->wMaxPacketSize;
        -                ep->sndToggle = bmSNDTOG0;
        -                ep->rcvToggle = bmRCVTOG0;
        -            }
        -            break;
        -
        -        default:
        -            Serial.print("unkown desc type ");
        -            Serial.println( descType, HEX);
        -            break;
        -        }
        -
        -        p += descLen;
        -    }
        -
        -    if (!(inEp->epAddr && outEp->epAddr))
        -        Serial.println("can't find accessory endpoints");
        -
        -    return inEp->epAddr && outEp->epAddr;
        -}
        -
        -...
        -
        - -

        Back in the configureAndroid() function, if there were endpoints found, they are - appropriately set up for communication. The device's configuration is set to 1 and the state of - the device is set to "running", which signifies that the device is properly set up to communicate - with your USB accessory. Setting this status prevents the device from being re-detected and - re-configured in the AndroidAccessory::isConnected() function.

        -
        -bool AndroidAccessory::configureAndroid(void)
        -{
        -    byte err;
        -    EP_RECORD inEp, outEp;
        -
        -    if (!findEndpoints(1, &inEp, &outEp))
        -        return false;
        -
        -    memset(&epRecord, 0x0, sizeof(epRecord));
        -
        -    epRecord[inEp.epAddr] = inEp;
        -    if (outEp.epAddr != inEp.epAddr)
        -        epRecord[outEp.epAddr] = outEp;
        -
        -    in = inEp.epAddr;
        -    out = outEp.epAddr;
        -
        -    Serial.print("inEp: ");
        -    Serial.println(inEp.epAddr, HEX);
        -    Serial.print("outEp: ");
        -    Serial.println(outEp.epAddr, HEX);
        -
        -    epRecord[0] = *(usb.getDevTableEntry(0,0));
        -    usb.setDevTableEntry(1, epRecord);
        -
        -    err = usb.setConf( 1, 0, 1 );
        -    if (err) {
        -        Serial.print("Can't set config to 1\n");
        -        return false;
        -    }
        -
        -    usb.setUsbTaskState( USB_STATE_RUNNING );
        -
        -    return true;
        -}
        -
        - -

        Lastly, methods to read and write to the appropriate endpoints are needed. The - demokit.pde sketch calls these methods depending on the data that is read from the - Android-powered device or sent by the ADK board. For instance, moving the joystick on the ADK - shield writes data that is read by the DemoKit application running on the Android-powered device. - Moving sliders on the DemoKit application is read by the demokit.pde sketch and - changes the state of the accessory, such as lighting up or changing the color of the LED - lights.

        -
        -int AndroidAccessory::read(void *buff, int len, unsigned int nakLimit) {
        -  return usb.newInTransfer(1, in, len, (char *)buff, nakLimit); }
        -
        -int AndroidAccessory::write(void *buff, int len) {
        -  usb.outTransfer(1, out, len, (char *)buff);
        -  return len; }
        -
        -
        - -

        See the firmware/demokit/demokit.pde file for information about how the ADK board - reads and writes data.

        diff --git a/docs/html/guide/topics/usb/host.jd b/docs/html/guide/topics/usb/host.jd deleted file mode 100644 index b56175445159..000000000000 --- a/docs/html/guide/topics/usb/host.jd +++ /dev/null @@ -1,440 +0,0 @@ -page.title=USB Host -@jd:body - - - -

        When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, - and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.

        - -

        API Overview

        - -

        Before you begin, it is important to understand the classes that you need to work with. The - following table describes the USB host APIs in the {@link android.hardware.usb} package.

        - -

        Table 1. USB Host APIs

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        ClassDescription
        {@link android.hardware.usb.UsbManager}Allows you to enumerate and communicate with connected USB devices.
        {@link android.hardware.usb.UsbDevice}Represents a connected USB device and contains methods to access its identifying - information, interfaces, and endpoints.
        {@link android.hardware.usb.UsbInterface}Represents an interface of a USB device, which defines a set of functionality for the - device. A device can have one or more interfaces on which to communicate on.
        {@link android.hardware.usb.UsbEndpoint}Represents an interface endpoint, which is a communication channel for this interface. An - interface can have one or more endpoints, and usually has input and output endpoints for - two-way communication with the device.
        {@link android.hardware.usb.UsbDeviceConnection}Represents a connection to the device, which transfers data on endpoints. This class - allows you to send data back and forth sychronously or asynchronously.
        {@link android.hardware.usb.UsbRequest}Represents an asynchronous request to communicate with a device through a {@link - android.hardware.usb.UsbDeviceConnection}.
        {@link android.hardware.usb.UsbConstants}Defines USB constants that correspond to definitions in linux/usb/ch9.h of the Linux - kernel.
        - -

        In most situations, you need to use all of these classes ({@link - android.hardware.usb.UsbRequest} is only required if you are doing asynchronous communication) - when communicating with a USB device. In general, you obtain a {@link - android.hardware.usb.UsbManager} to retrieve the desired {@link android.hardware.usb.UsbDevice}. - When you have the device, you need to find the appropriate {@link - android.hardware.usb.UsbInterface} and the {@link android.hardware.usb.UsbEndpoint} of that - interface to communicate on. Once you obtain the correct endpoint, open a {@link - android.hardware.usb.UsbDeviceConnection} to communicate with the USB device.

        - -

        Android Manifest Requirements

        - -

        The following list describes what you need to add to your application's manifest file before - working with the USB host APIs:

        - -
          -
        • Because not all Android-powered devices are guaranteed to support the USB host APIs, - include a <uses-feature> element that declares that your application uses - the android.hardware.usb.host feature.
        • - -
        • Set the minimum SDK of the application to API Level 12 or higher. The USB host APIs are not - present on earlier API levels.
        • - -
        • If you want your application to be notified of an attached USB device, specify an - <intent-filter> and <meta-data> element pair for the - android.hardware.usb.action.USB_DEVICE_ATTACHED intent in your main activity. The - <meta-data> element points to an external XML resource file that declares - identifying information about the device that you want to detect. - -

          In the XML resource file, declare <usb-device> elements for the USB - devices that you want to filter. The following list describes the attributes of - <usb-device>. In general, use vendor and product ID if you want to filter - for a specific device and use class, subclass, and protocol if you want to filter for a group - of USB devices, such as mass storage devices or digital cameras. You can specify none or - all of these attributes. Specifying no attributes matches every USB device, so only do this - if your application requires it:

          - -
            -
          • vendor-id
          • - -
          • product-id
          • - -
          • class
          • - -
          • subclass
          • - -
          • protocol (device or interface)
          • -
          - -

          Save the resource file in the res/xml/ directory. The resource file name - (without the .xml extension) must be the same as the one you specified in the - <meta-data> element. The format for the XML resource file is in the - example below.

          -
        • -
        - -

        Manifest and resource file examples

        - -

        The following example shows a sample manifest and its corresponding resource file:

        -
        -<manifest ...>
        -    <uses-feature android:name="android.hardware.usb.host" />
        -    <uses-sdk android:minSdkVersion="12" />
        -    ...
        -    <application>
        -        <activity ...>
        -            ...
        -            <intent-filter>
        -                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        -            </intent-filter>
        -
        -            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        -                android:resource="@xml/device_filter" />
        -        </activity>
        -    </application>
        -</manifest>
        -
        - -

        In this case, the following resource file should be saved in - res/xml/device_filter.xml and specifies that any USB device with the specified - attributes should be filtered:

        -
        -<?xml version="1.0" encoding="utf-8"?>
        -
        -<resources>
        -    <usb-device vendor-id="1234" product-id="5678" class="255" subclass="66" protocol="1" />
        -</resources>
        -
        - -

        Working with Devices

        - -

        When users connect USB devices to an Android-powered device, the Android system can determine - whether your application is interested in the connected device. If so, you can set up - communication with the device if desired. To do this, your application has to:

        - -
          -
        1. Discover connected USB devices by using an intent filter to be notified when the user - connects a USB device or by enumerating USB devices that are already connected.
        2. - -
        3. Ask the user for permission to connect to the USB device, if not already obtained.
        4. - -
        5. Communicate with the USB device by reading and writing data on the appropriate interface - endpoints.
        6. -
        - -

        Discovering a device

        - -

        Your application can discover USB devices by either using an intent filter to be notified when - the user connects a device or by enumerating USB devices that are already connected. Using an - intent filter is useful if you want to be able to have your application automatically detect a - desired device. Enumerating connected USB devices is useful if you want to get a list of all - connected devices or if your application did not filter for an intent.

        - -

        Using an intent filter

        - -

        To have your application discover a particular USB device, you can specify an intent filter to - filter for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent. Along with - this intent filter, you need to specify a resource file that specifies properties of the USB - device, such as product and vendor ID. When users connect a device that matches your device - filter, the system presents them with a dialog that asks if they want to start your application. - If users accept, your application automatically has permission to access the device until the - device is disconnected.

        - -

        The following example shows how to declare the intent filter:

        -
        -<activity ...>
        -...
        -    <intent-filter>
        -        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        -    </intent-filter>
        -
        -    <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        -        android:resource="@xml/device_filter" />
        -</activity>
        -
        - -

        The following example shows how to declare the corresponding resource file that specifies the - USB devices that you're interested in:

        -
        -<?xml version="1.0" encoding="utf-8"?>
        -
        -<resources>
        -    <usb-device vendor-id="1234" product-id="5678" />
        -</resources>
        -
        - -

        In your activity, you can obtain the {@link android.hardware.usb.UsbDevice} that represents - the attached device from the intent like this:

        -
        -UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        -
        - -

        Enumerating devices

        - -

        If your application is interested in inspecting all of the USB devices currently connected - while your application is running, it can enumerate devices on the bus. Use the {@link - android.hardware.usb.UsbManager#getDeviceList() getDeviceList()} method to get a hash map of all - the USB devices that are connected. The hash map is keyed by the USB device's name if you want to - obtain a device from the map.

        -
        -UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        -...  
        -HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        -UsbDevice device = deviceList.get("deviceName");
        -
        - -

        If desired, you can also just obtain an iterator from the hash map and process each device one - by one:

        -
        -UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        -...
        -HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        -Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        -while(deviceIterator.hasNext()){
        -    UsbDevice device = deviceIterator.next()
        -    //your code
        -}
        -
        - -

        Obtaining permission to communicate with a device

        - -

        Before communicating with the USB device, your applicaton must have permission from your - users.

        - -

        Note: If your application uses an - intent filter to discover USB devices as they're connected, it automatically receives - permission if the user allows your application to handle the intent. If not, you must request - permission explicitly in your application before connecting to the device.

        - -

        Explicitly asking for permission might be neccessary in some situations such as when your - application enumerates USB devices that are already connected and then wants to communicate with - one. You must check for permission to access a device before trying to communicate with it. If - not, you will receive a runtime error if the user denied permission to access the device.

        - -

        To explicitly obtain permission, first create a broadcast receiver. This receiver listens for - the intent that gets broadcast when you call {@link - android.hardware.usb.UsbManager#requestPermission requestPermission()}. The call to {@link - android.hardware.usb.UsbManager#requestPermission requestPermission()} displays a dialog to the - user asking for permission to connect to the device. The following sample code shows how to - create the broadcast receiver:

        -
        -private static final String ACTION_USB_PERMISSION =
        -    "com.android.example.USB_PERMISSION";
        -private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        -
        -    public void onReceive(Context context, Intent intent) {
        -        String action = intent.getAction();
        -        if (ACTION_USB_PERMISSION.equals(action)) {
        -            synchronized (this) {
        -                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        -
        -                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
        -                    if(device != null){
        -                      //call method to set up device communication
        -                   }
        -                } 
        -                else {
        -                    Log.d(TAG, "permission denied for device " + device);
        -                }
        -            }
        -        }
        -    }
        -};
        -
        - -

        To register the broadcast receiver, add this in your onCreate() method in your - activity:

        -
        -UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        -private static final String ACTION_USB_PERMISSION =
        -    "com.android.example.USB_PERMISSION";
        -...
        -mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        -IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        -registerReceiver(mUsbReceiver, filter);
        -
        - -

        To display the dialog that asks users for permission to connect to the device, call the {@link - android.hardware.usb.UsbManager#requestPermission requestPermission()} method:

        -
        -UsbDevice device;
        -...
        -mUsbManager.requestPermission(device, mPermissionIntent);
        -
        - -

        When users reply to the dialog, your broadcast receiver receives the intent that contains the - {@link android.hardware.usb.UsbManager#EXTRA_PERMISSION_GRANTED} extra, which is a boolean - representing the answer. Check this extra for a value of true before connecting to the - device.

        - -

        Communicating with a device

        - -

        Communication with a USB device can be either synchronous or asynchronous. In either case, you - should create a new thread on which to carry out all data transmissions, so you don't block the - UI thread. To properly set up communication with a device, you need to obtain the appropriate - {@link android.hardware.usb.UsbInterface} and {@link android.hardware.usb.UsbEndpoint} of the - device that you want to communicate on and send requests on this endpoint with a {@link - android.hardware.usb.UsbDeviceConnection}. In general, your code should:

        - -
          -
        • Check a {@link android.hardware.usb.UsbDevice} object's attributes, such as product ID, - vendor ID, or device class to figure out whether or not you want to communicate with the - device.
        • - -
        • When you are certain that you want to communicate with the device, find the appropriate - {@link android.hardware.usb.UsbInterface} that you want to use to communicate along with the - appropriate {@link android.hardware.usb.UsbEndpoint} of that interface. Interfaces can have one - or more endpoints, and commonly will have an input and output endpoint for two-way - communication.
        • - -
        • When you find the correct endpoint, open a {@link android.hardware.usb.UsbDeviceConnection} - on that endpoint.
        • - -
        • Supply the data that you want to transmit on the endpoint with the {@link - android.hardware.usb.UsbDeviceConnection#bulkTransfer bulkTransfer()} or {@link - android.hardware.usb.UsbDeviceConnection#controlTransfer controlTransfer()} method. You should - carry out this step in another thread to prevent blocking the main UI thread. For more - information about using threads in Android, see Processes and - Threads.
        • -
        - -

        The following code snippet is a trivial way to do a synchronous data transfer. Your code - should have more logic to correctly find the correct interface and endpoints to communicate on - and also should do any transferring of data in a different thread than the main UI thread:

        -
        -private Byte[] bytes
        -private static int TIMEOUT = 0;
        -private boolean forceClaim = true;
        -
        -...
        -
        -UsbInterface intf = device.getInterface(0);
        -UsbEndpoint endpoint = intf.getEndpoint(0);
        -UsbDeviceConnection connection = mUsbManager.openDevice(device); 
        -connection.claimInterface(intf, forceClaim);
        -connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //do in another thread
        -
        - -

        To send data asynchronously, use the {@link android.hardware.usb.UsbRequest} class to {@link - android.hardware.usb.UsbRequest#initialize initialize} and {@link - android.hardware.usb.UsbRequest#queue queue} an asynchronous request, then wait for the result - with {@link android.hardware.usb.UsbDeviceConnection#requestWait requestWait()}.

        - -

        For more information, see the AdbTest sample, which shows how to do - asynchronous bulk transfers, and the MissleLauncher sample, which - shows how to listen on an interrupt endpoint asynchronously.

        - -

        Terminating communication with a device

        - -

        When you are done communicating with a device or if the device was detached, close the {@link - android.hardware.usb.UsbInterface} and {@link android.hardware.usb.UsbDeviceConnection} by - calling {@link android.hardware.usb.UsbDeviceConnection#releaseInterface releaseInterface()} and - {@link android.hardware.usb.UsbDeviceConnection#close() close()}. To listen for detached events, - create a broadcast receiver like below:

        -
        -BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        -    public void onReceive(Context context, Intent intent) {
        -        String action = intent.getAction(); 
        -
        -      if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
        -            UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        -            if (device != null) {
        -                // call your method that cleans up and closes communication with the device
        -            }
        -        }
        -    }
        -};
        -
        - -

        Creating the broadcast receiver within the application, and not the manifest, allows your - application to only handle detached events while it is running. This way, detached events are - only sent to the application that is currently running and not broadcast to all applications.

        - diff --git a/docs/html/guide/topics/usb/index.jd b/docs/html/guide/topics/usb/index.jd deleted file mode 100644 index ef53bdf7c5db..000000000000 --- a/docs/html/guide/topics/usb/index.jd +++ /dev/null @@ -1,67 +0,0 @@ -page.title=USB Host and Accessory -@jd:body - -
        -
        -

        Topics

        - -
          -
        1. USB Accessory
        2. - -
        3. USB Host
        4. -
        -
        -
        - -

        Android supports a variety of USB peripherals and Android USB accessories (hardware that - implements the Android accessory protocol) through two modes: USB accessory and USB host. In USB - accessory mode, the external USB hardware act as the USB hosts. Examples of accessories might - include robotics controllers; docking stations; diagnostic and musical equipment; kiosks; card - readers; and much more. This gives Android-powered devices that do not have host capabilities the - ability to interact with USB hardware. Android USB accessories must be designed to work with - Android-powered devices and must adhere to the Android accessory communication protocol. In USB - host mode, the Android-powered device acts as the host. Examples of devices include digital - cameras, keyboards, mice, and game controllers. USB devices that are designed for a wide range of - applications and environments can still interact with Android applications that can correctly - communicate with the device.

        - -

        Figure 1 shows the differences between the two modes. When the Android-powered device is in - host mode, it acts as the USB host and powers the bus. When the Android-powered device is in USB - accessory mode, the connected USB hardware (an Android USB accessory in this case) acts as the - host and powers the bus.

        - -

        Figure 1. USB Host and Accessory Modes

        - -

        USB accessory and host modes are directly supported in Android 3.1 (API level 12) or newer - platforms. USB accessory mode is also backported to Android 2.3.4 (API level 10) as an add-on - library to support a broader range of devices. Device manufacturers can choose whether or not to - include the add-on library on the device's system image.

        - -

        Note: Support for USB host and accessory modes are ultimately - dependant on the device's hardware, regardless of platform level. You can filter for devices that - support USB host and accessory through a <uses-feature> element. See - the USB accessory and host documentation for more details.

        - -

        Debugging considerations

        - -

        When debugging applications that use USB accessory or host features, you most likely will have - USB hardware connected to your Android-powered device. This will prevent you from having an - adb connection to the Android-powered device via USB. You can still access - adb over a network connection. To enable adb over a network - connection:

        - -
          -
        1. Connect the Android-powered device via USB to your computer.
        2. - -
        3. From your SDK platform-tools/ directory, enter adb tcpip 5555 at - the command prompt.
        4. - -
        5. Enter adb connect <device-ip-address>:5555 You should now be connected - to the Android-powered device and can issue the usual adb commands like adb - logcat.
        6. - -
        7. To set your device to listen on USB, enter adb usb.
        8. -
        diff --git a/docs/html/guide/topics/views/custom-views.jd b/docs/html/guide/topics/views/custom-views.jd deleted file mode 100644 index 8589b1a01a1a..000000000000 --- a/docs/html/guide/topics/views/custom-views.jd +++ /dev/null @@ -1,544 +0,0 @@ -page.title=Building Custom Views -parent.title=Views and Layout -parent.link=index.html -@jd:body - -

        Android offers a sophisticated and powerful componentized model for building your UI, based on the fundamental building block classes {@link android.view.View} and {@link android.view.ViewGroup}. To start with, the platform includes a variety of prebuilt View and ViewGroup subclasses — called widgets and layouts, respectively — that you can use to construct your UI. The widgets and layouts are fully implemented and handle all of their own measuring and drawing, so you can use them right away. You can make new types of UI elements simply by nesting and grouping the widgets and layouts. Using widgets and layouts is the recommended approach to building a UI for your applications.

        - -

        A partial list of available widgets includes {@link android.widget.Button Button}, -{@link android.widget.TextView TextView}, -{@link android.widget.EditText EditText}, -{@link android.widget.ListView ListView}, -{@link android.widget.CheckBox CheckBox}, -{@link android.widget.RadioButton RadioButton}, -{@link android.widget.Gallery Gallery}, -{@link android.widget.Spinner Spinner}, and the more special-purpose -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, -{@link android.widget.ImageSwitcher ImageSwitcher}, and -{@link android.widget.TextSwitcher TextSwitcher}.

        - -

        Among the layouts available are {@link android.widget.LinearLayout LinearLayout}, -{@link android.widget.FrameLayout FrameLayout}, {@link android.widget.AbsoluteLayout AbsoluteLayout}, and others. For more examples, see Common Layout Objects.

        - -

        If none of the prebuilt widgets or layouts meets your needs, you can also create your own View subclass, such as a layout group or compound control. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout and override its methods. -

        - -

        Creating your own View subclasses gives you precise control over the appearance and function of a screen element. To give an idea of the control you get with custom views, here are some examples of what you could do with them:

        - -
          -
        • - You could create a completely custom-rendered View type, for example a "volume - control" knob rendered using 2D graphics, and which resembles an - analog electronic control. -
        • -
        • - You could combine a group of View components into a new single component, perhaps - to make something like a ComboBox (a combination of popup list and free - entry text field), a dual-pane selector control (a left and right pane - with a list in each where you can re-assign which item is in which - list), and so on. -
        • -
        • - You could override the way that an EditText component is rendered on the screen - (the Notepad sample uses this to good effect, - to create a lined-notepad page). -
        • -
        • - You could capture other events like key presses and handle them in some custom - way (such as for a game). -
        • -
        -

        -The sections below explain how to create custom Views and use them in your application. -For detailed reference information, see the {@link android.view.View} class.

        - -

        This document covers the following:

        -
          -
        1. The Basic Approach
        2. -
        3. Fully Customized Views
        4. -
        5. Customized View Example
        6. -
        7. Compound Controls
        8. -
        9. Modifying an Existing Component Type
        10. -
        - - -

        The Basic Approach -

        -

        -These steps provide a high level overview of -what you need to know to get started in creating your own -View components:

        - -
          -
        1. - Extend an existing {@link android.view.View View} class or subclass - with your own class. -
        2. -
        3. - Override some of the methods from the superclass: the superclass methods - to override start with 'on', for - example, {@link android.view.View#onDraw onDraw()}, - {@link android.view.View#onMeasure onMeasure()}, and - {@link android.view.View#onKeyDown onKeyDown()}. -
            -
          • - This is similar to the on... events in {@link android.app.Activity - Activity} or {@link android.app.ListActivity ListActivity} - that you override for life cycle and other functionality hooks. -
          • -
          -
        4. - Use your new extension class: once completed, your new extension class - can be used in place of the view upon which it was based, but now with the new - functionality. -
        5. -
        -

        Tip: - Extension classes can be defined as inner classes inside the activities - that use them. This is useful because it controls access to them but - isn't necessary (perhaps you want to create a new public View for - wider use in your application). -

        - - -

        Fully Customized Components

        -

        -Fully customized components can be used to create graphical components that -appear however you wish. Perhaps a graphical VU -meter that looks like an old analog gauge, or a sing-a-long text view where -a bouncing ball moves along the words so you can sing along with a karaoke -machine. Either way, you want something that the built-in components just -won't do, no matter how you combine them.

        -

        Fortunately, you can easily create components that look and behave in any -way you like, limited perhaps only by your imagination, the size of the -screen, and the available processing power (remember that ultimately your -application might have to run on something with significantly less power -than your desktop workstation).

        -

        To create a fully customized component:

        -
          -
        1. - The most generic view you can extend is, unsurprisingly, {@link - android.view.View View}, so you will usually start by extending this to - create your new super component. -
        2. -
        3. - You can supply a constructor which can - take attributes and parameters from the XML, and you can also consume - your own such attributes and parameters (perhaps the color and range of - the VU meter, or the width and damping of the needle, etc.) -
        4. -
        5. - You will probably want to create your own event listeners, - property accessors and modifiers, and possibly more sophisticated - behavior in your component class as well. -
        6. -
        7. - You will almost certainly want to override onMeasure() and - are also likely to need to override onDraw() if you want - the component to show something. While both have default behavior, - the default onDraw() will do nothing, and the default - onMeasure() will always set a size of 100x100 — which is - probably not what you want. -
        8. -
        9. - Other on... methods may also be overridden as required. -
        10. -
        -

        onDraw() and onMeasure()

        -

        onDraw() delivers you a {@link android.graphics.Canvas Canvas} -upon which you can implement anything you want: 2D graphics, other standard or -custom components, styled text, or anything else you can think of.

        -

        Note: -Except for 3D graphics. If you want to -use 3D graphics, you must extend {@link android.view.SurfaceView SurfaceView} -instead of View, and draw from a separate thread. See the -GLSurfaceViewActivity sample -for details.

        -

        onMeasure() is a little more involved. onMeasure() -is a critical piece of the rendering contract between your component and its -container. onMeasure() should be overridden to efficiently and -accurately report the measurements of its contained parts. This is made -slightly more complex by the requirements of limits from the parent -(which are passed in to the onMeasure() method) and by the -requirement to call the setMeasuredDimension() method with the -measured width and height once they have been calculated. If you fail to -call this method from an overridden onMeasure() method, the -result will be an exception at measurement time.

        -

        At a high level, implementing onMeasure() looks something - like this:

        - -
          -
        1. - The overridden onMeasure() method is called with width and - height measure specifications (widthMeasureSpec and - heightMeasureSpec parameters, both are integer codes - representing dimensions) which should be treated as requirements for - the restrictions on the width and height measurements you should produce. A - full reference to the kind of restrictions these specifications can require - can be found in the reference documentation under {@link - android.view.View#onMeasure View.onMeasure(int, int)} (this reference - documentation does a pretty good job of explaining the whole measurement - operation as well). -
        2. -
        3. - Your component's onMeasure() method should calculate a - measurement width and height which will be required to render the - component. It should try to stay within the specifications passed in, - although it can choose to exceed them (in this case, the parent can - choose what to do, including clipping, scrolling, throwing an exception, - or asking the onMeasure() to try again, perhaps with - different measurement specifications). -
        4. -
        5. - Once the width and height are calculated, the setMeasuredDimension(int - width, int height) method must be called with the calculated - measurements. Failure to do this will result in an exception being - thrown. -
        6. -
        - -

        -Here's a summary of some of the other standard methods that the framework calls on views: -

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        Category Methods Description
        CreationConstructorsThere is a form of the constructor that are called when the view - is created from code and a form that is called when the view is - inflated from a layout file. The second form should parse and apply - any attributes defined in the layout file. -
        {@link android.view.View#onFinishInflate()}Called after a view and all of its children has been inflated - from XML.
        Layout{@link android.view.View#onMeasure}Called to determine the size requirements for this view and all - of its children. -
        {@link android.view.View#onLayout}Called when this view should assign a size and position to all - of its children. -
        {@link android.view.View#onSizeChanged}Called when the size of this view has changed. -
        Drawing{@link android.view.View#onDraw}Called when the view should render its content. -
        Event processing{@link android.view.View#onKeyDown}Called when a new key event occurs. -
        {@link android.view.View#onKeyUp}Called when a key up event occurs. -
        {@link android.view.View#onTrackballEvent}Called when a trackball motion event occurs. -
        {@link android.view.View#onTouchEvent}Called when a touch screen motion event occurs. -
        Focus{@link android.view.View#onFocusChanged}Called when the view gains or loses focus. -
        {@link android.view.View#onWindowFocusChanged}Called when the window containing the view gains or loses focus. -
        Attaching{@link android.view.View#onAttachedToWindow()}Called when the view is attached to a window. -
        {@link android.view.View#onDetachedFromWindow}Called when the view is detached from its window. -
        {@link android.view.View#onWindowVisibilityChanged}Called when the visibility of the window containing the view - has changed. -
        - - - -

        A Custom View Example

        -

        The CustomView sample in the -API Demos provides an example -of a customized View. The custom View is defined in the -LabelView -class.

        -

        The LabelView sample demonstrates a number of different aspects of custom components:

        -
          -
        • Extending the View class for a completely custom component.
        • -
        • Parameterized constructor that takes the view inflation parameters - (parameters defined in the XML). Some of these are passed through to the - View superclass, but more importantly, there are some custom attributes defined - and used for LabelView.
        • -
        • Standard public methods of the type you would expect to see for a label - component, for example setText(), setTextSize(), - setTextColor() and so on.
        • -
        • An overridden onMeasure method to determine and set the - rendering size of the component. (Note that in LabelView, the real work is done - by a private measureWidth() method.)
        • -
        • An overridden onDraw() method to draw the label onto the - provided canvas.
        • -
        -

        You can see some sample usages of the LabelView custom View in -custom_view_1.xml -from the samples. In particular, you can see a mix of both android: -namespace parameters and custom app: namespace parameters. These -app: parameters are the custom ones that the LabelView recognizes -and works with, and are defined in a styleable inner class inside of the -samples R resources definition class.

        - - -

        Compound Controls -

        -

        If you don't want to create a completely customized component, but instead -are looking to put together a reusable component that consists of a group of -existing controls, then creating a Compound Component (or Compound Control) might -fit the bill. In a nutshell, this brings together a number of more atomic -controls (or views) into a logical group of items that can be treated as a -single thing. For example, a Combo Box can be thought of as a -combination of a single line EditText field and an adjacent button with an attached - PopupList. If you press the button and select -something from the list, it populates the EditText field, but the user can -also type something directly into the EditText if they prefer.

        -

        In Android, there are actually two other Views readily available to do -this: {@link android.widget.Spinner Spinner} and -{@link android.widget.AutoCompleteTextView AutoCompleteTextView}, but -regardless, the concept of a Combo Box makes an easy-to-understand -example.

        -

        To create a compound component:

        -
          -
        1. - The usual starting point is a Layout of some kind, so create a class - that extends a Layout. Perhaps in the case of a Combo box we might use - a LinearLayout with horizontal orientation. Remember that other layouts - can be nested inside, so the compound component can be arbitrarily - complex and structured. Note that just like with an Activity, you can - use either the declarative (XML-based) approach to creating the - contained components, or you can nest them programmatically from your - code. -
        2. -
        3. - In the constructor for the new class, take whatever parameters the - superclass expects, and pass them through to the superclass constructor - first. Then you can set up the other views to use within your new - component; this is where you would create the EditText field and the - PopupList. Note that you also might introduce your own attributes and - parameters into the XML that can be pulled out and used by your - constructor. -
        4. -
        5. - You can also create listeners for events that your contained views might - generate, for example, a listener method for the List Item Click Listener - to update the contents of the EditText if a list selection is made. -
        6. -
        7. - You might also create your own properties with accessors and modifiers, - for example, allow the EditText value to be set initially in the - component and query for its contents when needed. -
        8. -
        9. - In the case of extending a Layout, you don't need to override the - onDraw() and onMeasure() methods since the - layout will have default behavior that will likely work just fine. However, - you can still override them if you need to. -
        10. -
        11. - You might override other on... methods, like - onKeyDown(), to perhaps choose certain default values from - the popup list of a combo box when a certain key is pressed. -
        12. -
        -

        - To summarize, the use of a Layout as the basis for a Custom Control has a -number of advantages, including:

        - -
          -
        • - You can specify the layout using the declarative XML files just like - with an activity screen, or you can create views programmatically and - nest them into the layout from your code. -
        • -
        • - The onDraw() and onMeasure() methods (plus - most of the other on... methods) will likely have suitable behavior so - you don't have to override them. -
        • -
        • - In the end, you can very quickly construct arbitrarily complex compound - views and re-use them as if they were a single component. -
        • -
        -

        Examples of Compound Controls

        -

        In the API Demos project - that comes with the SDK, there are two List - examples — Example 4 and Example 6 under Views/Lists demonstrate a - SpeechView which extends LinearLayout to make a component for displaying - Speech quotes. The corresponding classes in the sample code are - List4.java and List6.java.

        - - -

        Modifying an Existing View Type -

        -

        There is an even easier option for creating a custom View which is -useful in certain circumstances. If there is a component that is already very -similar to what you want, you can simply extend that component and just -override the behavior that you want to change. You can do all of the things -you would do with a fully customized component, but by starting with a more -specialized class in the View hierarchy, you can also get a lot of behavior for -free that probably does exactly what you want.

        -

        For example, the SDK includes a NotePad application in the -samples. This demonstrates many aspects of using the Android platform, among -them is extending an EditText View to make a lined notepad. This is not a -perfect example, and the APIs for doing this might change from this early -preview, but it does demonstrate the principles.

        -

        If you haven't done so already, import the -NotePad sample into Eclipse (or -just look at the source using the link provided). In particular look at the definition of -MyEditText in the NoteEditor.java -file.

        -

        Some points to note here

        -
          -
        1. - The Definition -

          The class is defined with the following line:

          - public static class MyEditText extends EditText

          - -
            -
          • - It is defined as an inner class within the NoteEditor - activity, but it is public so that it could be accessed as - NoteEditor.MyEditText from outside of the NoteEditor - class if desired. -
          • -
          • - It is static, meaning it does not generate the so-called - "synthetic methods" that allow it to access data from the parent - class, which in turn means that it really behaves as a separate - class rather than something strongly related to NoteEditor. - This is a cleaner way to create inner classes if they do not need - access to state from the outer class, keeps the generated class - small, and allows it to be used easily from other classes. -
          • -
          • - It extends EditText, which is the View we have chosen to - customize in this case. When we are finished, the new class will be - able to substitute for a normal EditText view.
            -
            -
          • -
          -
        2. -
        3. - Class Initialization -

          As always, the super is called first. Furthermore, - this is not a default constructor, but a parameterized one. The - EditText is created with these parameters when it is inflated from an - XML layout file, thus, our constructor needs to both take them and pass them - to the superclass constructor as well.

          -
        4. -
        5. - Overridden Methods -

          In this example, there is only one method to be overridden: - onDraw() — but there could easily be others needed when you - create your own custom components.

          -

          For the NotePad sample, overriding the onDraw() method allows - us to paint the blue lines on the EditText view canvas (the - canvas is passed into the overridden onDraw() method). The - super.onDraw() method is called before the method ends. The - superclass method should be invoked, but in this case, we do it at the - end after we have painted the lines we want to include.

          -
        6. - Use the Custom Component -

          We now have our custom component, but how can we use it? In the - NotePad example, the custom component is used directly from the - declarative layout, so take a look at note_editor.xml in the - res/layout folder.

          -
          -<view xmlns:android="http://schemas.android.com/apk/res/android" 
          -  class="com.android.notepad.NoteEditor$MyEditText" 
          -  id="@+id/note"
          -  android:layout_width="fill_parent"
          -  android:layout_height="fill_parent"
          -  android:background="@android:drawable/empty"
          -  android:padding="10dip"
          -  android:scrollbars="vertical"
          -  android:fadingEdge="vertical" /> 
          - -
            -
          • - The custom component is created as a generic view in the XML, and - the class is specified using the full package. Note also that the - inner class we defined is referenced using the - NoteEditor$MyEditText notation which is a standard way to - refer to inner classes in the Java programming language. -
          • -
          • - The other attributes and parameters in the definition are the ones - passed into the custom component constructor, and then passed - through to the EditText constructor, so they are the same - parameters that you would use for an EditText view. Note that it is - possible to add your own parameters as well, and we will touch on - this again below. -
          • -
          -
        7. -
        -

        And that's all there is to it. Admittedly this is a simple case, but -that's the point — creating custom components is only as complicated as you -need it to be.

        -

        A more sophisticated component may override even more on... methods and -introduce some of its own helper methods, substantially customizing its properties and -behavior. The only limit is your imagination and what you need the component to -do.

        - diff --git a/docs/html/guide/topics/views/intro.jd b/docs/html/guide/topics/views/intro.jd deleted file mode 100644 index f49f5478bce3..000000000000 --- a/docs/html/guide/topics/views/intro.jd +++ /dev/null @@ -1,49 +0,0 @@ -page.title=Introduction to Views -parent.title=Views and Layout -parent.link=index.html -@jd:body - -

        The basic functional unit of an Android application is the activity — an object of the class {@link android.app.Activity android.app.Activity}. An activity can do many things, but by itself it does not have a presence on the screen. To give your activity a screen presence and design its UI, you work with views and viewgroups -- basic units of user interface expression on the Android platform.

        - -

        Views

        -

        A view is an object of base class {@link android.view.View android.view.View}. It's a data structure whose properties store the layout and content for a specific rectangular area of the screen. A View object handles measuring and layout, drawing, focus change, scrolling, and key/gestures for the screen area it represents.

        -

        The View class serves as a base class for widgets — a set of fully implemented subclasses that draw interactive screen elements. Widgets handle their own measuring and drawing, so you can use them to build your UI more quickly. The list of widgets available includes Text, EditText, InputMethod, MovementMethod, Button, RadioButton, Checkbox, and ScrollView.

        - -

        Viewgroups

        - -

        A viewgroup is an object of class {@link android.view.ViewGroup android.view.Viewgroup}. As its name indicates, a viewgroup is a special type of view object whose function is to contain and manage a subordinate set of views and other viewgroups, Viewgroups let you add structure to your UI and build up complex screen elements that can be addressed as a single entity.

        - -

        The Viewgroup class serves as a base class for layouts — a set of fully implemented subclasses that provide common types of screen layout. The layouts give you a way to build a structure for a set of views.

        - -

        A Tree-Structured UI

        - -

        On the Android platform, you define an Activity's UI using a tree of view and viewgroup nodes, as shown in the diagram below. The tree can be as simple or complex as you need to make it, and you can build it up using Android's set of predefined widgets and layouts or custom view types that you create yourself.

        - -An example of a tree of views and viewgroups - -

        To attach the tree to the screen for rendering, your Activity calls its setContentView() method and passes a reference to the root node object. Once the Android system has the reference to the root node object, it can work directly with the node to invalidate, measure, and draw the tree. When your Activity becomes active and receives focus, the system notifies your activity and requests the root node to measure and draw the tree. The root node then requests that its child nodes draw themselves — in turn, each viewgroup node in the tree is responsible for drawing its direct children.

        - -

        As mentioned previously, each view group has the responsibility of - measuring its available space, laying out its children, and calling Draw() on - each child to let it render itself. The children may request a size and location - in the parent, but the parent object has the final decision on where how big - each child can be.

        - -

        LayoutParams: How a Child Specifies Its Position and Size

        - -

        Every viewgroup class uses a nested class that extends {@link -android.view.ViewGroup.LayoutParams ViewGroup.LayoutParams}. This subclass - contains property types that define a child's size and position, in properties - appropriate for that view group class.

        - -An example of layoutparams - -

        Note that every LayoutParams subclass has its own syntax for setting -values. Each child element must define LayoutParams that are appropriate for its parent, although it may define different LayoutParams for its children.

        - -

        All viewgroups include width and height. Many also include margins and -borders. You can specify width and height exactly, though you probably won't want -to do this often. More often you will tell your view to size itself either to -the dimensions of its content, or to become as big as its containing object -will allow.

        - diff --git a/docs/html/guide/topics/views/ui-xml.jd b/docs/html/guide/topics/views/ui-xml.jd deleted file mode 100644 index bcfa56286ab5..000000000000 --- a/docs/html/guide/topics/views/ui-xml.jd +++ /dev/null @@ -1,138 +0,0 @@ -page.title=Declaring a UI in XML -parent.title=Views and Layout -parent.link=index.html -@jd:body - -

        You can create your application's user interface in two ways: -

          -
        • You can declare UI elements statically, in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
        • -
        • You can instantiate screen elements dynamically, at runtime, through code in your application. Your application can refer to or create View or other class objects and manipulate their properties programmatically.
        • -
        - -

        One advantage of declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls it's behavior. Your UI description is external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations and for a variety of device screen sizes or languages. Additionally, declaring in XML makes it easier to see the elements and structure of your UI, so it's easier to debug problems.

        - -

        The Android framework gives you the flexibility to use either or both of these ways of declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.

        - -

        You build your application's UI in approximately the same way, whether you are declaring it in XML or programmatically. In both cases, your UI will be a tree structure that may include multiple View or Viewgroup subclasses.

        - -

        In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the framework's UI-related classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element.

        - -

        However, note that the XML vocabulary for defining UI is not entirely identical to the framework's classes and methods. In some cases, there are slight naming differences. For -example, the EditText element has a text attribute that corresponds to -EditText.setText.

        - - - -

        Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create HTML files — as a series of nested tags.

        - -

        Each layout file must contain exactly one root element, and the root element must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or controls as child elements of the root element, if needed. In the example below, the tree of XML elements evaluates to the outermost LinearLayout object. - -

        After you've declared your layout in XML, you must save the file, with the .xml extension, in the proper location, so that it will be compiled correctly. The proper location for storing layout files is in your application's res/layout/ directory.

        - -

        When you compile your application, each XML layout file is compiled into an -android.view.View resource. You can then load the layout resource from your application code, by calling setContentView(R.layout.layout_file_name) in your {@link android.app.Activity#onCreate(android.os.Bundle) Activity.onCreate()} -implementation.

        - -

        When you load a layout resource, the Android system initializes run-time objects corresponding to the elements in your layout. It parses the elements of your layout in-order (depth-first), instantiating the Views and adding them to their parent(s).

        - -

        Attributes named layout_something apply to that -object's LayoutParams member. Layout -Resources also describes how to learn the syntax for specifying -LayoutParams properties.

        - -

        Also note that Android draws elements in the order in which they -appear in the XML. Therefore, if elements overlap, the last one in the XML -file will probably be drawn on top of any previously listed elements in that -same space.

        - -

        The following values are supported for dimensions (described in {@link -android.util.TypedValue TypedValue}):

        - -
          -
        • px (pixels)
        • -
        • dip (device independent pixels)
        • -
        • sp (scaled pixels — best for text size)
        • -
        • pt (points)
        • -
        • in (inches)
        • -
        • mm (millimeters)
        • -
        - -

        Example: android:layout_width="25px"

        - -

        For more information about these dimensions, see Dimension Values.

        - -

        The example below shows an XML file and the resulting screen in the UI. Note that the text on the -top of the screen was set by calling {@link -android.app.Activity#setTitle(java.lang.CharSequence) Activity.setTitle}. Note -that the attributes that refer to relative elements (i.e., layout_toLeft) -refer to the ID using the syntax of a relative resource -(@id/id_number).

        - - - - - - -
        -
        <?xml version="1.0" encoding="utf-8"?>
        -<!-- Demonstrates using a relative layout to create a form -->
        -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
        -                android:layout_width="fill_parent" 
        -                android:layout_height="wrap_content"
        -                android:background="@drawable/blue"
        -                android:padding="10px">
        -
        -    <TextView id="@+id/label" 
        -              android:layout_width="fill_parent" 
        -              android:layout_height="wrap_content" 
        -              android:text="Type here:"/>
        -
        -    <EditText id="@+id/entry" 
        -              android:layout_width="fill_parent" 
        -              android:layout_height="wrap_content" 
        -              android:background="@android:drawable/editbox_background"
        -              android:layout_below="@id/label"/>
        -  
        -    <Button id="@+id/ok" 
        -            android:layout_width="wrap_content" 
        -            android:layout_height="wrap_content" 
        -            android:layout_below="@id/entry"
        -            android:layout_alignParentRight="true"
        -            android:layout_marginLeft="10px"
        -            android:text="OK" />
        -
        -    <Button android:layout_width="wrap_content" 
        -            android:layout_height="wrap_content"
        -            android:layout_toLeftOf="@id/ok"
        -            android:layout_alignTop="@id/ok"
        -            android:text="Cancel" />
        -</RelativeLayout>
        Screen shot showing how this layout XML file is rendered.
        - -

        Loading the XML Resource

        - -

        Loading the compiled layout resource is very easy, and done with a single -call in the activity's onCreate() method, as shown here:

        - -
        -protected void onCreate(Bundle savedValues)
        -{
        -   // Be sure to call the super class.
        -   super.onCreate(savedValues);
        -
        -   // Load the compiled layout resource into the window's
        -   // default ViewGroup.
        -   // The source file is res/layout/hello_activity.xml
        -    setContentView(R.layout.hello_activity);
        -  
        -   // Retrieve any important stored values.
        -   restoreValues(savedValues);
        -} 
        diff --git a/docs/html/guide/topics/wireless/bluetooth.jd b/docs/html/guide/topics/wireless/bluetooth.jd deleted file mode 100644 index 0567799565e2..000000000000 --- a/docs/html/guide/topics/wireless/bluetooth.jd +++ /dev/null @@ -1,1086 +0,0 @@ -page.title=Bluetooth -@jd:body - -
        -
        - -

        Quickview

        -
          -
        • Android's bluetooth APIs allow your application to perform wireless data transactions with -other devices
        • -
        - -

        In this document

        -
          -
        1. The Basics
        2. -
        3. Bluetooth Permissions
        4. -
        5. Setting Up Bluetooth
        6. -
        7. Finding Devices -
            -
          1. Querying paired devices
          2. -
          3. Discovering devices
          4. -
        8. -
        9. Connecting Devices -
            -
          1. Connecting as a server
          2. -
          3. Connecting as a client
          4. -
        10. -
        11. Managing a Connection
        12. -
        13. Working with Profiles -
            -
          1. Vendor-specific AT commands -
          2. Health Device Profile -
        14. -
        - -

        Key classes

        -
          -
        1. {@link android.bluetooth.BluetoothAdapter}
        2. -
        3. {@link android.bluetooth.BluetoothDevice}
        4. -
        5. {@link android.bluetooth.BluetoothSocket}
        6. -
        7. {@link android.bluetooth.BluetoothServerSocket}
        8. -
        - -

        Related samples

        -
          -
        1. Bluetooth Chat
        2. -
        3. Bluetooth HDP (Health Device Profile)
        4. -
        - -
        -
        - - -

        The Android platform includes support for the Bluetooth network stack, -which allows a device to wirelessly exchange data with other Bluetooth devices. -The application framework provides access to the Bluetooth functionality through -the Android Bluetooth APIs. These APIs let applications wirelessly -connect to other Bluetooth devices, enabling point-to-point and multipoint -wireless features.

        - -

        Using the Bluetooth APIs, an Android application can perform the -following:

        -
          -
        • Scan for other Bluetooth devices
        • -
        • Query the local Bluetooth adapter for paired Bluetooth devices
        • -
        • Establish RFCOMM channels
        • -
        • Connect to other devices through service discovery
        • -
        • Transfer data to and from other devices
        • -
        • Manage multiple connections
        • -
        - - -

        The Basics

        - -

        This document describes how to use the Android Bluetooth APIs to accomplish -the four major tasks necessary to communicate using Bluetooth: setting up -Bluetooth, finding devices that are either paired or available in the local -area, connecting devices, and transferring data between devices.

        - -

        All of the Bluetooth APIs are available in the {@link android.bluetooth} -package. Here's a summary of the classes and interfaces you will need to create Bluetooth -connections:

        - -
        -
        {@link android.bluetooth.BluetoothAdapter}
        -
        Represents the local Bluetooth adapter (Bluetooth radio). The -{@link android.bluetooth.BluetoothAdapter} is the entry-point for all Bluetooth -interaction. Using this, -you can discover other Bluetooth devices, query a list of bonded (paired) -devices, instantiate a {@link android.bluetooth.BluetoothDevice} using a known -MAC address, and create a {@link android.bluetooth.BluetoothServerSocket} to -listen for communications -from other devices.
        - -
        {@link android.bluetooth.BluetoothDevice}
        -
        Represents a remote Bluetooth device. Use this to request a connection -with a remote device through a {@link android.bluetooth.BluetoothSocket} or -query information about the -device such as its name, address, class, and bonding state.
        - -
        {@link android.bluetooth.BluetoothSocket}
        -
        Represents the interface for a Bluetooth socket (similar to a TCP -{@link java.net.Socket}). This is the connection point that allows -an application to exchange data with another Bluetooth device via InputStream -and OutputStream.
        - -
        {@link android.bluetooth.BluetoothServerSocket}
        -
        Represents an open server socket that listens for incoming requests -(similar to a TCP {@link java.net.ServerSocket}). In order to connect two -Android devices, one device must open a server socket with this class. When a -remote Bluetooth device makes a connection request to the this device, the -{@link android.bluetooth.BluetoothServerSocket} will return a connected {@link -android.bluetooth.BluetoothSocket} when the -connection is accepted.
        - -
        {@link android.bluetooth.BluetoothClass}
        -
        Describes the general characteristics and capabilities of a Bluetooth -device. This is a read-only set of properties that define the device's major and -minor device classes and its services. However, this does not reliably describe -all Bluetooth profiles and services supported by the device, but is useful as a -hint to the device type.
        - -
        {@link android.bluetooth.BluetoothProfile}
        An interface that -represents a Bluetooth profile. A Bluetooth profile is a wireless -interface specification for Bluetooth-based communication between devices. An -example is the Hands-Free profile. For more discussion of profiles, see Working with Profiles
        - -
        {@link android.bluetooth.BluetoothHeadset}
        Provides support for -Bluetooth headsets to be used with mobile phones. This includes both Bluetooth -Headset and Hands-Free (v1.5) profiles.
        - -
        {@link android.bluetooth.BluetoothA2dp}
        Defines how high quality -audio can be streamed from one device to another over a Bluetooth connection. -"A2DP" stands for Advanced Audio Distribution Profile.
        - -
        {@link android.bluetooth.BluetoothHealth}
        -
        Represents a Health Device Profile proxy that controls the Bluetooth service.
        - -
        {@link android.bluetooth.BluetoothHealthCallback}
        - -
        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.
        - -
        {@link android.bluetooth.BluetoothHealthAppConfiguration}
        - -
        Represents an application configuration that the Bluetooth Health third-party -application registers to communicate with a remote Bluetooth health -device.
        - -
        {@link android.bluetooth.BluetoothProfile.ServiceListener}
        - -
        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).
        - -
        - - - - -

        Bluetooth Permissions

        - -

        In order to use Bluetooth features in your application, you need to declare -at least one of two Bluetooth permissions: {@link -android.Manifest.permission#BLUETOOTH} and {@link -android.Manifest.permission#BLUETOOTH_ADMIN}.

        - -

        You must request the {@link android.Manifest.permission#BLUETOOTH} permission -in order to perform any Bluetooth communication, such as requesting a -connection, accepting a connection, and transferring data.

        - -

        You must request the {@link android.Manifest.permission#BLUETOOTH_ADMIN} -permission in order to initiate device discovery or manipulate Bluetooth -settings. Most applications need this permission solely for the -ability to discover local Bluetooth devices. The other abilities granted by this -permission should not be used, unless the application is a "power manager" that -will modify Bluetooth settings upon user request. Note: If you -use {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission, then must -also have the {@link android.Manifest.permission#BLUETOOTH} permission.

        - -

        Declare the Bluetooth permission(s) in your application manifest file. For -example:

        - -
         
        -<manifest ... >
        -  <uses-permission android:name="android.permission.BLUETOOTH" />
        -  ...
        -</manifest>
        -
        - -

        See the <uses-permission> -reference for more information about declaring application permissions.

        - - -

        Setting Up Bluetooth

        - -
        - -Figure 1: The enabling Bluetooth dialog. -
        - -

        Before your application can communicate over Bluetooth, you need to verify -that Bluetooth is supported on the device, and if so, ensure that it is enabled.

        - -

        If Bluetooth is not supported, then you should gracefully disable any -Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the -user enable Bluetooth without leaving your application. This setup is -accomplished in two steps, using the {@link android.bluetooth.BluetoothAdapter}.

        - - -
          -
        1. Get the {@link android.bluetooth.BluetoothAdapter} -

          The {@link android.bluetooth.BluetoothAdapter} is required for any and all Bluetooth -activity. To get the {@link android.bluetooth.BluetoothAdapter}, call the static {@link -android.bluetooth.BluetoothAdapter#getDefaultAdapter()} method. This returns a -{@link android.bluetooth.BluetoothAdapter} that represents the device's own -Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the -entire system, and your application can interact with it using this object. If -{@link android.bluetooth.BluetoothAdapter#getDefaultAdapter()} returns null, -then the device does not support Bluetooth and your story ends here. For example:

          -
           
          -BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
          -if (mBluetoothAdapter == null) {
          -    // Device does not support Bluetooth
          -}
          -
          -
        2. - -
        3. Enable Bluetooth -

          Next, you need to ensure that Bluetooth is enabled. Call {@link -android.bluetooth.BluetoothAdapter#isEnabled()} to check whether Bluetooth is -currently enable. If this method returns false, then Bluetooth is disabled. To -request that Bluetooth be enabled, call {@link -android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} -with the {@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} action Intent. -This will issue a request to enable Bluetooth through the system settings (without -stopping your application). For example:

          -
           
          -if (!mBluetoothAdapter.isEnabled()) {
          -    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
          -    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          -}
          -
          - -

          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).

          - -

          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 -requestCode parameter.

          - -

          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 is {@link -android.app.Activity#RESULT_CANCELED}.

          -
        4. -
        - -

        Optionally, your application can also listen for the -{@link android.bluetooth.BluetoothAdapter#ACTION_STATE_CHANGED} broadcast Intent, which -the system will broadcast whenever the Bluetooth state has changed. This broadcast contains -the extra fields {@link android.bluetooth.BluetoothAdapter#EXTRA_STATE} and {@link -android.bluetooth.BluetoothAdapter#EXTRA_PREVIOUS_STATE}, containing the new and old -Bluetooth states, respectively. Possible values for these extra fields are -{@link android.bluetooth.BluetoothAdapter#STATE_TURNING_ON}, {@link -android.bluetooth.BluetoothAdapter#STATE_ON}, {@link -android.bluetooth.BluetoothAdapter#STATE_TURNING_OFF}, and {@link -android.bluetooth.BluetoothAdapter#STATE_OFF}. Listening for this -broadcast can be useful to detect changes made to the Bluetooth state while your -app is running.

        - -

        Tip: Enabling discoverability will automatically -enable Bluetooth. If you plan to consistently enable device discoverability before -performing Bluetooth activity, you can skip -step 2 above. Read about enabling discoverability, -below.

        - - -

        Finding Devices

        - -

        Using the {@link android.bluetooth.BluetoothAdapter}, you can find remote Bluetooth -devices either through device discovery or by querying the list of paired (bonded) -devices.

        - -

        Device discovery is a scanning procedure that searches the local area for -Bluetooth enabled devices and then requesting some information about each one -(this is sometimes referred to as "discovering," "inquiring" or "scanning"). -However, a Bluetooth device within the local area will respond to a discovery -request only if it is currently enabled to be discoverable. If a device is -discoverable, it will respond to the discovery request by sharing some -information, such as the device name, class, and its unique MAC address. Using -this information, the device performing discovery can then choose to initiate a -connection to the discovered device.

        - -

        Once a connection is made with a remote device for the first time, a pairing -request is automatically presented to the user. When a device is -paired, the basic information about that device (such as the device name, class, -and MAC address) is saved and can be read using the Bluetooth APIs. Using the -known MAC address for a remote device, a connection can be initiated with it at -any time without performing discovery (assuming the device is within range).

        - -

        Remember there is a difference between being paired and being connected. To -be paired means that two devices are aware of each other's existence, have a -shared link-key that can be used for authentication, and are capable of -establishing an encrypted connection with each other. To be connected means that -the devices currently share an RFCOMM channel and are able to transmit data with -each other. The current Android Bluetooth API's require devices to be paired -before an RFCOMM connection can be established. (Pairing is automatically performed -when you initiate an encrypted connection with the Bluetooth APIs.)

        - -

        The following sections describe how to find devices that have been paired, or -discover new devices using device discovery.

        - -

        Note: Android-powered devices are not -discoverable by default. A user can make -the device discoverable for a limited time through the system settings, or an -application can request that the user enable discoverability without leaving the -application. How to enable discoverability -is discussed below.

        - - -

        Querying paired devices

        - -

        Before performing device discovery, its worth querying the set -of paired devices to see if the desired device is already known. To do so, -call {@link android.bluetooth.BluetoothAdapter#getBondedDevices()}. This -will return a Set of {@link android.bluetooth.BluetoothDevice}s representing -paired devices. For example, you can query all paired devices and then -show the name of each device to the user, using an ArrayAdapter:

        -
         
        -Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        -// If there are paired devices
        -if (pairedDevices.size() > 0) {
        -    // Loop through paired devices
        -    for (BluetoothDevice device : pairedDevices) {
        -        // Add the name and address to an array adapter to show in a ListView
        -        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        -    }
        -}
        -
        - -

        All that's needed from the {@link android.bluetooth.BluetoothDevice} object -in order to initiate a connection is the MAC address. In this example, it's saved -as a part of an ArrayAdapter that's shown to the user. The MAC address can later -be extracted in order to initiate the connection. You can learn more about creating -a connection in the section about Connecting Devices.

        - - -

        Discovering devices

        - -

        To start discovering devices, simply call {@link -android.bluetooth.BluetoothAdapter#startDiscovery()}. The -process is asynchronous and the method will immediately return with a boolean -indicating whether discovery has successfully started. The discovery process -usually involves an inquiry scan of about 12 seconds, followed by a page scan of -each found device to retrieve its Bluetooth name.

        - -

        Your application must register a BroadcastReceiver for the -{@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent in -order to receive information about each -device discovered. For each device, the system will broadcast the -{@link android.bluetooth.BluetoothDevice#ACTION_FOUND} Intent. This -Intent carries the extra fields -{@link android.bluetooth.BluetoothDevice#EXTRA_DEVICE} and -{@link android.bluetooth.BluetoothDevice#EXTRA_CLASS}, containing a -{@link android.bluetooth.BluetoothDevice} and a {@link -android.bluetooth.BluetoothClass}, respectively. For example, here's how you can -register to handle the broadcast when devices are discovered:

        -
         
        -// Create a BroadcastReceiver for ACTION_FOUND
        -private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        -    public void onReceive(Context context, Intent intent) {
        -        String action = intent.getAction();
        -        // When discovery finds a device
        -        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        -            // Get the BluetoothDevice object from the Intent
        -            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        -            // Add the name and address to an array adapter to show in a ListView
        -            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        -        }
        -    }
        -};
        -// Register the BroadcastReceiver
        -IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        -registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        -
        - -

        All that's needed from the {@link android.bluetooth.BluetoothDevice} object -in order to initiate a -connection is the MAC address. In this example, it's saved as a part of an -ArrayAdapter that's shown to the user. The MAC address can later be extracted in -order to initiate the connection. You can learn more about creating a connection -in the section about Connecting Devices.

        - -

        Caution: Performing device discovery is -a heavy procedure for the Bluetooth -adapter and will consume a lot of its resources. Once you have found a device to -connect, be certain that you always stop discovery with -{@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} before -attempting a connection. Also, if you -already hold a connection with a device, then performing discovery can -significantly reduce the bandwidth available for the connection, so you should -not perform discovery while connected.

        - -

        Enabling discoverability

        - -

        If you would like to make the local device discoverable to other devices, -call {@link android.app.Activity#startActivityForResult(Intent,int)} with the -{@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE} action -Intent. This will issue a request to enable discoverable mode through the system -settings (without stopping your application). By default, the device will become -discoverable for 120 seconds. You can define a different duration by adding the -{@link android.bluetooth.BluetoothAdapter#EXTRA_DISCOVERABLE_DURATION} Intent -extra. The maximum duration an app can set is 3600 seconds, and a value of 0 -means the device is always discoverable. Any value below 0 or above 3600 is -automatically set to 120 secs). For example, this snippet sets the duration to -300:

        - -
        Intent discoverableIntent = new
        -Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        -discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        -startActivity(discoverableIntent);
        -
        - -
        - -Figure 2: The enabling discoverability dialog. -
        - -

        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 -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 {@link android.app.Activity#RESULT_CANCELED}.

        - -

        Note: If Bluetooth has not been enabled on the device, -then enabling device discoverability will automatically enable Bluetooth.

        - -

        The device will silently remain in discoverable mode for the allotted time. -If you would like to be notified when the discoverable mode has changed, you can -register a BroadcastReceiver for the {@link -android.bluetooth.BluetoothAdapter#ACTION_SCAN_MODE_CHANGED} -Intent. This will contain the extra fields {@link -android.bluetooth.BluetoothAdapter#EXTRA_SCAN_MODE} and -{@link android.bluetooth.BluetoothAdapter#EXTRA_PREVIOUS_SCAN_MODE}, which tell you the -new and old scan mode, respectively. Possible values for each are -{@link android.bluetooth.BluetoothAdapter#SCAN_MODE_CONNECTABLE_DISCOVERABLE}, -{@link android.bluetooth.BluetoothAdapter#SCAN_MODE_CONNECTABLE}, or {@link -android.bluetooth.BluetoothAdapter#SCAN_MODE_NONE}, -which indicate that the device is either in discoverable mode, not in -discoverable mode but still able to receive connections, or not in discoverable -mode and unable to receive connections, respectively.

        - -

        You do not need to enable device discoverability if you will be initiating -the connection to a remote device. Enabling discoverability is only necessary when -you want your application to host a server socket that will accept incoming -connections, because the remote devices must be able to discover the device -before it can initiate the connection.

        - - - -

        Connecting Devices

        - -

        In order to create a connection between your application on two devices, you -must implement both the server-side and client-side mechanisms, because one -device must open a server socket and the other one must initiate the connection -(using the server device's MAC address to initiate a connection). The server and -client are considered connected to each other when they each have a connected -{@link android.bluetooth.BluetoothSocket} on the same RFCOMM channel. At this -point, each device can obtain input and output streams and data transfer can -begin, which is discussed in the section about Managing a Connection. This section describes how -to initiate the connection between two devices.

        - -

        The server device and the client device each obtain the required {@link -android.bluetooth.BluetoothSocket} in different ways. The server will receive it -when an incoming connection is accepted. The client will receive it when it -opens an RFCOMM channel to the server.

        - -
        - -Figure 3: The Bluetooth pairing dialog. -
        - -

        One implementation technique is to automatically prepare each device as a -server, so that each one has a server socket open and listening for connections. -Then either device can initiate a connection with the other and become the -client. Alternatively, one device can explicitly "host" the connection and open -a server socket on demand and the other device can simply initiate the -connection.

        - -

        Note: If the two devices have not been previously paired, -then the Android framework will automatically show a pairing request notification or -dialog to the user during the connection procedure, as shown in Figure 3. So -when attempting to connect devices, -your application does not need to be concerned about whether or not the devices are -paired. Your RFCOMM connection attempt will block until the user has successfully paired, -or will fail if the user rejects pairing, or if pairing fails or times out.

        - - -

        Connecting as a server

        - -

        When you want to connect two devices, one must act as a server by holding an -open {@link android.bluetooth.BluetoothServerSocket}. The purpose of the server -socket is to listen for incoming connection requests and when one is accepted, -provide a connected {@link android.bluetooth.BluetoothSocket}. When the {@link -android.bluetooth.BluetoothSocket} is acquired from the {@link -android.bluetooth.BluetoothServerSocket}, -the {@link android.bluetooth.BluetoothServerSocket} can (and should) be -discarded, unless you want to accept more connections.

        - - - -

        Here's the basic procedure to set up a server socket and accept a -connection:

        - -
          -
        1. Get a {@link android.bluetooth.BluetoothServerSocket} by calling the -{@link -android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, -UUID)}. -

          The string is an identifiable name of your service, which the system will -automatically write to a new Service Discovery Protocol (SDP) database entry on -the device (the name is arbitrary and can simply be your application name). The -UUID is also included in the SDP entry and will be the basis for the connection -agreement with the client device. That is, when the client attempts to connect -with this device, it will carry a UUID that uniquely identifies the service with -which it wants to connect. These UUIDs must match in order for the connection to -be accepted (in the next step).

          -
        2. - -
        3. Start listening for connection requests by calling -{@link android.bluetooth.BluetoothServerSocket#accept()}. -

          This is a blocking call. It will return when either a connection has been -accepted or an exception has occurred. A connection is accepted only when a -remote device has sent a connection request with a UUID matching the one -registered with this listening server socket. When successful, {@link -android.bluetooth.BluetoothServerSocket#accept()} will -return a connected {@link android.bluetooth.BluetoothSocket}.

          -
        4. - -
        5. Unless you want to accept additional connections, call -{@link android.bluetooth.BluetoothServerSocket#close()}. -

          This releases the server socket and all its resources, but does not close the -connected {@link android.bluetooth.BluetoothSocket} that's been returned by {@link -android.bluetooth.BluetoothServerSocket#accept()}. Unlike TCP/IP, RFCOMM only allows one -connected client per channel at a time, so in most cases it makes sense to call {@link -android.bluetooth.BluetoothServerSocket#close()} on the {@link -android.bluetooth.BluetoothServerSocket} immediately after accepting a connected -socket.

          -
        6. -
        - -

        The {@link android.bluetooth.BluetoothServerSocket#accept()} call should not -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 -thread managed by your application. To abort a blocked call such as {@link -android.bluetooth.BluetoothServerSocket#accept()}, call {@link -android.bluetooth.BluetoothServerSocket#close()} on the {@link -android.bluetooth.BluetoothServerSocket} (or {@link -android.bluetooth.BluetoothSocket}) from another thread and the blocked call will -immediately return. Note that all methods on a {@link -android.bluetooth.BluetoothServerSocket} or {@link android.bluetooth.BluetoothSocket} -are thread-safe.

        - -

        Example

        - -

        Here's a simplified thread for the server component that accepts incoming -connections:

        -
         
        -private class AcceptThread extends Thread {
        -    private final BluetoothServerSocket mmServerSocket;
        - 
        -    public AcceptThread() {
        -        // Use a temporary object that is later assigned to mmServerSocket,
        -        // because mmServerSocket is final
        -        BluetoothServerSocket tmp = null;
        -        try {
        -            // MY_UUID is the app's UUID string, also used by the client code
        -            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        -        } catch (IOException e) { }
        -        mmServerSocket = tmp;
        -    }
        - 
        -    public void run() {
        -        BluetoothSocket socket = null;
        -        // Keep listening until exception occurs or a socket is returned
        -        while (true) {
        -            try {
        -                socket = mmServerSocket.accept();
        -            } catch (IOException e) {
        -                break;
        -            }
        -            // If a connection was accepted
        -            if (socket != null) {
        -                // Do work to manage the connection (in a separate thread)
        -                manageConnectedSocket(socket);
        -                mmServerSocket.close();
        -                break;
        -            }
        -        }
        -    }
        - 
        -    /** Will cancel the listening socket, and cause the thread to finish */
        -    public void cancel() {
        -        try {
        -            mmServerSocket.close();
        -        } catch (IOException e) { }
        -    }
        -}
        -
        - -

        In this example, only one incoming connection is desired, so as soon as a -connection is accepted and the {@link android.bluetooth.BluetoothSocket} is -acquired, the application -sends the acquired {@link android.bluetooth.BluetoothSocket} to a separate -thread, closes the -{@link android.bluetooth.BluetoothServerSocket} and breaks the loop.

        - -

        Note that when {@link android.bluetooth.BluetoothServerSocket#accept()} -returns the {@link android.bluetooth.BluetoothSocket}, the socket is already -connected, so you should not call {@link -android.bluetooth.BluetoothSocket#connect()} (as you do from the -client-side).

        - -

        manageConnectedSocket() is a fictional method in the application -that will -initiate the thread for transferring data, which is discussed in the section -about Managing a Connection.

        - -

        You should usually close your {@link android.bluetooth.BluetoothServerSocket} -as soon as you are done listening for incoming connections. In this example, {@link -android.bluetooth.BluetoothServerSocket#close()} is called as soon -as the {@link android.bluetooth.BluetoothSocket} is acquired. You may also want -to provide a public method in your thread that can close the private {@link -android.bluetooth.BluetoothSocket} in the event that you need to stop listening on the -server socket.

        - - -

        Connecting as a client

        - -

        In order to initiate a connection with a remote device (a device holding an -open -server socket), you must first obtain a {@link -android.bluetooth.BluetoothDevice} object that represents the remote device. -(Getting a {@link android.bluetooth.BluetoothDevice} is covered in the above -section about Finding Devices.) You must then use the -{@link android.bluetooth.BluetoothDevice} to acquire a {@link -android.bluetooth.BluetoothSocket} and initiate the connection.

        - -

        Here's the basic procedure:

        - -
          -
        1. Using the {@link android.bluetooth.BluetoothDevice}, get a {@link -android.bluetooth.BluetoothSocket} by calling {@link -android.bluetooth.BluetoothDevice#createRfcommSocketToServiceRecord(UUID)}. -

          This initializes a {@link android.bluetooth.BluetoothSocket} that will -connect to the {@link android.bluetooth.BluetoothDevice}. The UUID passed here -must match the UUID used by the server device when it opened its -{@link android.bluetooth.BluetoothServerSocket} (with {@link -android.bluetooth.BluetoothAdapter#listenUsingRfcommWithServiceRecord(String, -UUID)}). Using the same UUID is simply a matter of hard-coding the UUID string -into your application and then referencing it from both the server and client -code.

          -
        2. - -
        3. Initiate the connection by calling {@link -android.bluetooth.BluetoothSocket#connect()}. -

          Upon this call, the system will perform an SDP lookup on the remote device in -order to match the UUID. If the lookup is successful and the remote device -accepts the connection, it will share the RFCOMM channel to use during the -connection and {@link -android.bluetooth.BluetoothSocket#connect()} will return. This method is a -blocking call. If, for -any reason, the connection fails or the {@link -android.bluetooth.BluetoothSocket#connect()} method times out (after about -12 seconds), then it will throw an exception.

          -

          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 -thread.

          -

          Note: You should always ensure that the device is not performing -device discovery when you call {@link -android.bluetooth.BluetoothSocket#connect()}. If discovery is in progress, then -the -connection attempt will be significantly slowed and is more likely to fail.

          -
        4. -
        - -

        Example

        - -

        Here is a basic example of a thread that initiates a Bluetooth -connection:

        -
         
        -private class ConnectThread extends Thread {
        -    private final BluetoothSocket mmSocket;
        -    private final BluetoothDevice mmDevice;
        - 
        -    public ConnectThread(BluetoothDevice device) {
        -        // Use a temporary object that is later assigned to mmSocket,
        -        // because mmSocket is final
        -        BluetoothSocket tmp = null;
        -        mmDevice = device;
        - 
        -        // Get a BluetoothSocket to connect with the given BluetoothDevice
        -        try {
        -            // MY_UUID is the app's UUID string, also used by the server code
        -            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        -        } catch (IOException e) { }
        -        mmSocket = tmp;
        -    }
        - 
        -    public void run() {
        -        // Cancel discovery because it will slow down the connection
        -        mBluetoothAdapter.cancelDiscovery();
        - 
        -        try {
        -            // Connect the device through the socket. This will block
        -            // until it succeeds or throws an exception
        -            mmSocket.connect();
        -        } catch (IOException connectException) {
        -            // Unable to connect; close the socket and get out
        -            try {
        -                mmSocket.close();
        -            } catch (IOException closeException) { }
        -            return;
        -        }
        - 
        -        // Do work to manage the connection (in a separate thread)
        -        manageConnectedSocket(mmSocket);
        -    }
        - 
        -    /** Will cancel an in-progress connection, and close the socket */
        -    public void cancel() {
        -        try {
        -            mmSocket.close();
        -        } catch (IOException e) { }
        -    }
        -}
        -
        - -

        Notice that {@link android.bluetooth.BluetoothAdapter#cancelDiscovery()} is called -before the connection is made. You should always do this before connecting and it is safe -to call without actually checking whether it is running or not (but if you do want to -check, call {@link android.bluetooth.BluetoothAdapter#isDiscovering()}).

        - -

        manageConnectedSocket() is a fictional method in the application -that will initiate the thread for transferring data, which is discussed in the section -about Managing a Connection.

        - -

        When you're done with your {@link android.bluetooth.BluetoothSocket}, always -call {@link android.bluetooth.BluetoothSocket#close()} to clean up. -Doing so will immediately close the connected socket and clean up all internal -resources.

        - - -

        Managing a Connection

        - -

        When you have successfully connected two (or more) devices, each one will -have a connected {@link android.bluetooth.BluetoothSocket}. This is where the fun -begins because you can share data between devices. Using the {@link -android.bluetooth.BluetoothSocket}, the general procedure to transfer arbitrary data is -simple:

        -
          -
        1. Get the {@link java.io.InputStream} and {@link java.io.OutputStream} that -handle transmissions through the socket, via {@link -android.bluetooth.BluetoothSocket#getInputStream()} and -{@link android.bluetooth.BluetoothSocket#getOutputStream}, respectively.
        2. - -
        3. Read and write data to the streams with {@link -java.io.InputStream#read(byte[])} and {@link java.io.OutputStream#write(byte[])}.
        4. -
        - -

        That's it.

        - -

        There are, of course, implementation details to consider. First and foremost, -you should use a dedicated thread for all stream reading and writing. This is -important because both {@link java.io.InputStream#read(byte[])} and {@link -java.io.OutputStream#write(byte[])} methods are blocking calls. {@link -java.io.InputStream#read(byte[])} will block until there is something to read -from the stream. {@link java.io.OutputStream#write(byte[])} does not usually -block, but can block for flow control if the remote device is not calling {@link -java.io.InputStream#read(byte[])} quickly enough and the intermediate buffers are full. -So, your main loop in the thread should be dedicated to reading from the {@link -java.io.InputStream}. A separate public method in the thread can be used to initiate -writes to the {@link java.io.OutputStream}.

        - -

        Example

        - -

        Here's an example of how this might look:

        -
         
        -private class ConnectedThread extends Thread {
        -    private final BluetoothSocket mmSocket;
        -    private final InputStream mmInStream;
        -    private final OutputStream mmOutStream;
        - 
        -    public ConnectedThread(BluetoothSocket socket) {
        -        mmSocket = socket;
        -        InputStream tmpIn = null;
        -        OutputStream tmpOut = null;
        - 
        -        // Get the input and output streams, using temp objects because
        -        // member streams are final
        -        try {
        -            tmpIn = socket.getInputStream();
        -            tmpOut = socket.getOutputStream();
        -        } catch (IOException e) { }
        - 
        -        mmInStream = tmpIn;
        -        mmOutStream = tmpOut;
        -    }
        - 
        -    public void run() {
        -        byte[] buffer = new byte[1024];  // buffer store for the stream
        -        int bytes; // bytes returned from read()
        - 
        -        // Keep listening to the InputStream until an exception occurs
        -        while (true) {
        -            try {
        -                // Read from the InputStream
        -                bytes = mmInStream.read(buffer);
        -                // Send the obtained bytes to the UI activity
        -                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
        -                        .sendToTarget();
        -            } catch (IOException e) {
        -                break;
        -            }
        -        }
        -    }
        - 
        -    /* 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 */
        -    public void cancel() {
        -        try {
        -            mmSocket.close();
        -        } catch (IOException e) { }
        -    }
        -}
        -
        - -

        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 -Handler from the parent class. Then it goes back and waits for more bytes from -the stream.

        - -

        Sending outgoing data is as simple as calling the thread's -write() 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.

        - -

        The thread's cancel() method is important so that the connection -can be -terminated at any time by closing the {@link android.bluetooth.BluetoothSocket}. -This should always be called when you're done using the Bluetooth -connection.

        - -
        -

        For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

        -
        - -

        Working with Profiles

        - -

        Starting in Android 3.0, the Bluetooth API includes support for working with -Bluetooth profiles. A Bluetooth profile is a wireless interface -specification for Bluetooth-based communication between devices. An example -is the Hands-Free profile. For a mobile phone to connect to a wireless headset, -both devices must support the Hands-Free profile.

        - -

        You can implement the interface {@link android.bluetooth.BluetoothProfile} to write -your own classes to support a particular Bluetooth profile. The Android -Bluetooth API provides implementations for the following Bluetooth -profiles:

        -
          - -
        • Headset. The Headset profile provides support for -Bluetooth headsets to be used with mobile phones. Android provides the {@link -android.bluetooth.BluetoothHeadset} class, which is a proxy for controlling the -Bluetooth Headset Service via interprocess communication (IPC). 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 Vendor-specific AT commands
        • - -
        • A2DP. The Advanced Audio Distribution Profile (A2DP) -profile defines how high quality audio can be streamed from one device to -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.
        • - -
        • Health Device. 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 Bluetooth Assigned Numbers at www.bluetooth.org. 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 Health Device Profile.
        • - -
        - -

        Here are the basic steps for working with a profile:

        -
          - -
        1. Get the default adapter, as described in - Setting Up - Bluetooth.
        2. - -
        3. Use {@link -android.bluetooth.BluetoothAdapter#getProfileProxy(android.content.Context, -android.bluetooth.BluetoothProfile.ServiceListener, int) getProfileProxy()} to -establish a connection to the profile proxy object associated with the profile. -In the example below, the profile proxy object is an instance of {@link -android.bluetooth.BluetoothHeadset}.
        4. - -
        5. Set up a {@link android.bluetooth.BluetoothProfile.ServiceListener}. This -listener notifies {@link android.bluetooth.BluetoothProfile} IPC clients when -they have been connected to or disconnected from the service.
        6. - -
        7. In {@link -android.bluetooth.BluetoothProfile.ServiceListener#onServiceConnected(int, -android.bluetooth.BluetoothProfile) onServiceConnected()}, get a handle -to the profile proxy object.
        8. - -
        9. Once you have the profile proxy object, you can use it to monitor the -state of the connection and perform other operations that are relevant to that -profile.
        10. -
        - -

        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:

        - -
        BluetoothHeadset mBluetoothHeadset;
        - 
        -// Get the default adapter
        -BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        - 
        -// Establish connection to the proxy.
        -mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
        - 
        -private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
        -    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        -        if (profile == BluetoothProfile.HEADSET) {
        -            mBluetoothHeadset = (BluetoothHeadset) proxy;
        -        }
        -    }
        -    public void onServiceDisconnected(int profile) {
        -        if (profile == BluetoothProfile.HEADSET) {
        -            mBluetoothHeadset = null;
        -        }
        -    }
        -};
        - 
        -// ... call functions on mBluetoothHeadset
        - 
        -// Close proxy connection after use.
        -mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);
        -
        - - - -

        Vendor-specific AT commands

        - -

        Starting in Android 3.0, applications can register to receive system -broadcasts of pre-defined vendor-specific AT commands sent by headsets (such as -a Plantronics +XEVENT command). For example, an application could receive -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.

        - -

        Health Device Profile

        - -

        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 The Basics.

        - -

        In using the Bluetooth Health API, it's helpful to understand these key HDP concepts:

        - - - - - - - - - - - - - - - - - - - - - - - - -
        ConceptDescription
        SourceA role defined in HDP. A source 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.
        SinkA role defined in HDP. In HDP, a sink 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.
        RegistrationRefers to registering a sink for a particular health device.
        ConnectionRefers to opening a channel between a health device and a smart device -such as an Android phone or tablet.
        - -

        Creating an HDP Application

        - -

        Here are the basic steps involved in creating an Android HDP application:

        -
          - -
        1. Get a reference to the {@link android.bluetooth.BluetoothHealth} proxy -object.

          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.

        2. - -
        3. Create a {@link android.bluetooth.BluetoothHealthCallback} and register an -application configuration -({@link android.bluetooth.BluetoothHealthAppConfiguration}) -that acts as a health -sink.
        4. - -
        5. Establish a connection to a health device. Some devices will initiate the -connection. It is unnecessary to carry out this step for those devices.
        6. - -
        7. When connected successfully to a health device, read/write to the health -device using the file descriptor.

          The received data needs to be interpreted -using a health manager which implements the IEEE 11073-xxxxx -specifications.

        8. - -
        9. When done, close the health channel and unregister the application. The -channel also closes when there is extended inactivity.
        10. -
        - -

        For a complete code sample that illustrates these steps, see Bluetooth HDP (Health -Device Profile).

        diff --git a/docs/html/guide/topics/wireless/index.jd b/docs/html/guide/topics/wireless/index.jd deleted file mode 100644 index 23d2f0fc4f78..000000000000 --- a/docs/html/guide/topics/wireless/index.jd +++ /dev/null @@ -1,23 +0,0 @@ -page.title=Wireless Controls -@jd:body - -Go away. - - - - diff --git a/docs/html/guide/topics/wireless/wifi.jd b/docs/html/guide/topics/wireless/wifi.jd deleted file mode 100644 index 761e463f0dea..000000000000 --- a/docs/html/guide/topics/wireless/wifi.jd +++ /dev/null @@ -1,18 +0,0 @@ -page.title=Wi-Fi -parent.title=Wireless Controls -parent.link=index.html -@jd:body - -
        -
        - -

        In this document

        -
          - -
        - -
        -
        - - -Go away. \ No newline at end of file diff --git a/docs/html/guide/topics/wireless/wifip2p.jd b/docs/html/guide/topics/wireless/wifip2p.jd deleted file mode 100644 index 82c9abdb1066..000000000000 --- a/docs/html/guide/topics/wireless/wifip2p.jd +++ /dev/null @@ -1,611 +0,0 @@ -page.title=Wi-Fi Direct - -@jd:body - - - -

        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.

        - -

        The Wi-Fi Direct APIs consist of the following main parts:

        - -
          -
        • Methods that allow you to discover, request, and connect to peers are defined - in the {@link android.net.wifi.p2p.WifiP2pManager} class.
        • - -
        • 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.
        • - -
        • Intents that notify you of specific events detected by the Wi-Fi Direct framework, - such as a dropped connection or a newly discovered peer.
        • -
        - -

        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.

        - -

        API Overview

        - -

        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:

        - -

        Table 1.Wi-Fi Direct Methods

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        MethodDescription
        {@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}Registers the application with the Wi-Fi framework. This must be called before calling any other Wi-Fi Direct method.
        {@link android.net.wifi.p2p.WifiP2pManager#connect connect()}Starts a peer-to-peer connection with a device with the specified configuration.
        {@link android.net.wifi.p2p.WifiP2pManager#cancelConnect cancelConnect()}Cancels any ongoing peer-to-peer group negotiation.
        {@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}Requests a device's connection information.
        {@link android.net.wifi.p2p.WifiP2pManager#createGroup createGroup()}Creates a peer-to-peer group with the current device as the group owner.
        {@link android.net.wifi.p2p.WifiP2pManager#removeGroup removeGroup()}Removes the current peer-to-peer group.
        {@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}Requests peer-to-peer group information.
        {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}Initiates peer discovery
        {@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}Requests the current list of discovered peers.
        - - -

        {@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:

        - -

        Table 2. Wi-Fi Direct Listeners

        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        Listener interfaceAssociated actions
        {@link android.net.wifi.p2p.WifiP2pManager.ActionListener}{@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()}
        {@link android.net.wifi.p2p.WifiP2pManager.ChannelListener}{@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}
        {@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener}{@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}
        {@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener}{@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}
        {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener}{@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}
        - -

        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 creating a broadcast - receiver that handles these intents:

        - -

        Table 3. Wi-Fi Direct Intents

        - - - - - - - - - - - - - - - - - - - - - - -
        IntentDescription
        {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}Broadcast when the state of the device's Wi-Fi connection changes.
        {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}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.
        {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}Broadcast when Wi-Fi Direct is enabled or disabled on the device.
        {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}Broadcast when a device's details have changed, such as the device's name.
        - - - -

        Creating a Broadcast Receiver for Wi-Fi Direct Intents

        - -

        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:

        - -
          -
        1. 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.
        2. - -
        3. In the broadcast receiver, check for the intents that you are interested in - {@link android.content.BroadcastReceiver#onReceive onReceive()}. - 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.
        4. -
        - -

        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:

        - -
        -/**
        - * 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
        -        }
        -    }
        -}
        -
        - -

        Creating a Wi-Fi Direct Application

        - -

        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.

        - -

        Initial setup

        -

        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.

        -
          -
        1. -

          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:

          -
          -<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" />
          -
          -
        2. - -
        3. 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: -
          -@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
          -        }
          -    }
          -    ...
          -}
          -
          -
        4. - -
        5. 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: -
          -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);
          -    ...
          -}
          -
          -
        6. - -
        7. Create an intent filter and add the same intents that your - broadcast receiver checks for: -
          -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);
          -    ...
          -}
          -
          -
        8. - -
        9. 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: -
          -/* 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);
          -}
          -
          - -

          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.

          -
        10. - -

          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.

          -
        - -

        Discovering peers

        - -

        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:

        -
        -manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
        -    @Override
        -    public void onSuccess() {
        -        ...
        -    }
        -
        -    @Override
        -    public void onFailure(int reasonCode) {
        -        ...
        -    }
        -});
        -
        -
        - -

        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:

        -
        -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);
        -    }
        -}
        -
        - -

        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.

        - -

        Connecting to peers

        - -

        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:

        -
        -//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
        -    }
        -});
        -
        -
        - - -

        Transferring data

        -

        Once a connection is established, you can transfer data between the devices with - sockets. The basic steps of transferring data are as follows:

        - -
          -
        1. 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.
        2. - -
        3. 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.
        4. - -
        5. 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.
        6. - -
        7. 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.
        8. -
        - -

        The following example, modified from the Wi-Fi Direct Demo 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 Wi-Fi Direct Demo sample.

        -
        -public static class FileServerAsyncTask extends AsyncTask {
        -
        -    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);
        -        }
        -    }
        -}
        -
        - -

        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.

        - -
        -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
        -            }
        -        }
        -    }
        -}
        -
        diff --git a/docs/html/guide/tutorials/hello-world.html b/docs/html/guide/tutorials/hello-world.html deleted file mode 100644 index 55187bd7a1a8..000000000000 --- a/docs/html/guide/tutorials/hello-world.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

        You should have been redirected. Please click here.

        - - \ No newline at end of file diff --git a/docs/html/guide/tutorials/images/hello_world_0.png b/docs/html/guide/tutorials/images/hello_world_0.png deleted file mode 100644 index 330a07c74760..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_0.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_1.png b/docs/html/guide/tutorials/images/hello_world_1.png deleted file mode 100644 index 1e5f7b0cdfe3..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_1.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_2.png b/docs/html/guide/tutorials/images/hello_world_2.png deleted file mode 100644 index 3e9c58b2a45d..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_2.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_3.png b/docs/html/guide/tutorials/images/hello_world_3.png deleted file mode 100644 index 22901a97ffde..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_3.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_4.png b/docs/html/guide/tutorials/images/hello_world_4.png deleted file mode 100644 index 5c41e80ad941..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_4.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_5.png b/docs/html/guide/tutorials/images/hello_world_5.png deleted file mode 100644 index 96b830a963a0..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_5.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_8.png b/docs/html/guide/tutorials/images/hello_world_8.png deleted file mode 100644 index 07db36019fed..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_8.png and /dev/null differ diff --git a/docs/html/guide/tutorials/images/hello_world_9.png b/docs/html/guide/tutorials/images/hello_world_9.png deleted file mode 100644 index a66526ad6ca2..000000000000 Binary files a/docs/html/guide/tutorials/images/hello_world_9.png and /dev/null differ diff --git a/docs/html/guide/tutorials/index.html b/docs/html/guide/tutorials/index.html deleted file mode 100644 index e412dec94b3b..000000000000 --- a/docs/html/guide/tutorials/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

        You should have been redirected. Please click here.

        - - \ No newline at end of file diff --git a/docs/html/guide/tutorials/localization/index.html b/docs/html/guide/tutorials/localization/index.html deleted file mode 100644 index 2ea666182f07..000000000000 --- a/docs/html/guide/tutorials/localization/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

        You should have been redirected. Please click here.

        - - \ No newline at end of file diff --git a/docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip b/docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip deleted file mode 100644 index 24fefc1a31fb..000000000000 Binary files a/docs/html/guide/tutorials/notepad/codelab/NotepadCodeLab.zip and /dev/null differ diff --git a/docs/html/guide/tutorials/notepad/index.html b/docs/html/guide/tutorials/notepad/index.html deleted file mode 100644 index 01e4d098a48b..000000000000 --- a/docs/html/guide/tutorials/notepad/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

        You should have been redirected. Please click here.

        - - \ No newline at end of file diff --git a/docs/html/guide/tutorials/notepad/notepad-ex1.jd b/docs/html/guide/tutorials/notepad/notepad-ex1.jd deleted file mode 100644 index cf7765e1693a..000000000000 --- a/docs/html/guide/tutorials/notepad/notepad-ex1.jd +++ /dev/null @@ -1,582 +0,0 @@ -page.title=Notepad Exercise 1 -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -

        In this exercise, you will construct a simple notes list that lets the -user add new notes but not edit them. The exercise demonstrates:

        -
          -
        • The basics of ListActivities and creating and handling menu -options.
        • -
        • How to use a SQLite database to store the notes.
        • -
        • How to bind data from a database cursor into a ListView using a -SimpleCursorAdapter.
        • -
        • The basics of screen layouts, including how to lay out a list view, how -you can add items to the activity menu, and how the activity handles those menu -selections.
        • -
        - - - - - -

        Step 1

        - -

        Open up the Notepadv1 project in Eclipse.

        - -

        Notepadv1 is a project that is provided as a starting point. It - takes care of some of the boilerplate work that you have already seen if you - followed the Hello, - World tutorial.

        - -
          -
        1. - Start a new Android Project by clicking File > - New > Android Project.
        2. -
        3. - In the New Android Project dialog, select Create project from existing source.
        4. -
        5. - Click Browse and navigate to where you copied the NotepadCodeLab - (downloaded during setup) - and select Notepadv1.
        6. -
        7. - The Project Name and other properties should be automatically filled for you. - You must select the Build Target—we recommend selecting a target with the - lowest platform version available. Also add an integer to the Min SDK Version field - that matches the API Level of the selected Build Target.
        8. -
        9. - Click Finish. The Notepadv1 project should open and be - visible in your Eclipse package explorer.
        10. -
        - -

        If you see an error about AndroidManifest.xml, or some - problems related to an Android zip file, right click on the project and - select Android Tools > Fix Project Properties. - (The project is looking in the wrong location for the library file, - this will fix it for you.)

        - -

        Step 2

        - - - -

        Take a look at the NotesDbAdapter class — this class is provided to - encapsulate data access to a SQLite database that will hold our notes data - and allow us to update it.

        -

        At the top of the class are some constant definitions that will be used in the application - to look up data from the proper field names in the database. There is also a database creation - string defined, which is used to create a new database schema if one doesn't exist already.

        -

        Our database will have the name data, and have a single table called - notes, which in turn has three fields: _id, title and - body. The _id is named with an underscore convention used in a number of - places inside the Android SDK and helps keep a track of state. The _id - usually has to be specified when querying or updating the database (in the column projections - and so on). The other two fields are simple text fields that will store data. -

        -

        The constructor for NotesDbAdapter takes a Context, which allows it to communicate with aspects - of the Android operating system. This is quite common for classes that need to touch the - Android system in some way. The Activity class implements the Context class, so usually you will just pass - this from your Activity, when needing a Context.

        -

        The open() method calls up an instance of DatabaseHelper, which is our local - implementation of the SQLiteOpenHelper class. It calls getWritableDatabase(), - which handles creating/opening a database for us.

        -

        close() just closes the database, releasing resources related to the - connection.

        -

        createNote() takes strings for the title and body of a new note, - then creates that note in the database. Assuming the new note is created successfully, the - method also returns the row _id value for the newly created note.

        -

        deleteNote() takes a rowId for a particular note, and deletes that note from - the database.

        - -

        fetchAllNotes() issues a query to return a {@link android.database.Cursor} over all notes in the - database. The query() call is worth examination and understanding. The first field is the - name of the database table to query (in this case DATABASE_TABLE is "notes"). - The next is the list of columns we want returned, in this case we want the _id, - title and body columns so these are specified in the String array. - The remaining fields are, in order: selection, - selectionArgs, groupBy, having and orderBy. - Having these all null means we want all data, need no grouping, and will take the default - order. See {@link android.database.sqlite.SQLiteDatabase SQLiteDatabase} for more details.

        -

        Note: A Cursor is returned rather than a collection of rows. This allows - Android to use resources efficiently -- instead of putting lots of data straight into memory - the cursor will retrieve and release data as it is needed, which is much more efficient for - tables with lots of rows.

        - -

        fetchNote() is similar to fetchAllNotes() but just gets one note - with the rowId we specify. It uses a slightly different version of the - {@link android.database.sqlite.SQLiteDatabase} query() method. - The first parameter (set true) indicates that we are interested - in one distinct result. The selection parameter (the fourth parameter) has been specified to search - only for the row "where _id =" the rowId we passed in. So we are returned a Cursor on - the one row.

        -

        And finally, updateNote() takes a rowId, title and body, and uses a - {@link android.content.ContentValues ContentValues} instance to update the note of the given - rowId.

        - -

        Step 3

        - - - -

        Open the notepad_list.xml file in res/layout -and - take a look at it. (You may have to - hit the xml tab, at the bottom, in order to view the XML markup.)

        - -

        This is a mostly-empty layout definition file. Here are some - things you should know about a layout file:

        - - -
          -
        • - All Android layout files must start with the XML header line: - <?xml version="1.0" encoding="utf-8"?>.
        • -
        • - The next definition will often (but not always) be a layout - definition of some kind, in this case a LinearLayout.
        • -
        • - The XML namespace of Android should always be defined in - the top level component or layout in the XML so that android: tags can - be used through the rest of the file: -

          xmlns:android="http://schemas.android.com/apk/res/android"

          -
        • -
        - -

        Step 4

        -

        We need to create the layout to hold our list. Add code inside - of the LinearLayout element so the whole file looks like this:

        -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="wrap_content"
        -    android:layout_height="wrap_content">
        -
        -  <ListView android:id="@android:id/list"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"/>
        -  <TextView android:id="@android:id/empty"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text="@string/no_notes"/>
        -
        -</LinearLayout>
        -
        -
          -
        • - The @ symbol in the id strings of the ListView and - TextView tags means - that the XML parser should parse and expand the rest of - the id string and use an ID resource.
        • -
        • - The ListView and TextView can be - thought as two alternative views, only one of which will be displayed at once. - ListView will be used when there are notes to be shown, while the TextView - (which has a default value of "No Notes Yet!" defined as a string - resource in res/values/strings.xml) will be displayed if there - aren't any notes to display.
        • -
        • The list and empty IDs are - provided for us by the Android platform, so, we must - prefix the id with android: (e.g., @android:id/list).
        • -
        • The View with the empty id is used - automatically when the {@link android.widget.ListAdapter} has no data for the ListView. The - ListAdapter knows to look for this name by default. Alternatively, you could change the - default empty view by using {@link android.widget.AdapterView#setEmptyView(View)} - on the ListView. -

          - More broadly, the android.R class is a set of predefined - resources provided for you by the platform, while your project's - R class is the set of resources your project has defined. - Resources found in the android.R resource class can be - used in the XML files by using the android: name space prefix - (as we see here).

          -
        • -
        - -

        Step 5

        - - - -

        To make the list of notes in the ListView, we also need to define a View for each row:

        -
          -
        1. - Create a new file under res/layout called - notes_row.xml.
        2. -
        3. - Add the following contents (note: again the XML header is used, and the - first node defines the Android XML namespace)
          -
          -<?xml version="1.0" encoding="utf-8"?>
          -<TextView android:id="@+id/text1"
          -    xmlns:android="http://schemas.android.com/apk/res/android"
          -    android:layout_width="wrap_content"
          -    android:layout_height="wrap_content"/>
          -

          - This is the View that will be used for each notes title row — it has only - one text field in it.

          -

          In this case we create a new id called text1. The - + after the @ in the id string indicates that the id should - be automatically created as a resource if it does not already exist, so we are defining - text1 on the fly and then using it.

          -
        4. -
        5. Save the file.
        6. -
        -

        Open the R.java class in the - project and look at it, you should see new definitions for - notes_row and text1 (our new definitions) - meaning we can now gain access to these from the our code.

        - -

        Step 6

        -

        Next, open the Notepadv1 class in the source. In the following steps, we are going to - alter this class to become a list adapter and display our notes, and also - allow us to add new notes.

        - -

        Notepadv1 will inherit from a subclass - of Activity called a ListActivity, - which has extra functionality to accommodate the kinds of - things you might want to do with a list, for - example: displaying an arbitrary number of list items in rows on the screen, - moving through the list items, and allowing them to be selected.

        - -

        Take a look through the existing code in Notepadv1 class. - There is a currently an unused private field called mNoteNumber that - we will use to create numbered note titles.

        -

        There are also three override methods defined: - onCreate, onCreateOptionsMenu and - onOptionsItemSelected; we need to fill these - out:

        -
          -
        • onCreate() is called when the activity is - started — it is a little like the "main" method for an Activity. We use - this to set up resources and state for the activity when it is - running.
        • -
        • onCreateOptionsMenu() is used to populate the - menu for the Activity. This is shown when the user hits the menu button, -and - has a list of options they can select (like "Create - Note").
        • -
        • onOptionsItemSelected() is the other half of the - menu equation, it is used to handle events generated from the menu (e.g., - when the user selects the "Create Note" item). -
        • -
        - -

        Step 7

        -

        Change the inheritance of Notepadv1 from -Activity - to ListActivity:

        -
        public class Notepadv1 extends ListActivity
        -

        Note: you will have to import ListActivity into the -Notepadv1 - class using Eclipse, ctrl-shift-O on Windows or Linux, or - cmd-shift-O on the Mac (organize imports) will do this for you - after you've written the above change.

        - -

        Step 8

        -

        Fill out the body of the onCreate() method.

        -

        Here we will set the title for the Activity (shown at the top of the - screen), use the notepad_list layout we created in XML, - set up the NotesDbAdapter instance that will - access notes data, and populate the list with the available note - titles:

        -
          -
        1. - In the onCreate method, call super.onCreate() with the - savedInstanceState parameter that's passed in.
        2. -
        3. - Call setContentView() and pass R.layout.notepad_list.
        4. -
        5. - At the top of the class, create a new private class field called mDbHelper of class - NotesDbAdapter. -
        6. -
        7. - Back in the onCreate method, construct a new -NotesDbAdapter - instance and assign it to the mDbHelper field (pass - this into the constructor for DBHelper) -
        8. -
        9. - Call the open() method on mDbHelper to open (or create) the - database. -
        10. -
        11. - Finally, call a new method fillData(), which will get the data and - populate the ListView using the helper — we haven't defined this method yet.
        12. -
        -

        - onCreate() should now look like this:

        -
        -    @Override
        -    public void onCreate(Bundle savedInstanceState) {
        -        super.onCreate(savedInstanceState);
        -        setContentView(R.layout.notepad_list);
        -        mDbHelper = new NotesDbAdapter(this);
        -        mDbHelper.open();
        -        fillData();
        -    }
        -

        And be sure you have the mDbHelper field definition (right - under the mNoteNumber definition):

        -
            private NotesDbAdapter mDbHelper;
        - -

        Step 9

        - - - -

        Fill out the body of the onCreateOptionsMenu() method.

        - -

        We will now create the "Add Item" button that can be accessed by pressing the menu -button on the device. We'll specify that it occupy the first position in the menu.

        - -
          -
        1. - In strings.xml resource (under res/values), add - a new string named "menu_insert" with its value set to Add Item: -
          <string name="menu_insert">Add Item</string>
          -

          Then save the file and return to Notepadv1.

          -
        2. -
        3. Create a menu position constant at the top of the class: -
          public static final int INSERT_ID = Menu.FIRST;
          -
        4. -
        5. In the onCreateOptionsMenu() method, change the - super call so we capture the boolean return as result. We'll return this value at the end.
        6. -
        7. Then add the menu item with menu.add().
        8. -
        -

        The whole method should now look like this: -

        -    @Override
        -    public boolean onCreateOptionsMenu(Menu menu) {
        -        boolean result = super.onCreateOptionsMenu(menu);
        -        menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        -        return result;
        -    }
        -

        The arguments passed to add() indicate: a group identifier for this menu (none, - in this case), a unique ID (defined above), the order of the item (zero indicates no preference), - and the resource of the string to use for the item.

        - -

        Step 10

        -

        Fill out the body of the onOptionsItemSelected() method:

        -

        This is going - to handle our new "Add Note" menu item. When this is selected, the - onOptionsItemSelected() method will be called with the - item.getId() set to INSERT_ID (the constant we - used to identify the menu item). We can detect this, and take the - appropriate actions:

        -
          -
        1. - The super.onOptionsItemSelected(item) method call goes at the - end of this method — we want to catch our events first!
        2. -
        3. - Write a switch statement on item.getItemId(). -

          In the case of INSERT_ID, call a new method, createNote(), - and return true, because we have handled this event and do not want to - propagate it through the system.

          -
        4. -
        5. Return the result of the superclass' onOptionsItemSelected() - method at the end.
        6. -
        -

        - The whole onOptionsItemSelect() method should now look like - this:

        -
        -    @Override
        -    public boolean onOptionsItemSelected(MenuItem item) {
        -        switch (item.getItemId()) {
        -        case INSERT_ID:
        -            createNote();
        -            return true;
        -        }
        -       
        -        return super.onOptionsItemSelected(item);
        -    }
        - -

        Step 11

        -

        Add a new createNote() method:

        -

        In this first version of - our application, createNote() is not going to be very useful. -We will simply - create a new note with a title assigned to it based on a counter ("Note 1", - "Note 2"...) and with an empty body. At present we have no way of editing - the contents of a note, so for now we will have to be content making one - with some default values:

        -
          -
        1. Construct the name using "Note" and the counter we defined in the class: - String noteName = "Note " + mNoteNumber++
        2. -
        3. - Call mDbHelper.createNote() using noteName as the - title and "" for the body -
        4. -
        5. - Call fillData() to populate the list of notes (inefficient but - simple) — we'll create this method next.
        6. -
        -

        - The whole createNote() method should look like this:

        -
        -    private void createNote() {
        -        String noteName = "Note " + mNoteNumber++;
        -        mDbHelper.createNote(noteName, "");
        -        fillData();
        -    }
        - - -

        Step 12

        - - -

        Define the fillData() method:

        -

        This - method uses SimpleCursorAdapter, which takes a database Cursor - and binds it to fields provided in the layout. These fields define the row elements of our list - (in this case we use the text1 field in our - notes_row.xml layout), so this allows us to easily populate the list with - entries from our database.

        -

        To do this we have to provide a mapping from the title field in the returned Cursor, to - our text1 TextView, which is done by defining two arrays: the first a string array - with the list of columns to map from (just "title" in this case, from the constant - NotesDbAdapter.KEY_TITLE) and, the second, an int array - containing references to the views that we'll bind the data into - (the R.id.text1 TextView).

        -

        This is a bigger chunk of code, so let's first take a look at it:

        - -
        -    private void fillData() {
        -        // Get all of the notes from the database and create the item list
        -        Cursor c = mDbHelper.fetchAllNotes();
        -        startManagingCursor(c);
        -
        -        String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
        -        int[] to = new int[] { R.id.text1 };
        -        
        -        // Now create an array adapter and set it to display using our row
        -        SimpleCursorAdapter notes =
        -            new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
        -        setListAdapter(notes);
        -    }
        - -

        Here's what we've done:

        -
          -
        1. - After obtaining the Cursor from mDbHelper.fetchAllNotes(), we - use an Activity method called - startManagingCursor() that allows Android to take care of the - Cursor lifecycle instead of us needing to worry about it. (We will cover the implications - of the lifecycle in exercise 3, but for now just know that this allows Android to do some - of our resource management work for us.)
        2. -
        3. - Then we create a string array in which we declare the column(s) we want - (just the title, in this case), and an int array that defines the View(s) - to which we'd like to bind the columns (these should be in order, respective to - the string array, but here we only have one for each).
        4. -
        5. - Next is the SimpleCursorAdapter instantiation. - Like many classes in Android, the SimpleCursorAdapter needs a Context in order to do its - work, so we pass in this for the context (since subclasses of Activity - implement Context). We pass the notes_row View we created as the receptacle - for the data, the Cursor we just created, and then our arrays.
        6. -
        -

        - In the future, remember that the mapping between the from columns and to resources - is done using the respective ordering of the two arrays. If we had more columns we wanted - to bind, and more Views to bind them in to, we would specify them in order, for example we - might use { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY } and - { R.id.text1, R.id.text2 } to bind two fields into the row (and we would also need - to define text2 in the notes_row.xml, for the body text). This is how you can bind multiple fields - into a single row (and get a custom row layout as well).

        -

        - If you get compiler errors about classes not being found, ctrl-shift-O or - (cmd-shift-O on the mac) to organize imports. -

        - -

        Step 13

        -

        Run it! -

          -
        1. - Right click on the Notepadv1 project.
        2. -
        3. - From the popup menu, select Run As > - Android Application.
        4. -
        5. - If you see a dialog come up, select Android Launcher as the way of running - the application (you can also use the link near the top of the dialog to - set this as your default for the workspace; this is recommended as it will - stop the plugin from asking you this every time).
        6. -
        7. Add new notes by hitting the menu button and selecting Add - Item from the menu.
        8. -
        - -

        Solution and Next Steps

        -

        You can see the solution to this class in Notepadv1Solution -from -the zip file to compare with your own.

        - -

        Once you are ready, move on to Tutorial -Exercise 2 to add the ability to create, edit and delete notes.

        - diff --git a/docs/html/guide/tutorials/notepad/notepad-ex2.jd b/docs/html/guide/tutorials/notepad/notepad-ex2.jd deleted file mode 100644 index fed40abb267e..000000000000 --- a/docs/html/guide/tutorials/notepad/notepad-ex2.jd +++ /dev/null @@ -1,642 +0,0 @@ -Rpage.title=Notepad Exercise 2 -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -

        In this exercise, you will add a second Activity to your notepad application, to let the user -create and edit notes. You will also allow the user to delete existing notes through a context menu. -The new Activity assumes responsibility for creating new notes by -collecting user input and packing it into a return Bundle provided by the intent. This exercise -demonstrates:

        -
          -
        • Constructing a new Activity and adding it to the Android manifest
        • -
        • Invoking another Activity asynchronously using startActivityForResult()
        • -
        • Passing data between Activity in Bundle objects
        • -
        • How to use a more advanced screen layout
        • -
        • How to create a context menu
        • -
        - - - -

        Step 1

        - -

        Create a new Android project using the sources from Notepadv2 under the -NotepadCodeLab folder, just like you did for the first exercise. If you see an error about -AndroidManifest.xml, or some problems related to an -android.zip file, right click on the project and select Android -Tools > Fix Project Properties.

        - -

        Open the Notepadv2 project and take a look around:

        -
          -
        • - Open and look at the strings.xml file under - res/values — there are several new strings which we will use - for our new functionality -
        • -
        • - Also, open and take a look at the top of the Notepadv2 class, - you will notice several new constants have been defined along with a new mNotesCursor - field used to hold the cursor we are using. -
        • -
        • - Note also that the fillData() method has a few more comments and now uses - the new field to store the notes Cursor. The onCreate() method is - unchanged from the first exercise. Also notice that the member field used to store the - notes Cursor is now called mNotesCursor. The m denotes a member - field and is part of the Android coding style standards. -
        • -
        • - There are also a couple of new overridden methods - (onCreateContextMenu(), onContextItemSelected(), - onListItemClick() and onActivityResult()) - which we will be filling in below. -
        • -
        - - -

        Step 2

        - - -

        First, let's create the context menu that will allow users to delete individual notes. -Open the Notepadv2 class.

        - -
          -
        1. In order for each list item in the ListView to register for the context menu, we call - registerForContextMenu() and pass it our ListView. So, at the very end of - the onCreate() method add this line: -
          registerForContextMenu(getListView());
          -

          Because our Activity extends the ListActivity class, getListView() will return us - the local ListView object for the Activity. Now, each list item in this ListView will activate the - context menu. -

        2. - Now fill in the onCreateContextMenu() method. This callback is similar to the other - menu callback used for the options menu. Here, we add just one line, which will add a menu item - to delete a note. Call menu.add() like so: -
          -public void onCreateContextMenu(Menu menu, View v,
          -        ContextMenu.ContextMenuInfo menuInfo) {
          -    super.onCreateContextMenu(menu, v, menuInfo);
          -    menu.add(0, DELETE_ID, 0, R.string.menu_delete);
          -}
          -

          The onCreateContextMenu() callback passes some other information in addition to the Menu object, - such as the View that has been triggered for the menu and - an extra object that may contain additional information about the object selected. However, we don't care about - these here, because we only have one kind of object in the Activity that uses context menus. In the next - step, we'll handle the menu item selection.

          -
        3. -
        - -

        Step 3

        -

        Now that the we've registered our ListView for a context menu and defined our context menu item, we need - to handle the callback when it is selected. For this, we need to identify the list ID of the - selected item, then delete it. So fill in the - onContextItemSelected() method like this:

        -
        -public boolean onContextItemSelected(MenuItem item) {
        -    switch(item.getItemId()) {
        -    case DELETE_ID:
        -        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        -        mDbHelper.deleteNote(info.id);
        -        fillData();
        -        return true;
        -    }
        -    return super.onContextItemSelected(item);
        -}
        -

        Here, we retrieve the {@link android.widget.AdapterView.AdapterContextMenuInfo AdapterContextMenuInfo} -with {@link android.view.MenuItem#getMenuInfo()}. The id field of this object tells us -the position of the item in the ListView. We then pass this to the deleteNote() -method of our NotesDbAdapter and the note is deleted. That's it for the context menu — notes -can now be deleted.

        - -

        Step 4

        - - -

        Fill in the body of the createNote() method: -

        Create a new Intent to create a note - (ACTIVITY_CREATE) using the NoteEdit class. - Then fire the Intent using the startActivityForResult() method - call:

        -
        -Intent i = new Intent(this, NoteEdit.class);
        -startActivityForResult(i, ACTIVITY_CREATE);
        -

        This form of the Intent call targets a specific class in our Activity, in this case - NoteEdit. Since the Intent class will need to communicate with the Android - operating system to route requests, we also have to provide a Context (this).

        -

        The startActivityForResult() method fires the Intent in a way that causes a method - in our Activity to be called when the new Activity is completed. The method in our Activity - that receives the callback is called - onActivityResult() and we will implement it in a later step. The other way - to call an Activity is using startActivity() but this is a "fire-and-forget" way - of calling it — in this manner, our Activity is not informed when the Activity is completed, and there is - no way to return result information from the called Activity with startActivity(). -

        Don't worry about the fact that NoteEdit doesn't exist yet, - we will fix that soon.

        - - - -

        Step 5

        - -

        Fill in the body of the onListItemClick() override.

        -

        onListItemClick() is a callback method that we'll override. It is called when - the user selects an item from the list. It is passed four parameters: the - ListView object it was invoked from, the View - inside the ListView that was clicked on, the - position in the list that was clicked, and the - mRowId of the item that was clicked. In this instance we can - ignore the first two parameters (we only have one ListView it - could be), and we ignore the mRowId as well. All we are - interested in is the position that the user selected. We use - this to get the data from the correct row, and bundle it up to send to - the NoteEdit Activity.

        -

        In our implementation of the callback, the method creates an - Intent to edit the note using - the NoteEdit class. It then adds data into the extras Bundle of - the Intent, which will be passed to the called Activity. We use it - to pass in the title and body text, and the mRowId for the note we are - editing. Finally, it will fire the Intent using the - startActivityForResult() method call. Here's the code that - belongs in onListItemClick():

        -
        -super.onListItemClick(l, v, position, id);
        -Cursor c = mNotesCursor;
        -c.moveToPosition(position);
        -Intent i = new Intent(this, NoteEdit.class);
        -i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        -i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
        -        c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
        -i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
        -        c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
        -startActivityForResult(i, ACTIVITY_EDIT);
        -
          -
        • - putExtra() is the method to add items into the extras Bundle - to pass in to intent invocations. Here, we are - using the Bundle to pass in the title, body and mRowId of the note we want to edit. -
        • -
        • - The details of the note are pulled out from our query Cursor, which we move to the - proper position for the element that was selected in the list, with - the moveToPosition() method.
        • -
        • With the extras added to the Intent, we invoke the Intent on the - NoteEdit class by passing startActivityForResult() - the Intent and the request code. (The request code will be - returned to onActivityResult as the requestCode parameter.)
        • -
        -

        Note: We assign the mNotesCursor field to a local variable at the - start of the method. This is done as an optimization of the Android code. Accessing a local - variable is much more efficient than accessing a field in the Dalvik VM, so by doing this - we make only one access to the field, and five accesses to the local variable, making the - routine much more efficient. It is recommended that you use this optimization when possible.

        - - -

        Step 6

        - -

        The above createNote() and onListItemClick() - methods use an asynchronous Intent invocation. We need a handler for the callback, so here we fill - in the body of the onActivityResult().

        -

        onActivityResult() is the overridden method - which will be called when an Activity returns with a result. (Remember, an Activity - will only return a result if launched with startActivityForResult.) The parameters provided - to the callback are:

        -
          -
        • requestCode — the original request code - specified in the Intent invocation (either ACTIVITY_CREATE or - ACTIVITY_EDIT for us). -
        • -
        • resultCode — the result (or error code) of the call, this - should be zero if everything was OK, but may have a non-zero code indicating - that something failed. There are standard result codes available, and you - can also create your own constants to indicate specific problems. -
        • -
        • intent — this is an Intent created by the Activity returning - results. It can be used to return data in the Intent "extras." -
        • -
        -

        The combination of startActivityForResult() and - onActivityResult() can be thought of as an asynchronous RPC - (remote procedure call) and forms the recommended way for an Activity to invoke - another and share services.

        -

        Here's the code that belongs in your onActivityResult():

        -
        -super.onActivityResult(requestCode, resultCode, intent);
        -Bundle extras = intent.getExtras();
        -
        -switch(requestCode) {
        -case ACTIVITY_CREATE:
        -    String title = extras.getString(NotesDbAdapter.KEY_TITLE);
        -    String body = extras.getString(NotesDbAdapter.KEY_BODY);
        -    mDbHelper.createNote(title, body);
        -    fillData();
        -    break;
        -case ACTIVITY_EDIT:
        -    Long mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
        -    if (mRowId != null) {
        -        String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
        -        String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
        -        mDbHelper.updateNote(mRowId, editTitle, editBody);
        -    }
        -    fillData();
        -    break;
        -}
        - -
          -
        • - We are handling both the ACTIVITY_CREATE and - ACTIVITY_EDIT activity results in this method. -
        • -
        • - In the case of a create, we pull the title and body from the extras (retrieved from the - returned Intent) and use them to create a new note. -
        • -
        • - In the case of an edit, we pull the mRowId as well, and use that to update - the note in the database. -
        • -
        • - fillData() at the end ensures everything is up to date . -
        • -
        - - -

        Step 7

        - - - -

        Open the file note_edit.xml that has been provided and take a - look at it. This is the UI code for the Note Editor.

        -

        This is the most - sophisticated UI we have dealt with yet. The file is given to you to avoid - problems that may sneak in when typing the code. (The XML is very strict - about case sensitivity and structure, mistakes in these are the usual cause - of problems with layout.)

        -

        There is a new parameter used - here that we haven't seen before: android:layout_weight (in - this case set to use the value 1 in each case).

        -

        layout_weight is used in LinearLayouts - to assign "importance" to Views within the layout. All Views have a default - layout_weight of zero, meaning they take up only as much room - on the screen as they need to be displayed. Assigning a value higher than - zero will split up the rest of the available space in the parent View, according - to the value of each View's layout_weight and its ratio to the - overall layout_weight specified in the current layout for this - and other View elements.

        -

        To give an example: let's say we have a text label - and two text edit elements in a horizontal row. The label has no - layout_weight specified, so it takes up the minimum space - required to render. If the layout_weight of each of the two - text edit elements is set to 1, the remaining width in the parent layout will - be split equally between them (because we claim they are equally important). - If the first one has a layout_weight of 1 - and the second has a layout_weight of 2, then one third of the - remaining space will be given to the first, and two thirds to the - second (because we claim the second one is more important).

        -

        This layout also demonstrates how to nest multiple layouts - inside each other to achieve a more complex and pleasant layout. In this - example, a horizontal linear layout is nested inside the vertical one to - allow the title label and text field to be alongside each other, - horizontally.

        - - -

        Step 8

        - -

        Create a NoteEdit class that extends - android.app.Activity.

        -

        This is the first time we will have - created an Activity without the Android Eclipse plugin doing it for us. When - you do so, the onCreate() method is not automatically - overridden for you. It is hard to imagine an Activity that doesn't override - the onCreate() method, so this should be the first thing you do.

        -
          -
        1. Right click on the com.android.demo.notepad2 package - in the Package Explorer, and select New > Class from the popup - menu.
        2. -
        3. Fill in NoteEdit for the Name: field in the - dialog.
        4. -
        5. In the Superclass: field, enter - android.app.Activity (you can also just type Activity and hit - Ctrl-Space on Windows and Linux or Cmd-Space on the Mac, to invoke code - assist and find the right package and class).
        6. -
        7. Click Finish.
        8. -
        9. In the resulting NoteEdit class, right click in the editor - window and select Source > Override/Implement Methods...
        10. -
        11. Scroll down through the checklist in the dialog until you see - onCreate(Bundle) — and check the box next to it.
        12. -
        13. Click OK.

          The method should now appear in your class.

        14. -
        - -

        Step 9

        - -

        Fill in the body of the onCreate() method for NoteEdit.

        - -

        This will set the title of our new Activity to say "Edit Note" (one - of the strings defined in strings.xml). It will also set the - content view to use our note_edit.xml layout file. We can then - grab handles to the title and body text edit views, and the confirm button, - so that our class can use them to set and get the note title and body, - and attach an event to the confirm button for when it is pressed by the - user.

        -

        We can then unbundle the values that were passed in to the Activity - with the extras Bundle attached to the calling Intent. We'll use them to pre-populate - the title and body text edit views so that the user can edit them. - Then we will grab and store the mRowId so we can keep - track of what note the user is editing.

        - -
          -
        1. - Inside onCreate(), set up the layout:
          -
          setContentView(R.layout.note_edit);
          -
        2. -
        3. - Find the edit and button components we need: -

          These are found by the - IDs associated to them in the R class, and need to be cast to the right - type of View (EditText for the two text views, - and Button for the confirm button):

          -
          -mTitleText = (EditText) findViewById(R.id.title);
          -mBodyText = (EditText) findViewById(R.id.body);
          -Button confirmButton = (Button) findViewById(R.id.confirm);
          -

          Note that mTitleText and mBodyText are member - fields (you need to declare them at the top of the class definition).

          -
        4. -
        5. At the top of the class, declare a Long mRowId private field to store - the current mRowId being edited (if any). -
        6. -
        7. Continuing inside onCreate(), - add code to initialize the title, body and - mRowId from the extras Bundle in - the Intent (if it is present):
          -
          -mRowId = null;
          -Bundle extras = getIntent().getExtras();
          -if (extras != null) {
          -    String title = extras.getString(NotesDbAdapter.KEY_TITLE);
          -    String body = extras.getString(NotesDbAdapter.KEY_BODY);
          -    mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
          -
          -    if (title != null) {
          -        mTitleText.setText(title);
          -    }
          -    if (body != null) {
          -        mBodyText.setText(body);
          -    }
          -}
          -
            -
          • - We are pulling the title and - body out of the - extras Bundle that was set from the - Intent invocation. -
          • - We also null-protect the text field setting (i.e., we don't want to set - the text fields to null accidentally).
          • -
          -
        8. -
        9. - Create an onClickListener() for the button: -

          Listeners can be one of the more confusing aspects of UI - implementation, but - what we are trying to achieve in this case is simple. We want an - onClick() method to be called when the user presses the - confirm button, and use that to do some work and return the values - of the edited note to the Intent caller. We do this using something called - an anonymous inner class. This is a bit confusing to look at unless you - have seen them before, but all you really need to take away from this is - that you can refer to this code in the future to see how to create a - listener and attach it to a button. (Listeners are a common idiom - in Java development, particularly for user interfaces.) Here's the empty listener:
          -

          -confirmButton.setOnClickListener(new View.OnClickListener() {
          -
          -    public void onClick(View view) {
          -
          -    }
          -
          -});
          -
        10. -
        -

        Step 10

        - -

        Fill in the body of the onClick() method of the OnClickListener created in the last step.

        - -

        This is the code that will be run when the user clicks on the - confirm button. We want this to grab the title and body text from the edit - text fields, and put them into the return Bundle so that they can be passed - back to the Activity that invoked this NoteEdit Activity. If the - operation is an edit rather than a create, we also want to put the - mRowId into the Bundle so that the - Notepadv2 class can save the changes back to the correct - note.

        -
          -
        1. - Create a Bundle and put the title and body text into it using the - constants defined in Notepadv2 as keys:
          -
          -Bundle bundle = new Bundle();
          -
          -bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
          -bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
          -if (mRowId != null) {
          -    bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
          -}
          -
        2. -
        3. - Set the result information (the Bundle) in a new Intent and finish the Activity: -
          -Intent mIntent = new Intent();
          -mIntent.putExtras(bundle);
          -setResult(RESULT_OK, mIntent);
          -finish();
          -
            -
          • The Intent is simply our data carrier that carries our Bundle - (with the title, body and mRowId).
          • -
          • The setResult() method is used to set the result - code and return Intent to be passed back to the - Intent caller. In this case everything worked, so we return RESULT_OK for the - result code.
          • -
          • The finish() call is used to signal that the Activity - is done (like a return call). Anything set in the Result will then be - returned to the caller, along with execution control.
          • -
          -
        4. -
        -

        The full onCreate() method (plus supporting class fields) should - now look like this:

        -
        -private EditText mTitleText;
        -private EditText mBodyText;
        -private Long mRowId;
        -
        -@Override
        -protected void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.note_edit);
        -
        -    mTitleText = (EditText) findViewById(R.id.title);
        -    mBodyText = (EditText) findViewById(R.id.body);
        -
        -    Button confirmButton = (Button) findViewById(R.id.confirm);
        -
        -    mRowId = null;
        -    Bundle extras = getIntent().getExtras();
        -    if (extras != null) {
        -        String title = extras.getString(NotesDbAdapter.KEY_TITLE);
        -        String body = extras.getString(NotesDbAdapter.KEY_BODY);
        -        mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
        -
        -        if (title != null) {
        -            mTitleText.setText(title);
        -        }
        -        if (body != null) {
        -            mBodyText.setText(body);
        -        }
        -    }
        -
        -    confirmButton.setOnClickListener(new View.OnClickListener() {
        -
        -        public void onClick(View view) {
        -            Bundle bundle = new Bundle();
        -
        -            bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
        -            bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
        -            if (mRowId != null) {
        -                bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
        -            }
        -
        -            Intent mIntent = new Intent();
        -            mIntent.putExtras(bundle);
        -            setResult(RESULT_OK, mIntent);
        -            finish();
        -        }
        -    });
        -}
        - -
    - -

    Step 11

    - - - -

    Finally, the new Activity has to be defined in the manifest file:

    -

    Before the new Activity can be seen by Android, it needs its own - Activity entry in the AndroidManifest.xml file. This is to let - the system know that it is there and can be called. We could also specify - which IntentFilters the activity implements here, but we are going to skip - this for now and just let Android know that the Activity is - defined.

    -

    There is a Manifest editor included in the Eclipse plugin that makes it much easier - to edit the AndroidManifest file, and we will use this. If you prefer to edit the file directly - or are not using the Eclipse plugin, see the box at the end for information on how to do this - without using the new Manifest editor.

    -

      -
    1. Double click on the AndroidManifest.xml file in the package explorer to open it. -
    2. -
    3. Click the Application tab at the bottom of the Manifest editor.
    4. -
    5. Click Add... in the Application Nodes section. -

      If you see a dialog with radiobuttons at the top, select the top radio button: - "Create a new element at the top level, in Application".

    6. -
    7. Make sure "(A) Activity" is selected in the selection pane of the dialog, and click OK.
    8. -
    9. Click on the new "Activity" node, in the Application Nodes section, then - type .NoteEdit into the Name* - field to the right. Press Return/Enter.
    10. -
    -

    The Android Manifest editor helps you add more complex entries into the AndroidManifest.xml - file, have a look around at some of the other options available (but be careful not to select - them otherwise they will be added to your Manifest). This editor should help you understand - and alter the AndroidManifest.xml file as you move on to more advanced Android applications.

    - -

    If you prefer to edit this file directly, simply open the - AndroidManifest.xml file and look at the source (use the - AndroidManifest.xml tab in the eclipse editor to see the source code directly). - Then edit the file as follows:
    - <activity android:name=".NoteEdit" />

    - This should be placed just below the line that reads:
    - </activity> for the .Notepadv2 activity.

    - -

    Step 12

    - -

    Now Run it!

    -

    You should now be able to add real notes from -the menu, as well as delete an existing one. Notice that in order to delete, you must -first use the directional controls on the device to highlight the note. -Furthermore, selecting a note title from the list should bring up the note -editor to let you edit it. Press confirm when finished to save the changes -back to the database. - -

    Solution and Next Steps

    - -

    You can see the solution to this exercise in Notepadv2Solution -from the zip file to compare with your own.

    -

    Now try editing a note, and then hitting the back button on the emulator -instead of the confirm button (the back button is below the menu button). You -will see an error come up. Clearly our application still has some problems. -Worse still, if you did make some changes and hit the back button, when you go -back into the notepad to look at the note you changed, you will find that all -your changes have been lost. In the next exercise we will fix these -problems.

    - -

    -Once you are ready, move on to Tutorial -Exercise 3 where you will fix the problems with the back button and lost -edits by introducing a proper life cycle into the NoteEdit Activity.

    - - diff --git a/docs/html/guide/tutorials/notepad/notepad-ex3.jd b/docs/html/guide/tutorials/notepad/notepad-ex3.jd deleted file mode 100644 index 557738e4c105..000000000000 --- a/docs/html/guide/tutorials/notepad/notepad-ex3.jd +++ /dev/null @@ -1,366 +0,0 @@ -page.title=Notepad Exercise 3 -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -

    In this exercise, you will use life-cycle event callbacks to store and -retrieve application state data. This exercise demonstrates:

    -
      -
    • Life-cycle events and how your application can use them
    • -
    • Techniques for maintaining application state
    • -
    - -
    - [Exercise 1] - [Exercise 2] - - [Exercise 3] - - [Extra Credit] -
    - -

    Step 1

    - -

    Import Notepadv3 into Eclipse. If you see an error about -AndroidManifest.xml, or some problems related to an Android zip -file, right click on the project and select Android Tools > -Fix Project Properties from the popup menu. The starting point for this exercise is -exactly where we left off at the end of the Notepadv2.

    -

    The current application has some problems — hitting the back button when editing -causes a crash, and anything else that happens during editing will cause the -edits to be lost.

    -

    To fix this, we will move most of the functionality for creating and editing -the note into the NoteEdit class, and introduce a full life cycle for editing -notes.

    - -
      -
    1. Remove the code in NoteEdit that parses the title and body - from the extras Bundle. -

      Instead, we are going to use the DBHelper class - to access the notes from the database directly. All we need passed into the - NoteEdit Activity is a mRowId (but only if we are editing, if creating we pass - nothing). Remove these lines:

      -
      -String title = extras.getString(NotesDbAdapter.KEY_TITLE);
      -String body = extras.getString(NotesDbAdapter.KEY_BODY);
      -
    2. -
    3. We will also get rid of the properties that were being passed in - the extras Bundle, which we were using to set the title - and body text edit values in the UI. So delete: -
      -if (title != null) {
      -    mTitleText.setText(title);
      -}
      -if (body != null) {
      -    mBodyText.setText(body);
      -}
      -
    4. -
    - -

    Step 2

    - -

    Create a class field for a NotesDbAdapter at the top of the NoteEdit class:

    -
        private NotesDbAdapter mDbHelper;
    -

    Also add an instance of NotesDbAdapter in the - onCreate() method (right below the super.onCreate() call):

    -
    -    mDbHelper = new NotesDbAdapter(this);
    -    mDbHelper.open();
    - -

    Step 3

    - -

    In NoteEdit, we need to check the savedInstanceState for the -mRowId, in case the note - editing contains a saved state in the Bundle, which we should recover (this would happen - if our Activity lost focus and then restarted).

    -
      -
    1. - Replace the code that currently initializes the mRowId:
      -
      -        mRowId = null;
      -
      -        Bundle extras = getIntent().getExtras();
      -        if (extras != null) {
      -            mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
      -        }
      -        
      - with this: -
      -        mRowId = (savedInstanceState == null) ? null :
      -            (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
      -        if (mRowId == null) {
      -            Bundle extras = getIntent().getExtras();
      -            mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
      -                                    : null;
      -        }
      -        
      -
    2. -
    3. - Note the null check for savedInstanceState, and we still need to load up - mRowId from the extras Bundle if it is not - provided by the savedInstanceState. This is a ternary operator shorthand - to safely either use the value or null if it is not present. -
    4. -
    5. - Note the use of Bundle.getSerializable() instead of - Bundle.getLong(). The latter encoding returns a long primitive and - so can not be used to represent the case when mRowId is null. -
    6. -
    - -

    Step 4

    - -

    Next, we need to populate the fields based on the mRowId if we - have it:

    -
    populateFields();
    -

    This goes before the confirmButton.setOnClickListener() line. - We'll define this method in a moment.

    - -

    Step 5

    - -

    Get rid of the Bundle creation and Bundle value settings from the - onClick() handler method. The Activity no longer needs to - return any extra information to the caller. And because we no longer have - an Intent to return, we'll use the shorter version - of setResult():

    -
    -public void onClick(View view) {
    -    setResult(RESULT_OK);
    -    finish();
    -}
    -

    We will take care of storing the updates or new notes in the database - ourselves, using the life-cycle methods.

    - -

    The whole onCreate() method should now look like this:

    -
    -super.onCreate(savedInstanceState);
    -
    -mDbHelper = new NotesDbAdapter(this);
    -mDbHelper.open();
    -
    -setContentView(R.layout.note_edit);
    -
    -mTitleText = (EditText) findViewById(R.id.title);
    -mBodyText = (EditText) findViewById(R.id.body);
    -
    -Button confirmButton = (Button) findViewById(R.id.confirm);
    -
    -mRowId = (savedInstanceState == null) ? null :
    -    (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
    -if (mRowId == null) {
    -    Bundle extras = getIntent().getExtras();
    -    mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
    -                            : null;
    -}
    -
    -populateFields();
    -
    -confirmButton.setOnClickListener(new View.OnClickListener() {
    -
    -    public void onClick(View view) {
    -        setResult(RESULT_OK);
    -        finish();
    -    }
    -
    -});
    - -

    Step 6

    - -

    Define the populateFields() method.

    -
    -private void populateFields() {
    -    if (mRowId != null) {
    -        Cursor note = mDbHelper.fetchNote(mRowId);
    -        startManagingCursor(note);
    -        mTitleText.setText(note.getString(
    -	            note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
    -        mBodyText.setText(note.getString(
    -                note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
    -    }
    -}
    -

    This method uses the NotesDbAdapter.fetchNote() method to find the right note to -edit, then it calls startManagingCursor() from the Activity class, which -is an Android convenience method provided to take care of the Cursor life-cycle. This will release -and re-create resources as dictated by the Activity life-cycle, so we don't need to worry about -doing that ourselves. After that, we just look up the title and body values from the Cursor -and populate the View elements with them.

    - - -

    Step 7

    - - - -

    Still in the NoteEdit class, we now override the methods - onSaveInstanceState(), onPause() and - onResume(). These are our life-cycle methods - (along with onCreate() which we already have).

    - -

    onSaveInstanceState() is called by Android if the - Activity is being stopped and may be killed before it is - resumed! This means it should store any state necessary to - re-initialize to the same condition when the Activity is restarted. It is - the counterpart to the onCreate() method, and in fact the - savedInstanceState Bundle passed in to onCreate() is the same - Bundle that you construct as outState in the - onSaveInstanceState() method.

    - -

    onPause() and onResume() are also - complimentary methods. onPause() is always called when the - Activity ends, even if we instigated that (with a finish() call for example). - We will use this to save the current note back to the database. Good - practice is to release any resources that can be released during an - onPause() as well, to take up less resources when in the - passive state. onResume() will call our populateFields() method - to read the note out of the database again and populate the fields.

    - -

    So, add some space after the populateFields() method - and add the following life-cycle methods:

    -
      -
    1. - onSaveInstanceState(): -
      -    @Override
      -    protected void onSaveInstanceState(Bundle outState) {
      -        super.onSaveInstanceState(outState);
      -        saveState();
      -        outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
      -    }
      -

      We'll define saveState() next.

      -
    2. -
    3. - onPause(): -
      -    @Override
      -    protected void onPause() {
      -        super.onPause();
      -        saveState();
      -    }
      -
    4. -
    5. - onResume(): -
      -    @Override
      -    protected void onResume() {
      -        super.onResume();
      -        populateFields();
      -    }
      -
    6. -
    -

    Note that saveState() must be called in both onSaveInstanceState() -and onPause() to ensure that the data is saved. This is because there is no -guarantee that onSaveInstanceState() will be called and because when it is -called, it is called before onPause().

    - - -

    Step 8

    - -

    Define the saveState() method to put the data out to the -database.

    -
    -     private void saveState() {
    -        String title = mTitleText.getText().toString();
    -        String body = mBodyText.getText().toString();
    -
    -        if (mRowId == null) {
    -            long id = mDbHelper.createNote(title, body);
    -            if (id > 0) {
    -                mRowId = id;
    -            }
    -        } else {
    -            mDbHelper.updateNote(mRowId, title, body);
    -        }
    -    }
    -

    Note that we capture the return value from createNote() and if a valid row ID is - returned, we store it in the mRowId field so that we can update the note in future - rather than create a new one (which otherwise might happen if the life-cycle events are - triggered).

    - - -

    Step 9

    - -

    Now pull out the previous handling code from the - onActivityResult() method in the Notepadv3 - class.

    -

    All of the note retrieval and updating now happens within the - NoteEdit life cycle, so all the onActivityResult() - method needs to do is update its view of the data, no other work is - necessary. The resulting method should look like this:

    -
    -@Override
    -protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    -    super.onActivityResult(requestCode, resultCode, intent);
    -    fillData();
    -}
    - -

    Because the other class now does the work, all this has to do is refresh - the data.

    - -

    Step 10

    - -

    Also remove the lines which set the title and body from the - onListItemClick() method (again they are no longer needed, - only the mRowId is):

    -
    -    Cursor c = mNotesCursor;
    -    c.moveToPosition(position);
    -
    -and also remove: -
    -
    -    i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
    -                    c.getColumnIndex(NotesDbAdapter.KEY_TITLE)));
    -    i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
    -                    c.getColumnIndex(NotesDbAdapter.KEY_BODY)));
    -
    -so that all that should be left in that method is: -
    -
    -    super.onListItemClick(l, v, position, id);
    -    Intent i = new Intent(this, NoteEdit.class);
    -    i.putExtra(NotesDbAdapter.KEY_ROWID, id);
    -    startActivityForResult(i, ACTIVITY_EDIT);
    - -

    You can also now remove the mNotesCursor field from the class, and set it back to using - a local variable in the fillData() method: -

    -    Cursor notesCursor = mDbHelper.fetchAllNotes();

    -

    Note that the m in mNotesCursor denotes a member field, so when we - make notesCursor a local variable, we drop the m. Remember to rename the - other occurrences of mNotesCursor in your fillData() method. - -

    -Run it! (use Run As -> Android Application on the project right -click menu again)

    - -

    Solution and Next Steps

    - -

    You can see the solution to this exercise in Notepadv3Solution -from -the zip file to compare with your own.

    -

    -When you are ready, move on to the Tutorial -Extra Credit exercise, where you can use the Eclipse debugger to -examine the life-cycle events as they happen.

    diff --git a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd b/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd deleted file mode 100644 index 34f7063dfa01..000000000000 --- a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd +++ /dev/null @@ -1,70 +0,0 @@ -page.title=Notepad Extra Credit -parent.title=Notepad Tutorial -parent.link=index.html -@jd:body - - -

    In this exercise, you will use the debugger to look at the work you did -in Exercise 3. This exercise demonstrates:

    -
      -
    • How to set breakpoints to observe execution
    • -
    • How to run your application in debug mode
    • -
    - -
    - - [Exercise 1] - [Exercise 2] - [Exercise 3] - - [Extra Credit] - -
    - -

    Step 1

    - -

    Using the working Notepadv3, put breakpoints in the code at the - beginning of the onCreate(), onPause(), - onSaveInstanceState() and onResume() methods in the - NoteEdit class (if you are not familiar with Eclipse, just - right click in the narrow grey border on the left of the edit window at the - line you want a breakpoint, and select Toggle Breakpoint, you -should see a blue dot appear).

    - -

    Step 2

    - -

    Now start the notepad demo in debug mode:

    - -
      -
    1. - Right click on the Notepadv3 project and from the Debug menu - select Debug As -> Android Application.
    2. -
    3. - The Android emulator should say "waiting for debugger to connect" - briefly and then run the application.
    4. -
    5. - If it gets stuck on the waiting... screen, quit the emulator and Eclipse, - from the command line do an adb kill-server, and then restart -Eclipse and try again.
    - -

    Step 3

    - -

    When you edit or create a new note you should see the breakpoints getting - hit and the execution stopping.

    - -

    Step 4

    - -

    Hit the Resume button to let execution continue (yellow rectangle with a -green triangle to its right in the Eclipse toolbars near the top).

    - -

    Step 5

    - -

    Experiment a bit with the confirm and back buttons, and try pressing Home and - making other mode changes. Watch what life-cycle events are generated and -when.

    - -

    The Android Eclipse plugin not only offers excellent debugging support for -your application development, but also superb profiling support. You can also -try using Traceview to profile your application. If your application is running too slow, this can help you -find the bottlenecks and fix them.

    - diff --git a/docs/html/guide/tutorials/notepad/notepad-index.jd b/docs/html/guide/tutorials/notepad/notepad-index.jd deleted file mode 100644 index 151c50dcda67..000000000000 --- a/docs/html/guide/tutorials/notepad/notepad-index.jd +++ /dev/null @@ -1,143 +0,0 @@ -page.title=Notepad Tutorial -@jd:body - - -

    The tutorial in this section gives you a "hands-on" introduction -to the Android framework and the tools you use to build applications on it. -Starting from a preconfigured project file, it guides you through the process of -developing a simple notepad application and provides concrete examples of how to -set up the project, develop the application logic and user interface, and then -compile and run the application.

    - -

    The tutorial presents the notepad application development as a set of -exercises (see below), each consisting of several steps. You can follow along -with the steps in each exercise and gradually build up and refine your -application. The exercises explain each step in detail and provide all the -sample code you need to complete the application.

    - -

    When you are finished with the tutorial, you will have created a functioning -Android application and learned in depth about many of the most important -concepts in Android development. If you want to add more complex features to -your application, you can examine the code in an alternative implementation -of a notepad application, in the -Sample Code documentation.

    - - - -

    Who Should Use this Tutorial

    - -

    This tutorial is designed for experienced developers, especially those with -knowledge of the Java programming language. If you haven't written Java -applications before, you can still use the tutorial, but you might need to work -at a slower pace.

    - -

    The tutorial assumes that you have some familiarity with the basic Android -application concepts and terminology. If you aren't yet familiar with those, you -should read Overview of an Android -Application before continuing.

    - -

    Also note that this tutorial uses -the Eclipse development environment, with the Android plugin installed. If you -are not using Eclipse, you can follow the exercises and build the application, -but you will need to determine how to accomplish the Eclipse-specific -steps in your environment.

    - - -

    Preparing for the Exercises

    - -

    This tutorial builds on the information provided in the Installing the SDK and Hello Android -documents, which explain in detail how to set up your development environment -for building Android applications. Before you start this tutorial, you should -read both these documents, have the SDK installed, and your work environment set up.

    - -

    To prepare for this lesson:

    - -
      -
    1. Download the project - exercises archive (.zip)
    2. -
    3. Unpack the archive file to a suitable location on your machine
    4. -
    5. Open the NotepadCodeLab folder
    6. -
    - -

    Inside the NotepadCodeLab folder, you should see six project -files: Notepadv1, - Notepadv2, Notepadv3, - Notepadv1Solution, Notepadv2Solution - and Notepadv3Solution. The Notepadv# projects are -the starting points for each of the exercises, while the -Notepadv#Solution projects are the exercise - solutions. If you are having trouble with a particular exercise, you - can compare your current work against the exercise solution.

    - - -

    Exercises

    - -

    The table below lists the tutorial exercises and describes the development -areas that each covers. Each exercise assumes that you have completed any -previous exercises.

    - - - - - - - - - - - - - - - - - - -
    Exercise -1Start here. Construct a simple notes list that lets the user add new notes but not -edit them. Demonstrates the basics of ListActivity and creating -and handling - menu options. Uses a SQLite database to store the notes.
    Exercise 2Add a second Activity to the -application. Demonstrates constructing a -new Activity, adding it to the Android manifest, passing data between the -activities, and using more advanced screen layout. Also shows how to -invoke another Activity to return a result, using -startActivityForResult().
    Exercise 3Add handling of life-cycle events to -the application, to let it -maintain application state across the life cycle.
    Extra -CreditDemonstrates how to use the Eclipse -debugger and how you can use it to -view life-cycle events as they are generated. This section is optional but -highly recommended.
    - - - -

    Other Resources and Further Learning

    -
      -
    • For a lighter but broader introduction to concepts not covered in the -tutorial, -take a look at Common Android Tasks.
    • -
    • The Android SDK includes a variety of fully functioning sample applications -that make excellent opportunities for further learning. You can find the sample -applications in the samples/ directory of your downloaded SDK.
    • -
    • This tutorial draws from the full Notepad application included in the -samples/ directory of the SDK, though it does not match it exactly. -When you are done with the tutorial, -it is highly recommended that you take a closer look at this version of the Notepad -application, -as it demonstrates a variety of interesting additions for your application, -such as:
    • -
        -
      • Setting up a custom striped list for the list of notes.
      • -
      • Creating a custom text edit view that overrides the draw() -method to - make it look like a lined notepad.
      • -
      • Implementing a full ContentProvider for notes.
      • -
      • Reverting and discarding edits instead of just automatically saving -them.
      • -
      -
    diff --git a/docs/html/guide/tutorials/views/hello-autocomplete.jd b/docs/html/guide/tutorials/views/hello-autocomplete.jd deleted file mode 100644 index 07235a14ab48..000000000000 --- a/docs/html/guide/tutorials/views/hello-autocomplete.jd +++ /dev/null @@ -1,116 +0,0 @@ -page.title=Hello, AutoCompleteTextView -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    {@link android.widget.AutoCompleteTextView} is an implementation of the EditText widget that will provide -auto-complete suggestions as the user types. The suggestions are extracted from a collection of strings.

    - - -
      -
    1. Start a new project/Activity called HelloAutoComplete.
    2. -
    3. Open the layout file. - Make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      -    android:orientation="horizontal"
      -    android:layout_width="fill_parent" 
      -    android:layout_height="wrap_content">
      -
      -    <TextView
      -        android:layout_width="wrap_content"
      -        android:layout_height="wrap_content"
      -        android:text="Country" />
      -
      -    <AutoCompleteTextView android:id="@+id/edit"
      -        android:layout_width="fill_parent"
      -        android:layout_height="wrap_content"/>
      -
      -</LinearLayout>
      -
      -
    4. - -
    5. Open HelloAutoComplete.java and insert the following as the onCreate method: -
      -@Override
      -protected void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -
      -    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
      -    ArrayAdapter adapter = new ArrayAdapter(this,
      -            android.R.layout.simple_dropdown_item_1line, COUNTRIES);
      -    textView.setAdapter(adapter);
      -}
      -
      -

      Here, we create an AutoCompleteTextView from our layout. We then - create an {@link android.widget.ArrayAdapter} that binds a simple_dropdown_item_1line - layout item to each entry in the COUNTRIES array (which we'll add next). - The last part sets the ArrayAdapter to associate with our AutoCompleteTextView.

      -
    6. - -
    7. After the onCreate() method, add the String array: -
      -static final String[] COUNTRIES = new String[] {
      -  "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
      -  "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
      -  "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
      -  "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
      -  "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
      -  "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
      -  "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
      -  "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
      -  "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
      -  "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
      -  "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
      -  "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
      -  "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
      -  "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
      -  "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
      -  "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
      -  "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
      -  "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
      -  "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
      -  "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
      -  "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
      -  "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
      -  "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
      -  "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
      -  "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
      -  "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
      -  "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
      -  "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
      -  "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
      -  "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
      -  "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
      -  "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
      -  "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
      -  "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
      -  "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
      -  "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
      -  "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
      -  "Ukraine", "United Arab Emirates", "United Kingdom",
      -  "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
      -  "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
      -  "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
      -};
      -
      -

      This is the list of suggestions that will be offered as the user types into the - AutoCompleteTextView.

      -
    8. - -
    9. Now run it.
    10. -
    -

    As you type, you should see something like this:

    - - - -

    References

    -
      -
    • {@link android.R.layout}
    • -
    • {@link android.widget.ArrayAdapter}
    • -
    • {@link android.widget.AutoCompleteTextView}
    • -
    - - diff --git a/docs/html/guide/tutorials/views/hello-datepicker.jd b/docs/html/guide/tutorials/views/hello-datepicker.jd deleted file mode 100644 index fcd43f3f890f..000000000000 --- a/docs/html/guide/tutorials/views/hello-datepicker.jd +++ /dev/null @@ -1,151 +0,0 @@ -page.title=Hello, DatePicker -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.DatePicker} is a widget that allows the user to select a month, day and year.

    - - -
      -
    1. Start a new project/Activity called HelloDatePicker.
    2. -
    3. Open the layout file and make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:layout_width="wrap_content"
      -    android:layout_height="wrap_content"
      -    android:orientation="vertical">
      -
      -    <TextView android:id="@+id/dateDisplay"
      -            android:layout_width="wrap_content"
      -            android:layout_height="wrap_content"
      -            android:text=""/>
      -
      -    <Button android:id="@+id/pickDate"
      -            android:layout_width="wrap_content"
      -            android:layout_height="wrap_content"
      -            android:text="Change the date"/>
      -
      -</LinearLayout>
      -
      -

      For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that - will display the date and a {@link android.widget.Button} that will initiate the DatePicker dialog. - With this layout, the TextView will sit above the Button. - The text value in the TextView is set empty, as it will be filled - with the current date when our Activity runs.

      -
    4. - -
    5. Open HelloDatePicker.java. Insert the following to the HelloDatePicker class: -
      -    private TextView mDateDisplay;
      -    private Button mPickDate;
      -
      -    private int mYear;
      -    private int mMonth;
      -    private int mDay;
      -
      -    static final int DATE_DIALOG_ID = 0;
      -
      -    @Override
      -    protected void onCreate(Bundle savedInstanceState) {
      -        super.onCreate(savedInstanceState);
      -        setContentView(R.layout.main);
      -
      -        // capture our View elements
      -        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
      -        mPickDate = (Button) findViewById(R.id.pickDate);
      -
      -        // add a click listener to the button
      -        mPickDate.setOnClickListener(new View.OnClickListener() {
      -            public void onClick(View v) {
      -                showDialog(DATE_DIALOG_ID);
      -            }
      -        });
      -
      -        // get the current date
      -        final Calendar c = Calendar.getInstance();
      -        mYear = c.get(Calendar.YEAR);
      -        mMonth = c.get(Calendar.MONTH);
      -        mDay = c.get(Calendar.DAY_OF_MONTH);
      -
      -        // display the current date
      -        updateDisplay();
      -    }
      -
      -

      Tip: Press Ctrl(or Cmd) + Shift + O to import all needed packages.

      -

      We start by instantiating variables for our Views and date fields. - The DATE_DIALOG_ID is a static integer that uniquely identifies the Dialog. In the - onCreate() method, we get prepared by setting the layout and capturing the View elements. - Then we create an on-click listener for the Button, so that when it is clicked it will - show our DatePicker dialog. The showDialog() method will pop-up the date picker dialog - by calling the onCreateDialog() callback method - (which we'll define in the next section). We then create an - instance of {@link java.util.Calendar} and get the current year, month and day. Finally, we call - updateDisplay()—our own method (defined later) that will fill the TextView.

      -
    6. - -
    7. After the onCreate() method, add the onCreateDialog() callback method -(which is called by showDialog()) -
      -@Override
      -protected Dialog onCreateDialog(int id) {
      -    switch (id) {
      -    case DATE_DIALOG_ID:
      -        return new DatePickerDialog(this,
      -                    mDateSetListener,
      -                    mYear, mMonth, mDay);
      -    }
      -    return null;
      -}
      -
      -

      This method is passed the identifier we gave showDialog() and initializes - the DatePicker to the date we retrieved from our Calendar instance.

      -
    8. - -
    9. Following that, add the updateDisplay() method: -
      -    // updates the date we display in the TextView
      -    private void updateDisplay() {
      -        mDateDisplay.setText(
      -            new StringBuilder()
      -                    // Month is 0 based so add 1
      -                    .append(mMonth + 1).append("-")
      -                    .append(mDay).append("-")
      -                    .append(mYear).append(" "));
      -    }
      -
      -

      This uses the member date values to write the date to our TextView.

      -
    10. -
    11. Finally, add a listener that will be called when the user sets a new date: -
      -    // the callback received when the user "sets" the date in the dialog
      -    private DatePickerDialog.OnDateSetListener mDateSetListener =
      -            new DatePickerDialog.OnDateSetListener() {
      -
      -                public void onDateSet(DatePicker view, int year, 
      -                                      int monthOfYear, int dayOfMonth) {
      -                    mYear = year;
      -                    mMonth = monthOfYear;
      -                    mDay = dayOfMonth;
      -                    updateDisplay();
      -                }
      -            };
      -
      -

      This OnDateSetListener method listens for when the user is done setting the date - (clicks the "Set" button). At that time, this fires and we update our member fields with - the new date defined by the user and update our TextView by calling updateDisplay().

      -
    12. - -
    13. Now run it.
    14. -
    -

    When you press the "Change the date" button, you should see the following:

    - - -

    References

    -
      -
    • {@link android.widget.DatePicker}
    • -
    • {@link android.widget.Button}
    • -
    • {@link android.widget.TextView}
    • -
    • {@link java.util.Calendar}
    • -
    - diff --git a/docs/html/guide/tutorials/views/hello-formstuff.jd b/docs/html/guide/tutorials/views/hello-formstuff.jd deleted file mode 100644 index b554001b8bf4..000000000000 --- a/docs/html/guide/tutorials/views/hello-formstuff.jd +++ /dev/null @@ -1,262 +0,0 @@ -page.title=Hello, Form Stuff -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    This page introduces a variety of widgets, like image buttons, -text fields, checkboxes and radio buttons.

    - - -
      -
    1. Start a new project/Activity called HelloFormStuff.
    2. -
    3. Your layout file should have a basic LinearLayout: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:orientation="vertical"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent" >
      -    	
      -</LinearLayout>
      -
      -

      For each widget you want to add, just put the respective View inside here.

      -
    4. -
    -

    Tip: As you add new Android code, press Ctrl(or Cmd) + Shift + O -to import all needed packages.

    - - -

    ImageButton

    -

    A button with a custom image on it. -We'll make it display a message when pressed.

    -
      -
    1. - Drag the Android image on the right (or your own image) into the - res/drawable/ directory of your project. - We'll use this for the button.
    2. -
    3. Open the layout file and, inside the LinearLayout, add the {@link android.widget.ImageButton} element: -
      -<ImageButton
      -    android:id="@+id/android_button"
      -    android:layout_width="100dip"
      -    android:layout_height="wrap_content"
      -    android:src="@drawable/android" />	
      -
      -

      The source of the button - is from the res/drawable/ directory, where we've placed the android.png.

      -

      Tip: You can also reference some of the many built-in - images from the Android {@link android.R.drawable} resources, - like ic_media_play, for a "play" button image. To do so, change the source - attribute to android:src="@android:drawable/ic_media_play".

      -
    4. -
    5. To make the button to actually do something, add the following -code at the end of the onCreate() method: -
      -final ImageButton button = (ImageButton) findViewById(R.id.android_button);
      -button.setOnClickListener(new OnClickListener() {
      -    public void onClick(View v) {
      -        // Perform action on clicks
      -        Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
      -    }
      -});
      -
      -

      This captures our ImageButton from the layout, then adds an on-click listener to it. -The {@link android.view.View.OnClickListener} must define the onClick() method, which -defines the action to be made when the button is clicked. Here, we show a -{@link android.widget.Toast} message when clicked.

      -
    6. -
    7. Run it.
    8. -
    - - -

    EditText

    -

    A text field for user input. We'll make it display the text entered so far when the "Enter" key is pressed.

    - -
      -
    1. Open the layout file and, inside the LinearLayout, add the {@link android.widget.EditText} element: -
      -<EditText
      -    android:id="@+id/edittext"
      -    android:layout_width="fill_parent"
      -    android:layout_height="wrap_content"/>
      -
      -
    2. -
    3. To do something with the text that the user enters, add the following code -to the end of the onCreate() method: -
      -final EditText edittext = (EditText) findViewById(R.id.edittext);
      -edittext.setOnKeyListener(new OnKeyListener() {
      -    public boolean onKey(View v, int keyCode, KeyEvent event) {
      -        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
      -          // Perform action on key press
      -          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
      -          return true;
      -        }
      -        return false;
      -    }
      -});
      -
      -

      This captures our EditText element from the layout, then adds an on-key listener to it. -The {@link android.view.View.OnKeyListener} must define the onKey() method, which -defines the action to be made when a key is pressed. In this case, we want to listen for the -Enter key (when pressed down), then pop up a {@link android.widget.Toast} message with the -text from the EditText field. Be sure to return true after the event is handled, -so that the event doesn't bubble-up and get handled by the View (which would result in a -carriage return in the text field).

      -
    4. Run it.
    5. -
    - - -

    CheckBox

    -

    A checkbox for selecting items. We'll make it display the the current state when pressed.

    - -
      -
    1. Open the layout file and, inside the LinearLayout, add the {@link android.widget.CheckBox} element: -
      -<CheckBox android:id="@+id/checkbox"
      -    android:layout_width="wrap_content"
      -    android:layout_height="wrap_content"
      -    android:text="check it out" />
      -
      -
    2. -
    3. To do something when the state is changed, add the following code -to the end of the onCreate() method: -
      -final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
      -checkbox.setOnClickListener(new OnClickListener() {
      -    public void onClick(View v) {
      -        // Perform action on clicks
      -        if (checkbox.isChecked()) {
      -            Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
      -        } else {
      -            Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
      -        }
      -    }
      -});
      -
      -

      This captures our CheckBox element from the layout, then adds an on-click listener to it. -The {@link android.view.View.OnClickListener} must define the onClick() method, which -defines the action to be made when the checkbox is clicked. Here, we query the current state of the -checkbox, then pop up a {@link android.widget.Toast} message that displays the current state. -Notice that the CheckBox handles its own state change between checked and un-checked, so we just -ask which it currently is.

      -
    4. Run it.
    5. -
    -

    Tip: If you find that you need to change the state -in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}), -use setChecked(true) or toggle().

    - - -

    RadioButton

    -

    Two mutually-exclusive radio buttons—enabling one disables the other. -When each is pressed, we'll pop up a message.

    - -
      -
    1. Open the layout file and, inside the LinearLayout, add two {@link android.widget.RadioButton}s, -inside a {@link android.widget.RadioGroup}: -
      -<RadioGroup
      -  android:layout_width="fill_parent"
      -  android:layout_height="wrap_content"
      -  android:orientation="vertical">
      -  
      -  <RadioButton android:id="@+id/radio_red"
      -      android:layout_width="wrap_content"
      -      android:layout_height="wrap_content"
      -      android:text="Red" />
      -  
      -  <RadioButton android:id="@+id/radio_blue"
      -      android:layout_width="wrap_content"
      -      android:layout_height="wrap_content"
      -      android:text="Blue" />
      -  
      -</RadioGroup>
      -
      -
    2. -
    3. To do something when each is selected, we'll need an OnClickListener. Unlike the other -listeners we've created, instead of creating this one as an anonymous inner class, -we'll create it as a new object. This way, we can re-use the OnClickListener for -both RadioButtons. So, add the following code in the HelloFormStuff Activity -(outside the onCreate() method): -
      -OnClickListener radio_listener = new OnClickListener() {
      -    public void onClick(View v) {
      -        // Perform action on clicks
      -        RadioButton rb = (RadioButton) v;
      -        Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
      -    }
      -};
      -
      -

      Our onClick() method will be handed the View clicked, so the first thing to do -is cast it into a RadioButton. Then we pop up a -{@link android.widget.Toast} message that displays the selection.

      -
    4. Now, at the bottom of the onCreate() method, add the following: -
      -  final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red);
      -  final RadioButton radio_blue = (RadioButton) findViewById(R.id.radio_blue);
      -  radio_red.setOnClickListener(radio_listener);
      -  radio_blue.setOnClickListener(radio_listener);
      -
      -

      This captures each of the RadioButtons from our layout and adds the newly-created -OnClickListener to each.

      -
    5. Run it.
    6. -
    -

    Tip: If you find that you need to change the state of a -RadioButton in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}), -use setChecked(true) or toggle().

    - - -

    ToggleButton

    -

    A button used specifically for toggling something on and off.

    - -
      -
    1. Open the layout file and, inside the LinearLayout, add the {@link android.widget.ToggleButton} element: -
      -<ToggleButton android:id="@+id/togglebutton"
      -    android:layout_width="wrap_content"
      -    android:layout_height="wrap_content" />
      -
      -
    2. -
    3. To do something when the state is changed, add the following code -to the end of the onCreate() method: -
      -final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
      -togglebutton.setOnClickListener(new OnClickListener() {
      -    public void onClick(View v) {
      -        // Perform action on clicks
      -        if (togglebutton.isChecked()) {
      -            Toast.makeText(HelloFormStuff.this, "ON", Toast.LENGTH_SHORT).show();
      -        } else {
      -            Toast.makeText(HelloFormStuff.this, "OFF", Toast.LENGTH_SHORT).show();
      -        }
      -    }
      -});
      -
      -

      This captures our ToggleButton element from the layout, then adds an on-click listener to it. -The {@link android.view.View.OnClickListener} must define the onClick() method, which -defines the action to be made when the button is clicked. Here, we query the current state of the -ToggleButton, then pop up a {@link android.widget.Toast} message that displays the current state. -Notice that the ToggleButton handles its own state change between checked and un-checked, so we just -ask which it is.

      -
    4. Run it.
    5. -
    - -

    Tip: By default, the text on the button is "ON" and "OFF", but -you can change each of these with setTextOn(CharSequence) and -setTextOff(CharSequence). And, if you find that you need to change the state -in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}), -use setChecked(true) or toggle().

    - - -

    If you've added all the form items above, your application should look something like this:

    - - -

    References

    -
      -
    • {@link android.widget.ImageButton}
    • -
    • {@link android.widget.EditText}
    • -
    • {@link android.widget.CheckBox}
    • -
    • {@link android.widget.RadioButton}
    • -
    • {@link android.widget.ToggleButton}
    • -
    - diff --git a/docs/html/guide/tutorials/views/hello-gallery.jd b/docs/html/guide/tutorials/views/hello-gallery.jd deleted file mode 100644 index 084f912ca646..000000000000 --- a/docs/html/guide/tutorials/views/hello-gallery.jd +++ /dev/null @@ -1,135 +0,0 @@ -page.title=Hello, Gallery -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.Gallery} is a View commonly used to display items in a horizontally scrolling list -that locks the current selection at the center. When one is selected, we'll show a message.

    - - -
      -
    1. Start a new project/Activity called HelloGallery.
    2. -
    3. Add some images to your res/drawable/ directory.
    4. -
    5. Open the layout file and make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
      -    android:id="@+id/gallery"
      -    android:layout_width="fill_parent"
      -    android:layout_height="wrap_content"
      -/>
      -
      -
    6. - - -
    7. Open the HelloGallery.java file. Insert the following for the onCreate() method: -
      -@Override
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -
      -    Gallery g = (Gallery) findViewById(R.id.gallery);
      -    g.setAdapter(new ImageAdapter(this));
      -
      -    g.setOnItemClickListener(new OnItemClickListener() {
      -        public void onItemClick(AdapterView parent, View v, int position, long id) {
      -            Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
      -        }
      -    });
      -}
      -
      -

      We start as usual: set the layout and capture the View we want (our Gallery). -We then set an Adapter, called ImageAdapter for the Gallery—this is a new class that -we'll create next. Then we create an item click listener for the Gallery. This is like a normal -on-click listener (which you might be familiar with for buttons), but it listens to each item -that we've added to the Gallery. The onItemClick() callback method -receives the AdapterView where the click occurred, the specific View that received the click, the -position of the View clicked (zero-based), and the row id of the item clicked (if applicable). All -that we care about is the position, so that we can pop up a {@link android.widget.Toast} message that -tells us the index position of the item clicked. We do this with Toast.makeText().show(). -

      -
    8. - -
    9. After the onCreate() method, add the ImageAdapter class: -
      -public class ImageAdapter extends BaseAdapter {
      -    int mGalleryItemBackground;
      -    private Context mContext;
      -
      -    private Integer[] mImageIds = {
      -            R.drawable.sample_1,
      -            R.drawable.sample_2,
      -            R.drawable.sample_3,
      -            R.drawable.sample_4,
      -            R.drawable.sample_5,
      -            R.drawable.sample_6,
      -            R.drawable.sample_7
      -    };
      -
      -    public ImageAdapter(Context c) {
      -        mContext = c;
      -        TypedArray a = obtainStyledAttributes(android.R.styleable.Theme);
      -        mGalleryItemBackground = a.getResourceId(
      -                android.R.styleable.Theme_galleryItemBackground, 0);
      -        a.recycle();
      -    }
      -
      -    public int getCount() {
      -        return mImageIds.length;
      -    }
      -
      -    public Object getItem(int position) {
      -        return position;
      -    }
      -
      -    public long getItemId(int position) {
      -        return position;
      -    }
      -
      -    public View getView(int position, View convertView, ViewGroup parent) {
      -        ImageView i = new ImageView(mContext);
      -
      -        i.setImageResource(mImageIds[position]);
      -        i.setLayoutParams(new Gallery.LayoutParams(150, 100));
      -        i.setScaleType(ImageView.ScaleType.FIT_XY);
      -        i.setBackgroundResource(mGalleryItemBackground);
      -
      -        return i;
      -    }
      -}
      -
      -

      First, there are a few member variables, including an array of IDs that reference -the images we placed in our drawable resources directory.

      -

      Next is the constructor, where we define the member Context. The rest of the constructor -sets up a reference for our Gallery them, which adds the nice framing for each Gallery item. -Once we have our mGalleryItemBackground, it's important to recycle the -StyledAttribute for later re-use.

      -

      The next three methods are required for basic member queries. -But then we have the getView() method, which is called -for each item read by our ImageAdapter, when the Gallery is being built. Here, we -use our member Context to create a new {@link android.widget.ImageView}. We then define -the image resource with the current position of the Gallery items (corresponding to our -array of drawables), set the dimensions for the ImageView, -set the image scaling to fit the ImageView dimensions, then finally set the -background theme for the ImageView.

      - -

      See {@link android.widget.ImageView.ScaleType} -for other image scaling options, in case you want to avoid stretching images that don't -exactly match the ImageView dimensions.

      - -
    10. Now run it.
    11. -
    -

    You should see something like this:

    - - - -

    References

    -
      -
    • {@link android.widget.BaseAdapter}
    • -
    • {@link android.widget.Gallery}
    • -
    • {@link android.widget.ImageView}
    • -
    • {@link android.widget.Toast}
    • -
    - - diff --git a/docs/html/guide/tutorials/views/hello-gridview.jd b/docs/html/guide/tutorials/views/hello-gridview.jd deleted file mode 100644 index 186c4e7513a6..000000000000 --- a/docs/html/guide/tutorials/views/hello-gridview.jd +++ /dev/null @@ -1,129 +0,0 @@ -page.title=Hello, GridView -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.GridView} displays items in a two-dimensional, scrolling grid. The items -are acquired from a {@link android.widget.ListAdapter}.

    - - -
      -
    1. Start a new project/Activity called HelloGridView.
    2. -
    3. Find some photos you'd like to use, or copy some from the SDK samples res/drawable/ - folder of your project.
    4. -
    5. Open the layout and make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
      -    android:id="@+id/gridview"
      -    android:layout_width="fill_parent" 
      -    android:layout_height="fill_parent"
      -    android:numColumns="auto_fit"
      -    android:verticalSpacing="10dp"
      -    android:horizontalSpacing="10dp"
      -    android:columnWidth="90dp"
      -    android:stretchMode="columnWidth"
      -    android:gravity="center"
      -/>
      -
      -
    6. -
    7. Open the HelloGridView Java file. Insert the following for the onCreate() method: -
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -
      -    GridView gridview = (GridView) findViewById(R.id.gridview);
      -    gridview.setAdapter(new ImageAdapter(this));
      -}
      -
      -

      Here, we get a handle on our GridView, from the layout, and give it an Adapter. - We're actually going to create our own Adapter called ImageAdapter.

      -
    8. -
    9. Create a new class (nested or otherwise), called ImageAdapter, which extends {@link android.widget.BaseAdapter}: -
      -public class ImageAdapter extends BaseAdapter {
      -    private Context mContext;
      -
      -    public ImageAdapter(Context c) {
      -        mContext = c;
      -    }
      -
      -    public int getCount() {
      -        return mThumbIds.length;
      -    }
      -
      -    public Object getItem(int position) {
      -        return null;
      -    }
      -
      -    public long getItemId(int position) {
      -        return 0;
      -    }
      -
      -    // create a new ImageView for each item referenced by the Adapter
      -    public View getView(int position, View convertView, ViewGroup parent) {
      -        ImageView imageView;
      -        if (convertView == null) {  // if it's not recycled, initialize some attributes
      -            imageView = new ImageView(mContext);
      -            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
      -            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
      -            imageView.setPadding(8, 8, 8, 8);
      -        } else {
      -            imageView = (ImageView) convertView;
      -        }
      -
      -        imageView.setImageResource(mThumbIds[position]);
      -        return imageView;
      -    }
      -
      -    // references to our images
      -    private Integer[] mThumbIds = {
      -            R.drawable.sample_2, R.drawable.sample_3,
      -            R.drawable.sample_4, R.drawable.sample_5,
      -            R.drawable.sample_6, R.drawable.sample_7,
      -            R.drawable.sample_0, R.drawable.sample_1,
      -            R.drawable.sample_2, R.drawable.sample_3,
      -            R.drawable.sample_4, R.drawable.sample_5,
      -            R.drawable.sample_6, R.drawable.sample_7,
      -            R.drawable.sample_0, R.drawable.sample_1,
      -            R.drawable.sample_2, R.drawable.sample_3,
      -            R.drawable.sample_4, R.drawable.sample_5,
      -            R.drawable.sample_6, R.drawable.sample_7
      -    };
      -}
      -
      -

      First we take care of some required methods inherited from BaseAdapter. - The constructor and getCount() are self-explanatory. Normally, getItem() - should return the actual object at the specified position in our Adapter, but for this Hello World, - we're not going to bother. Likewise, getItemId() should return the row id of - the item, but right now we don't care.

      -

      However, getView() is the method we care about. This one creates a new View for each image that we - put in our ImageAdapter. So we're going to create an ImageView each time. When this is called, we're - going to receive a View, which is likely a recycled View object (at least after the first call), so we - check for this—if it's null, we initialize the ImageView and setup all the properties we want. - The LayoutParams() initialization sets the height and width of the View—this ensures - that no matter the drawable size, each image is resized and cropped to fit in the ImageView (if necessary). - With setScaleType(), we say that images should be cropped toward the center (if necessary). - And finally, we set the padding within the ImageView. (Note that, if the images have various aspect-ratios, - as they do in this demo, then less padding will cause for more cropping of the image, if it does not match - the dimensions given to the ImageView.) At the end of getView() we set the image resource and - return the ImageView.

      -

      All that's left is our array or drawable resources at the bottom.

      -
    10. -
    11. Run it.
    12. -
    -

    Your grid layout should look something like this:

    - - -

    Try experimenting with the behaviors of the GridView and ImageView by adjusting their properties. For example, - instead of setting the ImageView LayoutParams, you can try using - {@link android.widget.ImageView#setAdjustViewBounds(boolean)}.

    - -

    References

    -
      -
    • {@link android.widget.GridView}
    • -
    • {@link android.widget.ImageView}
    • -
    • {@link android.widget.BaseAdapter}
    • -
    - diff --git a/docs/html/guide/tutorials/views/hello-linearlayout.jd b/docs/html/guide/tutorials/views/hello-linearlayout.jd deleted file mode 100644 index 0e8947c10e3a..000000000000 --- a/docs/html/guide/tutorials/views/hello-linearlayout.jd +++ /dev/null @@ -1,130 +0,0 @@ -page.title=Hello, LinearLayout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.LinearLayout} is a GroupView that will lay child View elements -vertically or horizontally.

    - - -
      -
    1. Start a new project/Activity called HelloLinearLayout.
    2. -
    3. Open the layout file. - Make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:orientation="vertical"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent">
      -
      -    <LinearLayout
      -	android:orientation="horizontal"
      -	android:layout_width="fill_parent"
      -	android:layout_height="fill_parent"
      -	android:layout_weight="1">
      -	
      -	<TextView
      -	    android:text="red"
      -	    android:gravity="center_horizontal"
      -	    android:background="#aa0000"
      -	    android:layout_width="wrap_content"
      -	    android:layout_height="fill_parent"
      -	    android:layout_weight="1"/>
      -	
      -	<TextView
      -	    android:text="green"
      -	    android:gravity="center_horizontal"
      -	    android:background="#00aa00"
      -	    android:layout_width="wrap_content"
      -	    android:layout_height="fill_parent"
      -	    android:layout_weight="1"/>
      -	
      -	<TextView
      -	    android:text="blue"
      -	    android:gravity="center_horizontal"
      -	    android:background="#0000aa"
      -	    android:layout_width="wrap_content"
      -	    android:layout_height="fill_parent"
      -	    android:layout_weight="1"/>
      -	
      -	<TextView
      -	    android:text="yellow"
      -	    android:gravity="center_horizontal"
      -	    android:background="#aaaa00"
      -	    android:layout_width="wrap_content"
      -	    android:layout_height="fill_parent"
      -	    android:layout_weight="1"/>
      -		
      -    </LinearLayout>
      -	
      -    <LinearLayout
      -	android:orientation="vertical"
      -	android:layout_width="fill_parent"
      -	android:layout_height="fill_parent"
      -	android:layout_weight="1">
      -	
      -	<TextView
      -	    android:text="row one"
      -	    android:textSize="15pt"
      -	    android:layout_width="fill_parent"
      -	    android:layout_height="wrap_content"
      -	    android:layout_weight="1"/>
      -	
      -	<TextView
      -	    android:text="row two"
      -	    android:textSize="15pt"
      -	    android:layout_width="fill_parent"
      -	    android:layout_height="wrap_content"
      -	    android:layout_weight="1"/>
      -	
      -	<TextView
      -	    android:text="row three"
      -	    android:textSize="15pt"
      -	    android:layout_width="fill_parent"
      -	    android:layout_height="wrap_content"
      -	    android:layout_weight="1"/>
      -	
      -	<TextView
      -	    android:text="row four"
      -	    android:textSize="15pt"
      -	    android:layout_width="fill_parent"
      -	    android:layout_height="wrap_content"
      -	    android:layout_weight="1"/>
      -        
      -    </LinearLayout>
      -        
      -</LinearLayout>
      -
      -

      Carefully inspect the XML. You'll notice how this layout works a lot like - an HTML layout. There is one parent LinearLayout that is defined to lay - its child elements vertically. The first child is another LinearLayout that uses a horizontal layout - and the second uses a vertical layout. Each LinearLayout contains several {@link android.widget.TextView} - elements.

      -
    4. -
    5. Now open the HelloLinearLayout Activity and be sure it loads this layout in the onCreate() method:

      -
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -}
      -
      -

      R.layout.main refers to the main.xml layout file.

      -
    6. -
    7. Run it.
    8. -
    -

    You should see the following:

    - - -

    Notice how the various XML attributes define the View's behavior. -Pay attention to the effect of the layout_weight. Try - experimenting with different values to see how the screen real estate is - distributed based on the weight of each element.

    - -

    References

    -
      -
    • {@link android.widget.LinearLayout}
    • -
    • {@link android.widget.TextView}
    • -
    - - diff --git a/docs/html/guide/tutorials/views/hello-listview.jd b/docs/html/guide/tutorials/views/hello-listview.jd deleted file mode 100644 index d90005bb4e5f..000000000000 --- a/docs/html/guide/tutorials/views/hello-listview.jd +++ /dev/null @@ -1,90 +0,0 @@ -page.title=Hello, ListView -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.ListView} is a View that shows items in a vertically scrolling list. The items are - acquired from a {@link android.widget.ListAdapter}.

    - - -
      -
    1. Start a new project/ListActivity called HelloListView.
    2. -
    3. Open the HelloListView Java file. Make the class extend ListActivity (instead of Activity). -
      public class HelloListView extends ListActivity {
      -
    4. -
    5. Insert the following for the onCreate() method: -
      -@Override
      -public void onCreate(Bundle savedInstanceState) {
      -  super.onCreate(savedInstanceState);
      -  
      -  setListAdapter(new ArrayAdapter<String>(this,
      -          android.R.layout.simple_list_item_1, COUNTRIES));
      -  getListView().setTextFilterEnabled(true);
      -}
      -
      -

      Notice that we don't need to load a layout (at least, not in this case, because we're using - the whole screen for our list). Instead, we just call setListAdapter() (which automatically - adds a ListView to the ListActivity), and provide it with an ArrayAdapter that binds a - simple_list_item_1 layout item to each entry in the COUNTRIES - array (added next). The next line of code adds a text filter to the ListView, so that when the user - begins typing, the list will filter the entire view to display only the items that match the entry.

      -
    6. -
    7. Following the onCreate() method, add the String array: -
      -  static final String[] COUNTRIES = new String[] {
      -    "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
      -    "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
      -    "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
      -    "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
      -    "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
      -    "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
      -    "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
      -    "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
      -    "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
      -    "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
      -    "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
      -    "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
      -    "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
      -    "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
      -    "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
      -    "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
      -    "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
      -    "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
      -    "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
      -    "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
      -    "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
      -    "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
      -    "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
      -    "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
      -    "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
      -    "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
      -    "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
      -    "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
      -    "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
      -    "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
      -    "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
      -    "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
      -    "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
      -    "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
      -    "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
      -    "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
      -    "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
      -    "Ukraine", "United Arab Emirates", "United Kingdom",
      -    "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
      -    "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
      -    "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
      -  };
      -
      -
    8. -
    9. Run it.
    10. -
    -

    You can scroll the list, or type to filter it. You should see something like this:

    - - -

    References

    -
      -
    • {@link android.widget.ListView}
    • -
    • {@link android.widget.ListAdapter}
    • -
    - diff --git a/docs/html/guide/tutorials/views/hello-mapview.jd b/docs/html/guide/tutorials/views/hello-mapview.jd deleted file mode 100644 index 5217b6b20e9f..000000000000 --- a/docs/html/guide/tutorials/views/hello-mapview.jd +++ /dev/null @@ -1,245 +0,0 @@ -page.title=Hello, MapView -parent.title=Hello, Views -parent.link=index.html -@jd:body - -
    -

    This tutorial requires that you have the Google Maps external library -installed in your SDK environment. By default the Android SDK includes the -Google APIs add-on, which in turn includes the Maps external library. If you -don't have the Google APIs SDK add-on, you can download it from this -location:

    - -

    http://code.google.com/android/add-ons/google-apis

    - -

    The Google APIs add-on requires Android 1.5 SDK or later release. After -installing the add-on in your SDK, set your project properties to use a Google -APIs build target. See the instructions for setting a build -target in Developing in -Eclipse with ADT or Developing in Other IDEs, -as appropriate for your environment.

    - -

    You will also need to use the android tool to set up an AVD that uses the -Google APIs deployment target. See Android Virtual Devices for -more information. Once you have set up your environment, you will be able to -build and run the project described in this tutorial

    - -
    - -

    A MapView allows you to create your own map-viewing Activity. -First, we'll create a simple Activity that can view and navigate a map. Then we will add some overlay items.

    - -
      -
    1. Start a new project/Activity called HelloMapView. - -
    2. Because we're using the Google Maps library, - which is not a part of the standard Android library, we need to - declare it in the Android Manifest. Open the AndroidManifest.xml - file and add the following as a child of the <application> element: - -
      <uses-library android:name="com.google.android.maps" />
      -
    3. -
    4. We also need access to the internet in order to retrieve the Google Maps tiles, - so the application must request the {@link android.Manifest.permission#INTERNET INTERNET} permissions. - In the manifest file, add the following as a child of the <manifest> element: -
      <uses-permission android:name="android.permission.INTERNET" />
      -
    5. -
    6. Now open the main layout file for your project. Define a layout with a com.google.android.maps.MapView - inside a android.widget.RelativeLayout: - -
      -<?xml version="1.0" encoding="utf-8"?>
      -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:id="@+id/mainlayout"
      -    android:orientation="vertical"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent" >
      -
      -    <com.google.android.maps.MapView
      -        android:id="@+id/mapview"
      -        android:layout_width="fill_parent"
      -        android:layout_height="fill_parent"
      -        android:clickable="true"
      -        android:apiKey="Your Maps API Key"
      -    />
      -
      -</RelativeLayout>
      -
      -

      The clickable attribute defines whether you want to allow user-interaction with the map. - In this case, we set it "true" so that the user can navigate.

      - -

      The apiKey attribute holds the Google Maps API Key that proves your application and signer - certificate has been registered with the Google Maps service. Because MapView uses Google Maps data, this key is required - in order to receive the map data, even while you are developing. Registration is free and it only takes a couple - minutes to register your certificate and receive a Maps API Key. For instructions on getting a key, read - Obtaining a Maps API Key. - (For the purpose of this tutorial, you should register with the fingerprint of the SDK debug certificate.) - Once you've acquired the Maps API Key, insert it for the apiKey value.

    7. - -
    8. Now open the HelloMapView.java file. For this Activity, we're going to extend the special sub-class of - Activity called MapActivity, so change the class declaration to extend - MapActivity, instead of Activity:

      - -
      public class HelloMapView extends MapActivity {
      - -
    9. The isRouteDisplayed() method is required, so add it inside the class: -
      -@Override
      -protected boolean isRouteDisplayed() {
      -    return false;
      -}
      -
      -

      You can actually run this now, but all it does is allow you to pan around the map.

      - -
    10. Now go back to the HelloMapView class. We'll now retrieve the ZoomControls object from - the MapView and add it to our new layout element. First, at the top of the HelloMapView, - instantiate handles for the MapView and LinearLayout, plus a ZoomControl object: -
      -LinearLayout linearLayout;
      -MapView mapView;
      -
      - -
    11. Then initialize each of these in onCreate(). We'll capture the LinearLayout and - MapView through their layout resources. Then get the ZoomControls from the MapView:: -
      -mapView = (MapView) findViewById(R.id.mapview);
      -mapView.setBuiltInZoomControls(true);
      -
      - -

      By using the built-in zoom control provided by MapView, we don't have to do any of the work - required to actually perform the zoom operations. The controls will appear whenever the user - touches the map, then disappear after a few moments of inactivity.

    12. - -
    13. Run it.
    14. -
    - -
    - -

    So, we now have full interaction controls. All well and good, but what we really want our map -for is custom markers and layovers. Let's add some Overlay -objects to our map. To do this, we're going to -implement the ItemizedOverlay -class, which can manage a whole set of Overlay items for us.

    - -
      -
    1. Create a new Java class named HelloItemizedOverlay that implements ItemizedOverlay. - -

      When using Eclipse, right-click the package name in the Eclipse Package Explorer, and select New > Class. Fill-in - the Name field as HelloItemizedOverlay. For the Superclass, enter - com.google.android.maps.ItemizedOverlay. Click the checkbox for Constructors from - superclass. Click Finish.

    2. - -
    3. First thing, we need an OverlayItem ArrayList, in which we'll put each of the OverlayItem - objects we want on our map. Add this at the top of the HelloItemizedOverlay class: - -
      private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    4. - -
    5. All the constructor does is define the default marker to be used on each of the OverlayItems. - In order for the Drawable to actually get drawn, it must have its bounds defined. And we want the - center-point at the bottom of the image to be the point at which it's attached to the map - coordinates. We handle all this with the boundCenterBottom() method. Wrap this around our - defaultMarker, so the super constructor call looks like this: - -
      super(boundCenterBottom(defaultMarker));
    6. - -
    7. In order to add new OverlayItems to our ArrayList, we need a new public method. We'll handle - this with the following method: - -
      -public void addOverlay(OverlayItem overlay) {
      -    mOverlays.add(overlay);
      -    populate();
      -}
      - -

      Each time we add a new OverlayItem, we must call populate(), which will read each of out - OverlayItems and prepare them to be drawn.

    8. - -
    9. In order for the populate() method to read each OverlayItem, it will make a request to - createItem(int). We must define this method to properly read from our ArrayList. Replace the - existing contents of the createItem method with a get() call to our ArrayList: - -
      -@Override
      -protected OverlayItem createItem(int i) {
      -  return mOverlays.get(i);
      -}
      -
    10. - -
    11. We're also required to override the size() method. Replace the existing contents of the - method with a size request to our ArrayList: - -
      return mOverlays.size();
    12. -
    - - -

    That's it for the HelloItemizedOverlay class. We're now ready to use it.

    - -
    -

    Go back to the HelloMapView -class. We'll start by creating one OverlayItem, adding to an instance of our HelloItemizedOverlay, -and then adding this to the MapView.

    - - -

    First, we need the image that we'll use for our map overlay. Here, we'll use the Android on the -right as our marker. Drag this image (or your own) to the res/drawable/ directory of your project workspace.

    - -

    Now we're ready to work in the HelloMapView:

    - -
      -
    1. First we need some more types. Add the following at the top of the HelloMapView class: - -
      -List<Overlay> mapOverlays;
      -Drawable drawable;
      -HelloItemizedOverlay itemizedOverlay;
    2. - -
    3. Now pick up where we left off in the onCreate() method. Instantiate the - new fields: - -
      -mapOverlays = mapView.getOverlays();
      -drawable = this.getResources().getDrawable(R.drawable.androidmarker);
      -itemizedoverlay = new HelloItemizedOverlay(drawable);
      - -

      All overlay elements on a map are held by the MapView, so when we want to add some, we must - first retrieve the List with getOverlays() methods. We instantiate the Drawable, which will - be used as our map marker, by using our Context resources to get the Drawable we placed in - the res/drawable/ directory (androidmarker.png). Our HelloItemizedOverlay takes the Drawable in order to set the - default marker.

    4. - -
    5. Now let's make our first OverlayItem by creating a GeoPoint - that defines our map coordinates, then pass it to a new OverlayItem: - -
      -GeoPoint point = new GeoPoint(19240000,-99120000);
      -OverlayItem overlayitem = new OverlayItem(point, "", "");
      - -

      GeoPoint coordinates are based in microdegrees (degrees * 1e6). The OverlayItem takes this - GeoPoint and two strings. Here, we won't concern ourselves with the strings, which can display - text when we click our marker, because we haven't yet written the click handler for the OverlayItem.

    6. - -
    7. All that's left is for us to add this OverlayItem to our collection in the HelloItemizedOverlay, - and add this to the List of Overlay objects retrieved from the MapView: - -
      -itemizedoverlay.addOverlay(overlayitem);
      -mapOverlays.add(itemizedoverlay);
    8. - -
    9. Run it!
    10. -
    - -

    We've sent our droid to Mexico City. Hola, Mundo!

    -

    You should see the following:

    - - -

    Because we created our ItemizedOverlay class with an ArrayList, we can continue adding new -OverlayItems. Try adding another one. Before the addOverlay() method is called, add these lines:

    -
    -GeoPoint point2 = new GeoPoint(35410000, 139460000);
    -OverlayItem overlayitem2 = new OverlayItem(point2, "", "");
    -
    -

    Run it again... We've sent a new droid to Tokyo. Sekai, konichiwa!

    - diff --git a/docs/html/guide/tutorials/views/hello-relativelayout.jd b/docs/html/guide/tutorials/views/hello-relativelayout.jd deleted file mode 100644 index 1b915379739c..000000000000 --- a/docs/html/guide/tutorials/views/hello-relativelayout.jd +++ /dev/null @@ -1,75 +0,0 @@ -page.title=Hello, RelativeLayout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.RelativeLayout} is a ViewGroup that allows you to layout child elements -in positions relative to the parent or siblings elements.

    - -
      -
    1. Start a new project/Activity called HelloRelativeLayout.
    2. -
    3. Open the layout file. Make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent">
      -
      -    <TextView
      -        android:id="@+id/label"
      -        android:layout_width="fill_parent"
      -        android:layout_height="wrap_content"
      -        android:text="Type here:"/>
      -
      -    <EditText
      -        android:id="@+id/entry"
      -        android:layout_width="fill_parent"
      -        android:layout_height="wrap_content"
      -        android:background="@android:drawable/editbox_background"
      -        android:layout_below="@id/label"/>
      -
      -    <Button
      -        android:id="@+id/ok"
      -        android:layout_width="wrap_content"
      -        android:layout_height="wrap_content"
      -        android:layout_below="@id/entry"
      -        android:layout_alignParentRight="true"
      -        android:layout_marginLeft="10dip"
      -        android:text="OK" />
      -
      -    <Button
      -        android:layout_width="wrap_content"
      -        android:layout_height="wrap_content"
      -        android:layout_toLeftOf="@id/ok"
      -        android:layout_alignTop="@id/ok"
      -        android:text="Cancel" />
      -
      -</RelativeLayout>
      -
      -

      Pay attention to each of the additional layout_* attributes (besides the -usual width and height, which are required for all elements). When using relative layout, -we use attributes like layout_below and layout_toLeftOf to describe -how we'd like to position each View. Naturally, these are different relative positions, and the -value of the attribute is the id of the element we want the position relative to.

      -
    4. -
    5. Make sure your Activity loads this layout in the onCreate() method:

      -
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -}
      -
      -

      R.layout.main refers to the main.xml layout file.

      -
    6. -
    7. Run it.
    8. -
    -

    You should see the following:

    - - -

    Resources

    -
      -
    • {@link android.widget.RelativeLayout}
    • -
    • {@link android.widget.TextView}
    • -
    • {@link android.widget.EditText}
    • -
    • {@link android.widget.Button}
    • -
    diff --git a/docs/html/guide/tutorials/views/hello-spinner.jd b/docs/html/guide/tutorials/views/hello-spinner.jd deleted file mode 100644 index 3a04214a1f3d..000000000000 --- a/docs/html/guide/tutorials/views/hello-spinner.jd +++ /dev/null @@ -1,106 +0,0 @@ -page.title=Hello, Spinner -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.Spinner} is a widget that allows the user to select an item from a group. -It is similar to a dropdown list and will allow scrolling when the -list exceeds the available vertical space on the screen.

    - - -
      -
    1. Start a new project/Activity called HelloSpinner.
    2. -
    3. Open the layout file. - Make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:orientation="vertical"
      -    android:padding="10dip"
      -    android:layout_width="fill_parent"
      -    android:layout_height="wrap_content">
      -
      -    <TextView
      -        android:layout_width="fill_parent"
      -        android:layout_height="wrap_content"
      -        android:layout_marginTop="10dip"
      -        android:text="Please select a planet:"
      -    />
      -
      -    <Spinner 
      -        android:id="@+id/spinner"
      -        android:layout_width="fill_parent"
      -        android:layout_height="wrap_content"
      -        android:drawSelectorOnTop="true"
      -        android:prompt="@string/planet_prompt"
      -    />
      -
      -</LinearLayout>
      -
      -

      Notice that the Spinner's android:prompt is a string resource. In - this case, Android does not allow it to be a string, it must be a reference to a resource. - So...

      -
    4. - -
    5. Open the strings.xml file in res/values/ and add the following <string> -element inside the <resources> element: -
      -<string name="planet_prompt">Choose a planet</string>
      -
      -
    6. - -
    7. Create a new XML file in res/values/ called arrays.xml. Insert the following: -
      -<resources>
      -
      -    <string-array name="planets">
      -        <item>Mercury</item>
      -        <item>Venus</item>
      -        <item>Earth</item>
      -        <item>Mars</item>
      -        <item>Jupiter</item>
      -        <item>Saturn</item>
      -        <item>Uranus</item>
      -        <item>Neptune</item>
      -    </string-array>
      -    
      -</resources>
      -
      -

      This is the list of items (planets) that the user can select from in the Spinner widget.

      -
    8. - -
    9. Now open the HelloSpinner.java file. Insert the following code into the HelloSpinner class: -
      -@Override
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -
      -    Spinner s = (Spinner) findViewById(R.id.spinner);
      -    ArrayAdapter adapter = ArrayAdapter.createFromResource(
      -            this, R.array.planets, android.R.layout.simple_spinner_item);
      -    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      -    s.setAdapter(adapter);
      -}
      -
      -

      That's it. We start by creating a Spinner from our layout. We then create an {@link android.widget.ArrayAdapter} - that binds each element of our string array to a layout view—we pass createFromResource our Context, - the array of selectable items and the type of layout we'd like each one bound to. We then call - setDropDownViewResource() to define the type of layout in which to present the - entire collection. Finally, we set this Adapter to associate with our Spinner, - so the string items have a place to go.

      -
    10. - -
    11. Now run it.
    12. -
    -

    It should look like this:

    - - - -

    Resources

    -
      -
    • {@link android.R.layout}
    • -
    • {@link android.widget.ArrayAdapter}
    • -
    • {@link android.widget.Spinner}
    • -
    - diff --git a/docs/html/guide/tutorials/views/hello-tablelayout.jd b/docs/html/guide/tutorials/views/hello-tablelayout.jd deleted file mode 100644 index 83d6f5d46be5..000000000000 --- a/docs/html/guide/tutorials/views/hello-tablelayout.jd +++ /dev/null @@ -1,118 +0,0 @@ -page.title=Hello, TableLayout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.TableLayout} is a ViewGroup that -will lay child View elements into rows and columns.

    - - -
      -
    1. Start a new project/Activity called HelloTableLayout.
    2. -
    3. Open the layout file. - Make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent"
      -    android:stretchColumns="1">
      -
      -    <TableRow>
      -        <TextView
      -            android:layout_column="1"
      -            android:text="Open..."
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="Ctrl-O"
      -            android:gravity="right"
      -            android:padding="3dip" />
      -    </TableRow>
      -
      -    <TableRow>
      -        <TextView
      -            android:layout_column="1"
      -            android:text="Save..."
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="Ctrl-S"
      -            android:gravity="right"
      -            android:padding="3dip" />
      -    </TableRow>
      -
      -    <TableRow>
      -        <TextView
      -            android:layout_column="1"
      -            android:text="Save As..."
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="Ctrl-Shift-S"
      -            android:gravity="right"
      -            android:padding="3dip" />
      -    </TableRow>
      -
      -    <View
      -        android:layout_height="2dip"
      -        android:background="#FF909090" />
      -
      -    <TableRow>
      -        <TextView
      -            android:text="X"
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="Import..."
      -            android:padding="3dip" />
      -    </TableRow>
      -
      -    <TableRow>
      -        <TextView
      -            android:text="X"
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="Export..."
      -            android:padding="3dip" />
      -        <TextView
      -            android:text="Ctrl-E"
      -            android:gravity="right"
      -            android:padding="3dip" />
      -    </TableRow>
      -
      -    <View
      -        android:layout_height="2dip"
      -        android:background="#FF909090" />
      -
      -    <TableRow>
      -        <TextView
      -            android:layout_column="1"
      -            android:text="Quit"
      -            android:padding="3dip" />
      -    </TableRow>
      -</TableLayout>
      -
      -

      Notice how this resembles the structure of an HTML table. TableLayout is like the -table element; TableRow is like a tr element; but for our cells like -the html td element, we can use any kind of View. Here, we use TextView for the cells.

      - -
    4. -
    5. Make sure your Activity loads this layout in the onCreate() method: -
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -}
      -
      -

      R.layout.main refers to the main.xml layout file.

      -
    6. -
    7. Run it.
    8. -
    -

    You should see the following:

    - - -

    References

    -
      -
    • {@link android.widget.TableLayout}
    • -
    • {@link android.widget.TableRow}
    • -
    • {@link android.widget.TextView}
    • -
    - - diff --git a/docs/html/guide/tutorials/views/hello-tabwidget.jd b/docs/html/guide/tutorials/views/hello-tabwidget.jd deleted file mode 100644 index 98dddf539049..000000000000 --- a/docs/html/guide/tutorials/views/hello-tabwidget.jd +++ /dev/null @@ -1,124 +0,0 @@ -page.title=Hello, TabWidget -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.TabWidget} offers the ability to easily draw an interface that uses -tabs to navigate between different views.

    - -
      -
    1. Start a new project/Activity called HelloTabWidget.
    2. -
    3. Open the layout file and make it like so:
    4. -
      -<?xml version="1.0" encoding="utf-8"?>
      -<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:id="@android:id/tabhost"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent">
      -    <LinearLayout
      -        android:orientation="vertical"
      -        android:layout_width="fill_parent"
      -        android:layout_height="fill_parent">
      -        <TabWidget
      -            android:id="@android:id/tabs"
      -            android:layout_width="fill_parent"
      -            android:layout_height="wrap_content" />
      -        <FrameLayout
      -            android:id="@android:id/tabcontent"
      -            android:layout_width="fill_parent"
      -            android:layout_height="fill_parent">
      -            <TextView 
      -                android:id="@+id/textview1"
      -                android:layout_width="fill_parent"
      -                android:layout_height="fill_parent" 
      -                android:text="this is a tab" />
      -            <TextView 
      -                android:id="@+id/textview2"
      -                android:layout_width="fill_parent"
      -                android:layout_height="fill_parent" 
      -                android:text="this is another tab" />
      -            <TextView 
      -                android:id="@+id/textview3"
      -                android:layout_width="fill_parent"
      -                android:layout_height="fill_parent" 
      -                android:text="this is a third tab" />
      -    	</FrameLayout>
      -    </LinearLayout>
      -</TabHost>
      -
      -

      Here, we've created a {@link android.widget.TabHost} that contains the entire layout of the Activity. - A TabHost requires two descendant elements: a {@link android.widget.TabWidget} and a {@link android.widget.FrameLayout}. - In order to properly layout these elements, we've put them inside a vertical {@link android.widget.LinearLayout}. - The FrameLayout is where we keep the content that will change with each tab. Each child in the FrameLayout will - be associated with a different tab. - In this case, each tab simply shows a different {@link android.widget.TextView} with some text.

      -

      Notice that the TabWidget and the FrameLayout elements have specific android namespace IDs. These are necessary - so that the TabHost can automatically retrieve references to them, populate the TabWidget with the tabs that we'll define - in our code, and swap the views in the FrameLayout. We've also defined our own IDs for each TextView, which we'll use to - associate each tab with the view that it should reveal.

      -

      Of course, you can - make these child views as large as complex as you'd like — instead of the TextView elements, - you could start with other layout views and build a unique layout hierarchy for each tab.

      - -
    5. Now we'll add our code. Open HelloTabWidget.java and make it a TabActivity. -

      By default, Eclipse creates a class that extends Activity. Change it to - extend TabActivity:

      -
      -public class HelloTabWidget extends TabActivity {
      -
      -
    6. -
    7. Now fill in the the onCreate method like this: -
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -
      -    mTabHost = getTabHost();
      -    
      -    mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(R.id.textview1));
      -    mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(R.id.textview2));
      -    mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(R.id.textview3));
      -    
      -    mTabHost.setCurrentTab(0);
      -}
      -
      -

      As usual, we start by setting our layout.

      -

      We then call the TabActivity method getTabHost(), - which returns us a reference to the TabHost we created in our layout. Upon our TabHost, we call addTab() - for each of the tabs that we want to add to the TabWidget. Each time we call this, we pass a - {@link android.widget.TabHost.TabSpec} that we build on the fly, and with it, chain together two necessary methods: - setIndicator() to set the text for the tab button, and setContent() to define - which View we want to associate with the tab and reveal when pressed. Our indicator is just a text string and - our content is an ID reference to the TextView elements we inserted in the FrameLayout.

      -

      At the end, we call setCurrentTab() to define which tab should be opened by default. The tabs - are saved like a zero-based array, so to open the first tab, we pass zero (0).

      -
    8. -
    9. To clean-up the presentation a bit more, let's remove the window title that appears at the top of the layout. - Android includes a theme that removes that title for us. To add it, open the Android Manifest file and add - the NoTitleBar theme to the <application> tag. It should end up like this: -
      -<application android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar">
      -
      -
    10. -
    11. That's it. Run your application.
    12. - -
    - - -

    Your application should look like this:

    - - -

    You can include icons in your tabs by passing a -{@link android.graphics.drawable.Drawable} when you call setIndicator(). Here's an example -that uses a Drawable created from an image in the project resources:

    -
    setIndicator("TAB 1", getResources().getDrawable(R.drawable.tab_icon))
    -
    - -

    References

    -
      -
    • {@link android.widget.TabWidget}
    • -
    • {@link android.widget.TabHost}
    • -
    • {@link android.widget.TabHost.TabSpec}
    • -
    • {@link android.widget.FrameLayout}
    • -
    - diff --git a/docs/html/guide/tutorials/views/hello-timepicker.jd b/docs/html/guide/tutorials/views/hello-timepicker.jd deleted file mode 100644 index 1a6c8f9eeb29..000000000000 --- a/docs/html/guide/tutorials/views/hello-timepicker.jd +++ /dev/null @@ -1,159 +0,0 @@ -page.title=Hello, TimePicker -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.widget.TimePicker} is a widget that allows the -user to select the time by hour, minute and AM or PM.

    - - -
      -
    1. Start a new project/Activity called HelloTimePicker.
    2. -
    3. Open the layout file and make it like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:layout_width="wrap_content"
      -    android:layout_height="wrap_content"
      -    android:orientation="vertical">
      -
      -    <TextView android:id="@+id/timeDisplay"
      -        android:layout_width="wrap_content"
      -        android:layout_height="wrap_content"
      -        android:text=""/>
      -
      -    <Button android:id="@+id/pickTime"
      -        android:layout_width="wrap_content"
      -        android:layout_height="wrap_content"
      -        android:text="Change the time"/>
      -
      -</LinearLayout>
      -
      -

      For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that - will display the time and a {@link android.widget.Button} that will initiate the - {@link android.widget.TimePicker} dialog. - With this layout, the TextView will sit above the Button. - The text value in the TextView is set empty, as it will be filled by our Activity - with the current time.

      -
    4. - -
    5. Open HelloTimePicker.java. Insert the following to the HelloTimePicker class: -
      -private TextView mTimeDisplay;
      -private Button mPickTime;
      -
      -private int mHour;
      -private int mMinute;
      -
      -static final int TIME_DIALOG_ID = 0;
      -
      -@Override
      -protected void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -    
      -    // capture our View elements
      -    mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
      -    mPickTime = (Button) findViewById(R.id.pickTime);
      -
      -    // add a click listener to the button
      -    mPickTime.setOnClickListener(new View.OnClickListener() {
      -        public void onClick(View v) {
      -            showDialog(TIME_DIALOG_ID);
      -        }
      -    });
      -
      -    // get the current time
      -    final Calendar c = Calendar.getInstance();
      -    mHour = c.get(Calendar.HOUR_OF_DAY);
      -    mMinute = c.get(Calendar.MINUTE);
      -
      -    // display the current date
      -    updateDisplay();
      -}
      -
      -

      Tip: Press Ctrl(or Cmd) + Shift + O to import all needed packages.

      -

      We start by instantiating variables for our View elements and time fields. - The TIME_DIALOG_ID is a static integer that uniquely identifies the dialog. In the - onCreate() method, we get prepared by setting the layout and capturing the View elements. - We then set an on-click listener for the Button, so that when it is clicked, it will - show our TimePicker dialog. The showDialog() method will perform a callback - to our Activity. (We'll define this callback in the next section.) We then create an - instance of {@link java.util.Calendar} and get the current hour and minute. Finally, we call - updateDisplay()—our own method that will fill the TextView with the time.

      -
    6. - -
    7. After the onCreate() method, add the onCreateDialog() callback method: -
      -@Override
      -protected Dialog onCreateDialog(int id) {
      -    switch (id) {
      -    case TIME_DIALOG_ID:
      -        return new TimePickerDialog(this,
      -                mTimeSetListener, mHour, mMinute, false);
      -    }
      -    return null;
      -}
      -
      -

      This is passed the identifier we gave showDialog() and initializes - the TimePicker to the time we retrieved from our Calendar instance. It will be called by - showDialog().

      -
    8. - -
    9. Now add our updateDisplay() method: -
      -// updates the time we display in the TextView
      -private void updateDisplay() {
      -    mTimeDisplay.setText(
      -        new StringBuilder()
      -                .append(pad(mHour)).append(":")
      -                .append(pad(mMinute)));
      -}
      -
      -

      This simply takes our member fields for the time and inserts them in - the mTimeDisplay TextView. Note that we call a new method, pad(), - on the hour and minute. (We'll create this method in the last step.)

      -
    10. - -
    11. Next, add a listener to be called when the time is reset: -
      -// the callback received when the user "sets" the time in the dialog
      -private TimePickerDialog.OnTimeSetListener mTimeSetListener =
      -    new TimePickerDialog.OnTimeSetListener() {
      -        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
      -            mHour = hourOfDay;
      -            mMinute = minute;
      -            updateDisplay();
      -        }
      -    };
      -
      -

      Now when the user is done setting the time (clicks the "Set" button), we update our member fields with - the new time and update our TextView.

      -
    12. -
    13. Finally, add the pad() method that we called from the updateDisplay(): -
      -private static String pad(int c) {
      -    if (c >= 10)
      -        return String.valueOf(c);
      -    else
      -        return "0" + String.valueOf(c);
      -}
      -
      -

      This method returns the appropriate String representation of the hour or minute. - It will prefix a zero to the number if it's a single digit. -

      -
    14. - -
    15. Now run it.
    16. -
    -

    When you press the "Change the time" button, you should see the following:

    - - -

    References

    -
      -
    1. {@link android.widget.TimePicker}
    2. -
    3. {@link android.widget.Button}
    4. -
    5. {@link android.widget.TextView}
    6. -
    7. {@link java.util.Calendar}
    8. -
    - diff --git a/docs/html/guide/tutorials/views/hello-webview.jd b/docs/html/guide/tutorials/views/hello-webview.jd deleted file mode 100644 index a927b0497dde..000000000000 --- a/docs/html/guide/tutorials/views/hello-webview.jd +++ /dev/null @@ -1,118 +0,0 @@ -page.title=Hello, WebView -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

    A {@link android.webkit.WebView} allows you to create your own web browser Activity. In this tutorial, -we'll create a simple Activity that can view web pages.

    - -
      -
    1. Create a new project/Activity called HelloWebView.
    2. -
    3. Open the layout file. Insert a WebView so it looks like so: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent"
      -    android:orientation="vertical">
      -
      -    <WebView 
      -        android:id="@+id/webview"
      -        android:layout_width="fill_parent"
      -        android:layout_height="fill_parent"
      -    />
      -
      -</LinearLayout>
      -
    4. - -
    5. Now open the HelloWebView.java file. - At the top of the class, instantiate a WebView object: -
      WebView webview;
      -

      Then add the following at the end of the onCreate() method:

      -
      -webview = (WebView) findViewById(R.id.webview);
      -webview.getSettings().setJavaScriptEnabled(true);
      -webview.loadUrl("http://www.google.com");
      -
      - -

      This captures the WebView we created in our layout, then requests a - {@link android.webkit.WebSettings} object and enables JavaScript. - Then we load a URL.

    6. - -
    7. Because we're accessing the internet, we need to add the appropriate - permissions to the Android manifest file. So open the AndroidManifest.xml file - and, add the following as a child of the <manifest> element: - -
      <uses-permission android:name="android.permission.INTERNET" />
    8. - -
    9. Now run it.
    10. -
    -

    You now have the world's simplest web page viewer. - It's not quite a browser yet. It only loads the page we've requested.

    - -
    - -

    We can load a page, but as soon as we click a link, the default Android web browser -handles the Intent, instead of our own WebView handling the action. So now we'll -override the {@link android.webkit.WebViewClient} to enable us to handle our own URL loading.

    - -
      -
    1. In the HelloAndroid Activity, add this nested private class: -
      -private class HelloWebViewClient extends WebViewClient {
      -    @Override
      -    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      -        view.loadUrl(url);
      -        return true;
      -    }
      -}
    2. - -
    3. Now, in the onCreate() method, set an instance of the HelloWebViewClient - as our WebViewClient: -
      webview.setWebViewClient(new HelloWebViewClient());
      - -

      This line should immediately follow the initialization of our WebView object.

      -

      What we've done is create a WebViewClient that will load any URL selected in our -WebView in the same WebView. You can see this in the shouldOverrideUrlLoading() -method, above—it is passed the current WebView and the URL, so all we do -is load the URL in the given view. Returning true says that we've handled the URL -ourselves and the event should not bubble-up.

      -

      If you try it again, new pages will now load in the HelloWebView Activity. However, you'll notice that -we can't navigate back. We need to handle the back button -on the device, so that it will return to the previous page, rather than exit the application.

      -
    4. - -
    5. To handle the back button key press, add the following method inside the HelloWebView -Activity: -
       
      -@Override
      -public boolean onKeyDown(int keyCode, KeyEvent event) {
      -    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
      -        webview.goBack();
      -        return true;
      -    }
      -    return super.onKeyDown(keyCode, event);
      -}
      -

      The condition uses a {@link android.view.KeyEvent} to check - whether the key pressed is the BACK button and whether the - WebView is actually capable of navigating back (if it has a history). If both are - not true, then we send the event up the chain (and the Activity will close). - But if both are true, then we call goBack(), - which will navigate back one step in the history. We then return true to indicate - that we've handled the event.

      -
    6. -
    -

    When you open the application, it should look like this:

    - - -

    Resource

    -
      -
    • {@link android.webkit.WebView}
    • -
    • {@link android.webkit.WebViewClient}
    • -
    • {@link android.view.KeyEvent}
    • -
    - - - - - diff --git a/docs/html/guide/tutorials/views/images/android.png b/docs/html/guide/tutorials/views/images/android.png deleted file mode 100755 index 39a1ac729394..000000000000 Binary files a/docs/html/guide/tutorials/views/images/android.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/androidmarker.png b/docs/html/guide/tutorials/views/images/androidmarker.png deleted file mode 100755 index 8c43d4668218..000000000000 Binary files a/docs/html/guide/tutorials/views/images/androidmarker.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-autocomplete.png b/docs/html/guide/tutorials/views/images/hello-autocomplete.png deleted file mode 100755 index e1fd80dfbf8b..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-autocomplete.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-datepicker.png b/docs/html/guide/tutorials/views/images/hello-datepicker.png deleted file mode 100755 index 2075066bfdc1..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-datepicker.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-formstuff.png b/docs/html/guide/tutorials/views/images/hello-formstuff.png deleted file mode 100755 index 3b4bf54d10dd..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-formstuff.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-gallery.png b/docs/html/guide/tutorials/views/images/hello-gallery.png deleted file mode 100755 index 22d1eaf6d145..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-gallery.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-gridview.png b/docs/html/guide/tutorials/views/images/hello-gridview.png deleted file mode 100755 index 2def0df666a4..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-gridview.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-linearlayout.png b/docs/html/guide/tutorials/views/images/hello-linearlayout.png deleted file mode 100755 index dfef819ef9d1..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-linearlayout.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-listview.png b/docs/html/guide/tutorials/views/images/hello-listview.png deleted file mode 100755 index a1cf7aa6e90b..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-listview.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-mapview.png b/docs/html/guide/tutorials/views/images/hello-mapview.png deleted file mode 100755 index 0956760a39c3..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-mapview.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-relativelayout.png b/docs/html/guide/tutorials/views/images/hello-relativelayout.png deleted file mode 100755 index ec4d9d44b0c6..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-relativelayout.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-spinner.png b/docs/html/guide/tutorials/views/images/hello-spinner.png deleted file mode 100755 index 42e2a915cb47..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-spinner.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-tablelayout.png b/docs/html/guide/tutorials/views/images/hello-tablelayout.png deleted file mode 100755 index 3d80e7f8a55a..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-tablelayout.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-tabwidget.png b/docs/html/guide/tutorials/views/images/hello-tabwidget.png deleted file mode 100644 index 6a52356c8f99..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-tabwidget.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-timepicker.png b/docs/html/guide/tutorials/views/images/hello-timepicker.png deleted file mode 100755 index bd5a1eeadaae..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-timepicker.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/images/hello-webview.png b/docs/html/guide/tutorials/views/images/hello-webview.png deleted file mode 100755 index 283ce7d0f4d6..000000000000 Binary files a/docs/html/guide/tutorials/views/images/hello-webview.png and /dev/null differ diff --git a/docs/html/guide/tutorials/views/index.html b/docs/html/guide/tutorials/views/index.html deleted file mode 100644 index 41d67965e59b..000000000000 --- a/docs/html/guide/tutorials/views/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should have been redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/guide/webapps/debugging.jd b/docs/html/guide/webapps/debugging.jd index c0dce48813c0..1eef1ae1c839 100644 --- a/docs/html/guide/webapps/debugging.jd +++ b/docs/html/guide/webapps/debugging.jd @@ -18,7 +18,7 @@ messages

    See also

      -
    1. Debugging
    2. +
    3. Debugging
    @@ -43,10 +43,10 @@ the device throws an error, as well as log messages written from your applicatio those written using JavaScript {@code console} APIs.

    To run logcat and view messages, execute {@code adb logcat} from your Android SDK {@code tools/} directory, or, from DDMS, select -Device > Run logcat. When using the ADT +Device > Run logcat. When using the ADT plugin for Eclipse, you can also view logcat messages by opening the Logcat view, available from Window > Show View > Other > Android > Logcat.

    -

    See Debugging +

    See Debugging for more information about .

    diff --git a/docs/html/guide/webapps/index.jd b/docs/html/guide/webapps/index.jd index 069290ae9352..df7ddbe7b102 100644 --- a/docs/html/guide/webapps/index.jd +++ b/docs/html/guide/webapps/index.jd @@ -1,71 +1,16 @@ -page.title=Web Apps Overview -@jd:body - -
    - -

    Figure 1. You can make your web content available to -users in two ways: in a traditional web browser and in an Android application, by -including a WebView in the layout.

    -
    - -

    There are essentially two ways to deliver an application on Android: as a -client-side application (developed using the Android SDK and installed on user devices as an {@code -.apk}) or as a web application (developed using web standards and accessed through a web -browser—there's nothing to install on user devices).

    +page.title=Web Apps +page.landing=true +page.landing.intro=Android has always been about connectivity and providing a great web browsing experience, so building your app with web technologies can be a great opportunity. Not only can you build an app on the web and still optimize your designs for Android's various screen sizes and densities, but you can also embed web-based content into your Android app using WebView. +page.landing.image= -

    The approach you choose for your application could depend on several factors, but Android makes -the decision to develop a web application easier by providing:

    -
      -
    • Support for viewport properties that allow you to properly size your web application -based on the screen size
    • -
    • CSS and JavaScript features that allow you to provide different styles and images -based on the screen's pixel density (screen resolution)
    • -
    - -

    Thus, your decision to develop a web application for Android can exclude consideration for -screen support, because it's already easy to make your web pages look good on all types of screens -powered by Android.

    - -

    Another great feature of Android is that you don't have to build your application purely on -the client or purely on the web. You can mix the two together by developing a client-side Android -application that embeds some web pages (using a {@link android.webkit.WebView} in your Android -application layout). Figure 1 visualizes how you can provide access to your web pages from either -a web browser or your Android application. However, you shouldn't develop an Android -application simply as a means to launch your web site. Rather, the web pages you embed in your -Android application should be designed especially for that environment. You can even define an -interface between your Android application and your web pages that allows JavaScript in the web -pages to call upon APIs in your Android application—providing Android APIs to your web-based -application.

    +@jd:body -

    Since Android 1.0, {@link android.webkit.WebView} has been available for Android -applications to embed web content in their layout and bind JavaScript to Android APIs. After -Android added support for more screen densities (adding support for high and low-density -screens), Android 2.0 added features to the WebKit framework to allow web pages to specify -viewport properties and query the screen density in order to modify styles -and image assets, as mentioned above. Because these features are a part of Android's WebKit -framework, both the Android Browser (the default web browser provided with the platform) and -{@link android.webkit.WebView} support the same viewport and screen density features.

    +
    -

    To develop a web application for Android-powered devices, you should read the -following documents:

    +
    +
    -
    -
    Targeting Screens from Web -Apps
    -
    How to properly size your web app on Android-powered devices and support -multiple screen densities. The information in this document is important if you're building a web -application that you at least expect to be available on Android-powered devices (which you should -assume for anything you publish on the web), but especially if you're targeting mobile devices -or using {@link android.webkit.WebView}.
    -
    Building Web Apps in -WebView
    -
    How to embed web pages into your Android application using {@link android.webkit.WebView} and -bind JavaScript to Android APIs.
    -
    Debugging Web Apps
    -
    How to debug web apps using JavaScript Console APIs.
    -
    Best Practices for Web -Apps
    -
    A list of practices you should follow, in order to provide an effective web application on -Android-powered devices.
    -
    +
    +
    +
    \ No newline at end of file diff --git a/docs/html/guide/webapps/overview.jd b/docs/html/guide/webapps/overview.jd new file mode 100644 index 000000000000..069290ae9352 --- /dev/null +++ b/docs/html/guide/webapps/overview.jd @@ -0,0 +1,71 @@ +page.title=Web Apps Overview +@jd:body + +
    + +

    Figure 1. You can make your web content available to +users in two ways: in a traditional web browser and in an Android application, by +including a WebView in the layout.

    +
    + +

    There are essentially two ways to deliver an application on Android: as a +client-side application (developed using the Android SDK and installed on user devices as an {@code +.apk}) or as a web application (developed using web standards and accessed through a web +browser—there's nothing to install on user devices).

    + +

    The approach you choose for your application could depend on several factors, but Android makes +the decision to develop a web application easier by providing:

    +
      +
    • Support for viewport properties that allow you to properly size your web application +based on the screen size
    • +
    • CSS and JavaScript features that allow you to provide different styles and images +based on the screen's pixel density (screen resolution)
    • +
    + +

    Thus, your decision to develop a web application for Android can exclude consideration for +screen support, because it's already easy to make your web pages look good on all types of screens +powered by Android.

    + +

    Another great feature of Android is that you don't have to build your application purely on +the client or purely on the web. You can mix the two together by developing a client-side Android +application that embeds some web pages (using a {@link android.webkit.WebView} in your Android +application layout). Figure 1 visualizes how you can provide access to your web pages from either +a web browser or your Android application. However, you shouldn't develop an Android +application simply as a means to launch your web site. Rather, the web pages you embed in your +Android application should be designed especially for that environment. You can even define an +interface between your Android application and your web pages that allows JavaScript in the web +pages to call upon APIs in your Android application—providing Android APIs to your web-based +application.

    + +

    Since Android 1.0, {@link android.webkit.WebView} has been available for Android +applications to embed web content in their layout and bind JavaScript to Android APIs. After +Android added support for more screen densities (adding support for high and low-density +screens), Android 2.0 added features to the WebKit framework to allow web pages to specify +viewport properties and query the screen density in order to modify styles +and image assets, as mentioned above. Because these features are a part of Android's WebKit +framework, both the Android Browser (the default web browser provided with the platform) and +{@link android.webkit.WebView} support the same viewport and screen density features.

    + +

    To develop a web application for Android-powered devices, you should read the +following documents:

    + +
    +
    Targeting Screens from Web +Apps
    +
    How to properly size your web app on Android-powered devices and support +multiple screen densities. The information in this document is important if you're building a web +application that you at least expect to be available on Android-powered devices (which you should +assume for anything you publish on the web), but especially if you're targeting mobile devices +or using {@link android.webkit.WebView}.
    +
    Building Web Apps in +WebView
    +
    How to embed web pages into your Android application using {@link android.webkit.WebView} and +bind JavaScript to Android APIs.
    +
    Debugging Web Apps
    +
    How to debug web apps using JavaScript Console APIs.
    +
    Best Practices for Web +Apps
    +
    A list of practices you should follow, in order to provide an effective web application on +Android-powered devices.
    +
    + diff --git a/docs/html/images/about/growth-chart.png b/docs/html/images/about/growth-chart.png new file mode 100644 index 000000000000..fee4e0942545 Binary files /dev/null and b/docs/html/images/about/growth-chart.png differ diff --git a/docs/html/images/activity_fragment_lifecycle.png b/docs/html/images/activity_fragment_lifecycle.png index bab957960df1..c44777493cfa 100644 Binary files a/docs/html/images/activity_fragment_lifecycle.png and b/docs/html/images/activity_fragment_lifecycle.png differ diff --git a/docs/html/images/activity_lifecycle.png b/docs/html/images/activity_lifecycle.png index 357349c44254..879f51f6e8fa 100644 Binary files a/docs/html/images/activity_lifecycle.png and b/docs/html/images/activity_lifecycle.png differ diff --git a/docs/html/images/android-logo.png b/docs/html/images/android-logo.png new file mode 100644 index 000000000000..d72fed1b2b31 Binary files /dev/null and b/docs/html/images/android-logo.png differ diff --git a/docs/html/images/billing_subscription_flow.png b/docs/html/images/billing_subscription_flow.png new file mode 100644 index 000000000000..a293228bd7b9 Binary files /dev/null and b/docs/html/images/billing_subscription_flow.png differ diff --git a/docs/html/images/brand/android_app_on_play_logo_large.png b/docs/html/images/brand/android_app_on_play_logo_large.png new file mode 100644 index 000000000000..a46bf3538c4e Binary files /dev/null and b/docs/html/images/brand/android_app_on_play_logo_large.png differ diff --git a/docs/html/images/brand/android_app_on_play_logo_small.png b/docs/html/images/brand/android_app_on_play_logo_small.png new file mode 100644 index 000000000000..2d8ef525df08 Binary files /dev/null and b/docs/html/images/brand/android_app_on_play_logo_small.png differ diff --git a/docs/html/images/brand/droid.gif b/docs/html/images/brand/droid.gif new file mode 100644 index 000000000000..7c7b941218c9 Binary files /dev/null and b/docs/html/images/brand/droid.gif differ diff --git a/docs/html/images/brand/get_it_on_play_logo_large.png b/docs/html/images/brand/get_it_on_play_logo_large.png new file mode 100644 index 000000000000..8b48767fc561 Binary files /dev/null and b/docs/html/images/brand/get_it_on_play_logo_large.png differ diff --git a/docs/html/images/brand/get_it_on_play_logo_small.png b/docs/html/images/brand/get_it_on_play_logo_small.png new file mode 100644 index 000000000000..1fcbec86b925 Binary files /dev/null and b/docs/html/images/brand/get_it_on_play_logo_small.png differ diff --git a/docs/html/images/brand/google_play_logo_450.png b/docs/html/images/brand/google_play_logo_450.png new file mode 100644 index 000000000000..59a1fcfdad1d Binary files /dev/null and b/docs/html/images/brand/google_play_logo_450.png differ diff --git a/docs/html/images/brand/learnmore.gif b/docs/html/images/brand/learnmore.gif new file mode 100644 index 000000000000..70a8e6bc4579 Binary files /dev/null and b/docs/html/images/brand/learnmore.gif differ diff --git a/docs/html/images/brand/logo_android.gif b/docs/html/images/brand/logo_android.gif new file mode 100644 index 000000000000..169c764c0976 Binary files /dev/null and b/docs/html/images/brand/logo_android.gif differ diff --git a/docs/html/images/brand/mediaplayer.gif b/docs/html/images/brand/mediaplayer.gif new file mode 100644 index 000000000000..860d110866fa Binary files /dev/null and b/docs/html/images/brand/mediaplayer.gif differ diff --git a/docs/html/images/brand/norad.gif b/docs/html/images/brand/norad.gif new file mode 100644 index 000000000000..d8707bdd871a Binary files /dev/null and b/docs/html/images/brand/norad.gif differ diff --git a/docs/html/images/dac-design-icon.png b/docs/html/images/dac-design-icon.png new file mode 100644 index 000000000000..245f08011347 Binary files /dev/null and b/docs/html/images/dac-design-icon.png differ diff --git a/docs/html/images/debugging-tall.png b/docs/html/images/debugging-tall.png new file mode 100644 index 000000000000..d29c4d151148 Binary files /dev/null and b/docs/html/images/debugging-tall.png differ diff --git a/docs/html/images/develop-placeholder.png b/docs/html/images/develop-placeholder.png new file mode 100644 index 000000000000..35a8767892ac Binary files /dev/null and b/docs/html/images/develop-placeholder.png differ diff --git a/docs/html/images/develop/app_components.png b/docs/html/images/develop/app_components.png new file mode 100644 index 000000000000..0e3460d8046c Binary files /dev/null and b/docs/html/images/develop/app_components.png differ diff --git a/docs/html/images/develop/auth-code.png b/docs/html/images/develop/auth-code.png new file mode 100644 index 000000000000..6dfabf9cc35f Binary files /dev/null and b/docs/html/images/develop/auth-code.png differ diff --git a/docs/html/images/develop/connectivity.png b/docs/html/images/develop/connectivity.png new file mode 100644 index 000000000000..2c9dadb2d9e0 Binary files /dev/null and b/docs/html/images/develop/connectivity.png differ diff --git a/docs/html/images/develop/marquee-play.png b/docs/html/images/develop/marquee-play.png new file mode 100644 index 000000000000..de8802d349e2 Binary files /dev/null and b/docs/html/images/develop/marquee-play.png differ diff --git a/docs/html/images/develop/resources.png b/docs/html/images/develop/resources.png new file mode 100644 index 000000000000..f6cbf5d2bdde Binary files /dev/null and b/docs/html/images/develop/resources.png differ diff --git a/docs/html/images/distribute/feature-market.png b/docs/html/images/distribute/feature-market.png new file mode 100644 index 000000000000..e9d3abf1e6a8 Binary files /dev/null and b/docs/html/images/distribute/feature-market.png differ diff --git a/docs/html/images/distribute/feature-monetize.png b/docs/html/images/distribute/feature-monetize.png new file mode 100644 index 000000000000..4b1b5095cbf4 Binary files /dev/null and b/docs/html/images/distribute/feature-monetize.png differ diff --git a/docs/html/images/distribute/feature-register.png b/docs/html/images/distribute/feature-register.png new file mode 100644 index 000000000000..ad387bf2da2d Binary files /dev/null and b/docs/html/images/distribute/feature-register.png differ diff --git a/docs/html/images/distribute/marquee-play.png b/docs/html/images/distribute/marquee-play.png new file mode 100644 index 000000000000..1aa4823c6af7 Binary files /dev/null and b/docs/html/images/distribute/marquee-play.png differ diff --git a/docs/html/images/editorschoice_ann.png b/docs/html/images/editorschoice_ann.png new file mode 100644 index 000000000000..c4f2c06834c8 Binary files /dev/null and b/docs/html/images/editorschoice_ann.png differ diff --git a/docs/html/images/fragment_lifecycle.png b/docs/html/images/fragment_lifecycle.png index d207db42514f..fcaa63b646b0 100644 Binary files a/docs/html/images/fragment_lifecycle.png and b/docs/html/images/fragment_lifecycle.png differ diff --git a/docs/html/images/fundamentals/diagram_backstack.png b/docs/html/images/fundamentals/diagram_backstack.png index bdb689304741..5ddadcbe4f47 100644 Binary files a/docs/html/images/fundamentals/diagram_backstack.png and b/docs/html/images/fundamentals/diagram_backstack.png differ diff --git a/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png b/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png index aab324ddd5fd..b9e5ed48f697 100644 Binary files a/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png and b/docs/html/images/fundamentals/diagram_backstack_singletask_multiactivity.png differ diff --git a/docs/html/images/fundamentals/diagram_multiple_instances.png b/docs/html/images/fundamentals/diagram_multiple_instances.png index 64b476ff436e..606f540955c5 100644 Binary files a/docs/html/images/fundamentals/diagram_multiple_instances.png and b/docs/html/images/fundamentals/diagram_multiple_instances.png differ diff --git a/docs/html/images/fundamentals/diagram_multitasking.png b/docs/html/images/fundamentals/diagram_multitasking.png index e21959992bd6..ffe5c65151d8 100644 Binary files a/docs/html/images/fundamentals/diagram_multitasking.png and b/docs/html/images/fundamentals/diagram_multitasking.png differ diff --git a/docs/html/images/fundamentals/fragments.png b/docs/html/images/fundamentals/fragments.png index bf986b1abb30..cb7204b46227 100644 Binary files a/docs/html/images/fundamentals/fragments.png and b/docs/html/images/fundamentals/fragments.png differ diff --git a/docs/html/images/fundamentals/restore_instance.png b/docs/html/images/fundamentals/restore_instance.png index 57a95eca6f99..698b83a8149c 100644 Binary files a/docs/html/images/fundamentals/restore_instance.png and b/docs/html/images/fundamentals/restore_instance.png differ diff --git a/docs/html/images/fundamentals/service_binding_tree_lifecycle.png b/docs/html/images/fundamentals/service_binding_tree_lifecycle.png index 526521625b5a..8b826f677bab 100644 Binary files a/docs/html/images/fundamentals/service_binding_tree_lifecycle.png and b/docs/html/images/fundamentals/service_binding_tree_lifecycle.png differ diff --git a/docs/html/images/gp-apps-home.png b/docs/html/images/gp-apps-home.png new file mode 100644 index 000000000000..851f7227fb79 Binary files /dev/null and b/docs/html/images/gp-apps-home.png differ diff --git a/docs/html/images/gp-buyer-currency.png b/docs/html/images/gp-buyer-currency.png new file mode 100644 index 000000000000..51b810857194 Binary files /dev/null and b/docs/html/images/gp-buyer-currency.png differ diff --git a/docs/html/images/gp-collectibles.png b/docs/html/images/gp-collectibles.png new file mode 100644 index 000000000000..a63cd505114b Binary files /dev/null and b/docs/html/images/gp-collectibles.png differ diff --git a/docs/html/images/gp-dc-countries.png b/docs/html/images/gp-dc-countries.png new file mode 100644 index 000000000000..00d0d5e3ff74 Binary files /dev/null and b/docs/html/images/gp-dc-countries.png differ diff --git a/docs/html/images/gp-dc-details.png b/docs/html/images/gp-dc-details.png new file mode 100644 index 000000000000..567567e65503 Binary files /dev/null and b/docs/html/images/gp-dc-details.png differ diff --git a/docs/html/images/gp-dc-home.png b/docs/html/images/gp-dc-home.png new file mode 100644 index 000000000000..381d0db017c4 Binary files /dev/null and b/docs/html/images/gp-dc-home.png differ diff --git a/docs/html/images/gp-dc-profile.png b/docs/html/images/gp-dc-profile.png new file mode 100644 index 000000000000..e52636970d35 Binary files /dev/null and b/docs/html/images/gp-dc-profile.png differ diff --git a/docs/html/images/gp-dc-reviews.png b/docs/html/images/gp-dc-reviews.png new file mode 100644 index 000000000000..cab175a7d8d5 Binary files /dev/null and b/docs/html/images/gp-dc-reviews.png differ diff --git a/docs/html/images/gp-dc-stats-mini.png b/docs/html/images/gp-dc-stats-mini.png new file mode 100644 index 000000000000..d29a270bfd81 Binary files /dev/null and b/docs/html/images/gp-dc-stats-mini.png differ diff --git a/docs/html/images/gp-dc-stats.png b/docs/html/images/gp-dc-stats.png new file mode 100644 index 000000000000..06f88e56d0bf Binary files /dev/null and b/docs/html/images/gp-dc-stats.png differ diff --git a/docs/html/images/gp-details-pages-magicpiano.png b/docs/html/images/gp-details-pages-magicpiano.png new file mode 100644 index 000000000000..4bb196273d8c Binary files /dev/null and b/docs/html/images/gp-details-pages-magicpiano.png differ diff --git a/docs/html/images/gp-details-ww-purchase.png b/docs/html/images/gp-details-ww-purchase.png new file mode 100644 index 000000000000..46df4434f8ed Binary files /dev/null and b/docs/html/images/gp-details-ww-purchase.png differ diff --git a/docs/html/images/gp-details-ww.png b/docs/html/images/gp-details-ww.png new file mode 100644 index 000000000000..ccc522c79e71 Binary files /dev/null and b/docs/html/images/gp-details-ww.png differ diff --git a/docs/html/images/gp-devconsole-home.png b/docs/html/images/gp-devconsole-home.png new file mode 100644 index 000000000000..1d758fd97a88 Binary files /dev/null and b/docs/html/images/gp-devconsole-home.png differ diff --git a/docs/html/images/gp-device.png b/docs/html/images/gp-device.png new file mode 100644 index 000000000000..86e46e5da746 Binary files /dev/null and b/docs/html/images/gp-device.png differ diff --git a/docs/html/images/gp-games-home.png b/docs/html/images/gp-games-home.png new file mode 100644 index 000000000000..81b7f7a2897b Binary files /dev/null and b/docs/html/images/gp-games-home.png differ diff --git a/docs/html/images/gp-growth-downloads.png b/docs/html/images/gp-growth-downloads.png new file mode 100644 index 000000000000..4a4b194a0476 Binary files /dev/null and b/docs/html/images/gp-growth-downloads.png differ diff --git a/docs/html/images/gp-rating-web.png b/docs/html/images/gp-rating-web.png new file mode 100644 index 000000000000..0885826995dc Binary files /dev/null and b/docs/html/images/gp-rating-web.png differ diff --git a/docs/html/images/gp-sendto.png b/docs/html/images/gp-sendto.png new file mode 100644 index 000000000000..7409c140c05a Binary files /dev/null and b/docs/html/images/gp-sendto.png differ diff --git a/docs/html/images/gp-subs.png b/docs/html/images/gp-subs.png new file mode 100644 index 000000000000..9b3a7df3f1a1 Binary files /dev/null and b/docs/html/images/gp-subs.png differ diff --git a/docs/html/images/gp-supported-dev-requirements.png b/docs/html/images/gp-supported-dev-requirements.png new file mode 100644 index 000000000000..d84f34efe089 Binary files /dev/null and b/docs/html/images/gp-supported-dev-requirements.png differ diff --git a/docs/html/images/gp-tab.png b/docs/html/images/gp-tab.png new file mode 100644 index 000000000000..4673d21d7622 Binary files /dev/null and b/docs/html/images/gp-tab.png differ diff --git a/docs/html/images/gp-top-new-paid.png b/docs/html/images/gp-top-new-paid.png new file mode 100644 index 000000000000..d98d6cad4e67 Binary files /dev/null and b/docs/html/images/gp-top-new-paid.png differ diff --git a/docs/html/images/gpp-cat-feature280-photo.png b/docs/html/images/gpp-cat-feature280-photo.png new file mode 100644 index 000000000000..ae2749b88caf Binary files /dev/null and b/docs/html/images/gpp-cat-feature280-photo.png differ diff --git a/docs/html/images/gpp-cat-feature280-puzzle.png b/docs/html/images/gpp-cat-feature280-puzzle.png new file mode 100644 index 000000000000..db203c6f1e54 Binary files /dev/null and b/docs/html/images/gpp-cat-feature280-puzzle.png differ diff --git a/docs/html/images/gpp-cat-feature280-sports.png b/docs/html/images/gpp-cat-feature280-sports.png new file mode 100644 index 000000000000..dcd70aaf7a96 Binary files /dev/null and b/docs/html/images/gpp-cat-feature280-sports.png differ diff --git a/docs/html/images/home-marquee.jpg b/docs/html/images/home-marquee.jpg new file mode 100644 index 000000000000..94d83d738da0 Binary files /dev/null and b/docs/html/images/home-marquee.jpg differ diff --git a/docs/html/images/home/design.png b/docs/html/images/home/design.png new file mode 100644 index 000000000000..bbaa767b9aa8 Binary files /dev/null and b/docs/html/images/home/design.png differ diff --git a/docs/html/images/home/developers_live.png b/docs/html/images/home/developers_live.png new file mode 100644 index 000000000000..13dbb5c580e9 Binary files /dev/null and b/docs/html/images/home/developers_live.png differ diff --git a/docs/html/images/home/google-io.png b/docs/html/images/home/google-io.png new file mode 100644 index 000000000000..d21a24da46bd Binary files /dev/null and b/docs/html/images/home/google-io.png differ diff --git a/docs/html/images/home/google-play.png b/docs/html/images/home/google-play.png new file mode 100644 index 000000000000..20321542fe40 Binary files /dev/null and b/docs/html/images/home/google-play.png differ diff --git a/docs/html/images/home/ics-android.png b/docs/html/images/home/ics-android.png new file mode 100644 index 000000000000..f4c3b5bee165 Binary files /dev/null and b/docs/html/images/home/ics-android.png differ diff --git a/docs/html/images/layoutparams.png b/docs/html/images/layoutparams.png index d99625e2efa9..ac31e44a65f0 100644 Binary files a/docs/html/images/layoutparams.png and b/docs/html/images/layoutparams.png differ diff --git a/docs/html/images/market/version-codes.png b/docs/html/images/market/version-codes.png index c0c985864fa9..aa4fd4193ef3 100644 Binary files a/docs/html/images/market/version-codes.png and b/docs/html/images/market/version-codes.png differ diff --git a/docs/html/images/opengl/ccw-square.png b/docs/html/images/opengl/ccw-square.png new file mode 100644 index 000000000000..010def9537bd Binary files /dev/null and b/docs/html/images/opengl/ccw-square.png differ diff --git a/docs/html/images/opengl/ccw-winding.png b/docs/html/images/opengl/ccw-winding.png new file mode 100644 index 000000000000..a7ece315a146 Binary files /dev/null and b/docs/html/images/opengl/ccw-winding.png differ diff --git a/docs/html/images/opengl/coordinates.png b/docs/html/images/opengl/coordinates.png index 7180cd5cecf3..7a02cdd5b82c 100644 Binary files a/docs/html/images/opengl/coordinates.png and b/docs/html/images/opengl/coordinates.png differ diff --git a/docs/html/images/opengl/helloopengl-es10-1.png b/docs/html/images/opengl/helloopengl-es10-1.png deleted file mode 100644 index 9aa2376ed720..000000000000 Binary files a/docs/html/images/opengl/helloopengl-es10-1.png and /dev/null differ diff --git a/docs/html/images/opengl/helloopengl-es10-2.png b/docs/html/images/opengl/helloopengl-es10-2.png deleted file mode 100644 index cdfd9c70539a..000000000000 Binary files a/docs/html/images/opengl/helloopengl-es10-2.png and /dev/null differ diff --git a/docs/html/images/opengl/helloopengl-es20-1.png b/docs/html/images/opengl/helloopengl-es20-1.png deleted file mode 100644 index 1f76c22cb23b..000000000000 Binary files a/docs/html/images/opengl/helloopengl-es20-1.png and /dev/null differ diff --git a/docs/html/images/opengl/helloopengl-es20-2.png b/docs/html/images/opengl/helloopengl-es20-2.png deleted file mode 100644 index 0fbbe60010e3..000000000000 Binary files a/docs/html/images/opengl/helloopengl-es20-2.png and /dev/null differ diff --git a/docs/html/images/opengl/ogl-triangle-projected.png b/docs/html/images/opengl/ogl-triangle-projected.png new file mode 100644 index 000000000000..d10bbdc0d27f Binary files /dev/null and b/docs/html/images/opengl/ogl-triangle-projected.png differ diff --git a/docs/html/images/opengl/ogl-triangle-touch.png b/docs/html/images/opengl/ogl-triangle-touch.png new file mode 100644 index 000000000000..35177a4670b0 Binary files /dev/null and b/docs/html/images/opengl/ogl-triangle-touch.png differ diff --git a/docs/html/images/opengl/ogl-triangle.png b/docs/html/images/opengl/ogl-triangle.png new file mode 100644 index 000000000000..3d4a385f198a Binary files /dev/null and b/docs/html/images/opengl/ogl-triangle.png differ diff --git a/docs/html/images/play_tableft.png b/docs/html/images/play_tableft.png new file mode 100644 index 000000000000..14740cb4347d Binary files /dev/null and b/docs/html/images/play_tableft.png differ diff --git a/docs/html/images/providers/ContactsDataFlow.png b/docs/html/images/providers/ContactsDataFlow.png new file mode 100644 index 000000000000..403afc77441e Binary files /dev/null and b/docs/html/images/providers/ContactsDataFlow.png differ diff --git a/docs/html/images/providers/contacts_structure.png b/docs/html/images/providers/contacts_structure.png new file mode 100644 index 000000000000..3cdc5de5a15f Binary files /dev/null and b/docs/html/images/providers/contacts_structure.png differ diff --git a/docs/html/images/providers/contacts_tables.png b/docs/html/images/providers/contacts_tables.png new file mode 100644 index 000000000000..c44994830a9c Binary files /dev/null and b/docs/html/images/providers/contacts_tables.png differ diff --git a/docs/html/images/providers/data_columns.png b/docs/html/images/providers/data_columns.png new file mode 100644 index 000000000000..6e9d90e669c7 Binary files /dev/null and b/docs/html/images/providers/data_columns.png differ diff --git a/docs/html/images/publishing/publishing_unknown_sources.png b/docs/html/images/publishing/publishing_unknown_sources.png deleted file mode 100755 index ad310a1810dc..000000000000 Binary files a/docs/html/images/publishing/publishing_unknown_sources.png and /dev/null differ diff --git a/docs/html/images/publishing/publishing_unknown_sources_sm.png b/docs/html/images/publishing/publishing_unknown_sources_sm.png new file mode 100644 index 000000000000..34cba2a7f858 Binary files /dev/null and b/docs/html/images/publishing/publishing_unknown_sources_sm.png differ diff --git a/docs/html/images/publishing/publishing_via_email.png b/docs/html/images/publishing/publishing_via_email.png index 54c64bd6e809..d367747230b4 100755 Binary files a/docs/html/images/publishing/publishing_via_email.png and b/docs/html/images/publishing/publishing_via_email.png differ diff --git a/docs/html/images/resources/res-selection-flowchart.png b/docs/html/images/resources/res-selection-flowchart.png index 5de7688a2532..149f4dcadda2 100644 Binary files a/docs/html/images/resources/res-selection-flowchart.png and b/docs/html/images/resources/res-selection-flowchart.png differ diff --git a/docs/html/images/resources/resource_devices_diagram1.png b/docs/html/images/resources/resource_devices_diagram1.png index 0b3c856ff859..e2f515fdb570 100644 Binary files a/docs/html/images/resources/resource_devices_diagram1.png and b/docs/html/images/resources/resource_devices_diagram1.png differ diff --git a/docs/html/images/resources/resource_devices_diagram2.png b/docs/html/images/resources/resource_devices_diagram2.png index d32a7811f64c..f0a3886bf30f 100644 Binary files a/docs/html/images/resources/resource_devices_diagram2.png and b/docs/html/images/resources/resource_devices_diagram2.png differ diff --git a/docs/html/images/robot-sdk.png b/docs/html/images/robot-sdk.png new file mode 100644 index 000000000000..962d4d512436 Binary files /dev/null and b/docs/html/images/robot-sdk.png differ diff --git a/docs/html/images/robot-tiny.png b/docs/html/images/robot-tiny.png new file mode 100644 index 000000000000..f925062b3fb6 Binary files /dev/null and b/docs/html/images/robot-tiny.png differ diff --git a/docs/html/images/screens_support/screens-densities.png b/docs/html/images/screens_support/screens-densities.png index edbd1e32572a..3220ecf5f687 100644 Binary files a/docs/html/images/screens_support/screens-densities.png and b/docs/html/images/screens_support/screens-densities.png differ diff --git a/docs/html/images/screens_support/screens-ranges.png b/docs/html/images/screens_support/screens-ranges.png index d8a0ffae549f..c6a06771a554 100644 Binary files a/docs/html/images/screens_support/screens-ranges.png and b/docs/html/images/screens_support/screens-ranges.png differ diff --git a/docs/html/images/sdk-cube.png b/docs/html/images/sdk-cube.png new file mode 100644 index 000000000000..58b43aec28c9 Binary files /dev/null and b/docs/html/images/sdk-cube.png differ diff --git a/docs/html/images/service_lifecycle.png b/docs/html/images/service_lifecycle.png index 7ab96d7c733a..413bf5627f42 100644 Binary files a/docs/html/images/service_lifecycle.png and b/docs/html/images/service_lifecycle.png differ diff --git a/docs/html/images/tools-home.png b/docs/html/images/tools-home.png new file mode 100644 index 000000000000..291a36138a4e Binary files /dev/null and b/docs/html/images/tools-home.png differ diff --git a/docs/html/images/topdev_ann.png b/docs/html/images/topdev_ann.png new file mode 100644 index 000000000000..9564387e8d8b Binary files /dev/null and b/docs/html/images/topdev_ann.png differ diff --git a/docs/html/images/training/basics/basic-lifecycle-create.png b/docs/html/images/training/basics/basic-lifecycle-create.png index 01d7328da8a4..d6c66fc0fcc6 100644 Binary files a/docs/html/images/training/basics/basic-lifecycle-create.png and b/docs/html/images/training/basics/basic-lifecycle-create.png differ diff --git a/docs/html/images/training/basics/basic-lifecycle-paused.png b/docs/html/images/training/basics/basic-lifecycle-paused.png index fcb8bd245fa9..1b81c07b3ffb 100644 Binary files a/docs/html/images/training/basics/basic-lifecycle-paused.png and b/docs/html/images/training/basics/basic-lifecycle-paused.png differ diff --git a/docs/html/images/training/basics/basic-lifecycle-savestate.png b/docs/html/images/training/basics/basic-lifecycle-savestate.png index d74f1baa3033..9ea9484fc620 100644 Binary files a/docs/html/images/training/basics/basic-lifecycle-savestate.png and b/docs/html/images/training/basics/basic-lifecycle-savestate.png differ diff --git a/docs/html/images/training/basics/basic-lifecycle-stopped.png b/docs/html/images/training/basics/basic-lifecycle-stopped.png index 26c22ee0cc33..6f45fccb7f42 100644 Binary files a/docs/html/images/training/basics/basic-lifecycle-stopped.png and b/docs/html/images/training/basics/basic-lifecycle-stopped.png differ diff --git a/docs/html/images/training/basics/basic-lifecycle.png b/docs/html/images/training/basics/basic-lifecycle.png index 61eb422de9ba..f991787f68b8 100644 Binary files a/docs/html/images/training/basics/basic-lifecycle.png and b/docs/html/images/training/basics/basic-lifecycle.png differ diff --git a/docs/html/images/training/basics/network-settings1.png b/docs/html/images/training/basics/network-settings1.png new file mode 100644 index 000000000000..9eaf207d29ee Binary files /dev/null and b/docs/html/images/training/basics/network-settings1.png differ diff --git a/docs/html/images/training/basics/network-settings2.png b/docs/html/images/training/basics/network-settings2.png new file mode 100644 index 000000000000..5f4dc63aa96d Binary files /dev/null and b/docs/html/images/training/basics/network-settings2.png differ diff --git a/docs/html/images/ui/button-types.png b/docs/html/images/ui/button-types.png new file mode 100644 index 000000000000..dcb083f0a687 Binary files /dev/null and b/docs/html/images/ui/button-types.png differ diff --git a/docs/html/images/ui/buttons-holo.png b/docs/html/images/ui/buttons-holo.png new file mode 100644 index 000000000000..16e2fd274b11 Binary files /dev/null and b/docs/html/images/ui/buttons-holo.png differ diff --git a/docs/html/images/ui/checkboxes.png b/docs/html/images/ui/checkboxes.png new file mode 100644 index 000000000000..8878fb137cf6 Binary files /dev/null and b/docs/html/images/ui/checkboxes.png differ diff --git a/docs/html/images/ui/edittext-actionlabel.png b/docs/html/images/ui/edittext-actionlabel.png new file mode 100644 index 000000000000..a0e9fe9fcb35 Binary files /dev/null and b/docs/html/images/ui/edittext-actionlabel.png differ diff --git a/docs/html/images/ui/edittext-actionsend.png b/docs/html/images/ui/edittext-actionsend.png new file mode 100644 index 000000000000..63ccbd1b9b19 Binary files /dev/null and b/docs/html/images/ui/edittext-actionsend.png differ diff --git a/docs/html/images/ui/edittext-autocomplete.png b/docs/html/images/ui/edittext-autocomplete.png new file mode 100644 index 000000000000..c29091ac75c9 Binary files /dev/null and b/docs/html/images/ui/edittext-autocomplete.png differ diff --git a/docs/html/images/ui/edittext-email.png b/docs/html/images/ui/edittext-email.png new file mode 100644 index 000000000000..26f6136b2ee6 Binary files /dev/null and b/docs/html/images/ui/edittext-email.png differ diff --git a/docs/html/images/ui/edittext-noextract.png b/docs/html/images/ui/edittext-noextract.png new file mode 100644 index 000000000000..b459283c4d60 Binary files /dev/null and b/docs/html/images/ui/edittext-noextract.png differ diff --git a/docs/html/images/ui/edittext-phone.png b/docs/html/images/ui/edittext-phone.png new file mode 100644 index 000000000000..45177d3af7f4 Binary files /dev/null and b/docs/html/images/ui/edittext-phone.png differ diff --git a/docs/html/images/ui/edittext-text-next.png b/docs/html/images/ui/edittext-text-next.png new file mode 100644 index 000000000000..ef5ff1deea8f Binary files /dev/null and b/docs/html/images/ui/edittext-text-next.png differ diff --git a/docs/html/images/ui/edittext-text.png b/docs/html/images/ui/edittext-text.png new file mode 100644 index 000000000000..599dcec187b7 Binary files /dev/null and b/docs/html/images/ui/edittext-text.png differ diff --git a/docs/html/images/ui/edittext.png b/docs/html/images/ui/edittext.png new file mode 100644 index 000000000000..d4bcaaa643cf Binary files /dev/null and b/docs/html/images/ui/edittext.png differ diff --git a/docs/html/images/ui/gridlayout-small.png b/docs/html/images/ui/gridlayout-small.png new file mode 100644 index 000000000000..935b481c20cf Binary files /dev/null and b/docs/html/images/ui/gridlayout-small.png differ diff --git a/docs/html/images/ui/gridlayout.png b/docs/html/images/ui/gridlayout.png new file mode 100644 index 000000000000..12ae414dfafa Binary files /dev/null and b/docs/html/images/ui/gridlayout.png differ diff --git a/docs/html/images/ui/gridview-small.png b/docs/html/images/ui/gridview-small.png new file mode 100644 index 000000000000..104a4d4ec95f Binary files /dev/null and b/docs/html/images/ui/gridview-small.png differ diff --git a/docs/html/images/ui/gridview.png b/docs/html/images/ui/gridview.png new file mode 100644 index 000000000000..a780df313469 Binary files /dev/null and b/docs/html/images/ui/gridview.png differ diff --git a/docs/html/images/ui/linearlayout-small.png b/docs/html/images/ui/linearlayout-small.png new file mode 100644 index 000000000000..5d929e25d641 Binary files /dev/null and b/docs/html/images/ui/linearlayout-small.png differ diff --git a/docs/html/images/ui/linearlayout.png b/docs/html/images/ui/linearlayout.png new file mode 100644 index 000000000000..392cc11bd749 Binary files /dev/null and b/docs/html/images/ui/linearlayout.png differ diff --git a/docs/html/images/ui/listview-small.png b/docs/html/images/ui/listview-small.png new file mode 100644 index 000000000000..97eba89c100b Binary files /dev/null and b/docs/html/images/ui/listview-small.png differ diff --git a/docs/html/images/ui/listview.png b/docs/html/images/ui/listview.png new file mode 100644 index 000000000000..456ed0c851ca Binary files /dev/null and b/docs/html/images/ui/listview.png differ diff --git a/docs/html/images/ui/pickers.png b/docs/html/images/ui/pickers.png new file mode 100644 index 000000000000..e446fab48a42 Binary files /dev/null and b/docs/html/images/ui/pickers.png differ diff --git a/docs/html/images/ui/radiobuttons.png b/docs/html/images/ui/radiobuttons.png new file mode 100644 index 000000000000..8f6b22a7ab0f Binary files /dev/null and b/docs/html/images/ui/radiobuttons.png differ diff --git a/docs/html/images/ui/relativelayout-small.png b/docs/html/images/ui/relativelayout-small.png new file mode 100644 index 000000000000..c531e9a76cdd Binary files /dev/null and b/docs/html/images/ui/relativelayout-small.png differ diff --git a/docs/html/images/ui/relativelayout.png b/docs/html/images/ui/relativelayout.png new file mode 100644 index 000000000000..72c06ae15796 Binary files /dev/null and b/docs/html/images/ui/relativelayout.png differ diff --git a/docs/html/images/ui/sample-linearlayout.png b/docs/html/images/ui/sample-linearlayout.png new file mode 100644 index 000000000000..c4beb93a6d07 Binary files /dev/null and b/docs/html/images/ui/sample-linearlayout.png differ diff --git a/docs/html/images/ui/sample-relativelayout.png b/docs/html/images/ui/sample-relativelayout.png new file mode 100644 index 000000000000..d9ea30e0b02c Binary files /dev/null and b/docs/html/images/ui/sample-relativelayout.png differ diff --git a/docs/html/images/ui/spinner.png b/docs/html/images/ui/spinner.png new file mode 100644 index 000000000000..79ee4e443626 Binary files /dev/null and b/docs/html/images/ui/spinner.png differ diff --git a/docs/html/images/ui/switch.png b/docs/html/images/ui/switch.png new file mode 100644 index 000000000000..e8d801484dd9 Binary files /dev/null and b/docs/html/images/ui/switch.png differ diff --git a/docs/html/images/ui/tabs-small.png b/docs/html/images/ui/tabs-small.png new file mode 100644 index 000000000000..622f1e70b6c5 Binary files /dev/null and b/docs/html/images/ui/tabs-small.png differ diff --git a/docs/html/images/ui/tabs.png b/docs/html/images/ui/tabs.png new file mode 100644 index 000000000000..da9d4b661dc1 Binary files /dev/null and b/docs/html/images/ui/tabs.png differ diff --git a/docs/html/images/ui/togglebutton.png b/docs/html/images/ui/togglebutton.png new file mode 100644 index 000000000000..a69b3fe38a30 Binary files /dev/null and b/docs/html/images/ui/togglebutton.png differ diff --git a/docs/html/images/ui/ui-controls.png b/docs/html/images/ui/ui-controls.png new file mode 100644 index 000000000000..13534d3861bd Binary files /dev/null and b/docs/html/images/ui/ui-controls.png differ diff --git a/docs/html/images/ui/ui_index.png b/docs/html/images/ui/ui_index.png new file mode 100644 index 000000000000..3cc82c270725 Binary files /dev/null and b/docs/html/images/ui/ui_index.png differ diff --git a/docs/html/images/ui/webview-small.png b/docs/html/images/ui/webview-small.png new file mode 100644 index 000000000000..4c3243246376 Binary files /dev/null and b/docs/html/images/ui/webview-small.png differ diff --git a/docs/html/images/ui/webview.png b/docs/html/images/ui/webview.png new file mode 100644 index 000000000000..12cef588cecd Binary files /dev/null and b/docs/html/images/ui/webview.png differ diff --git a/docs/html/images/viewgroup.png b/docs/html/images/viewgroup.png index 2c86ddbd1874..fa077991037a 100644 Binary files a/docs/html/images/viewgroup.png and b/docs/html/images/viewgroup.png differ diff --git a/docs/html/images/webapps/webapps.png b/docs/html/images/webapps/webapps.png index 6ad620530345..ff499cfcd4dc 100644 Binary files a/docs/html/images/webapps/webapps.png and b/docs/html/images/webapps/webapps.png differ diff --git a/docs/html/index.jd b/docs/html/index.jd index d3203bbb04cb..58bfd040815c 100644 --- a/docs/html/index.jd +++ b/docs/html/index.jd @@ -1,218 +1,70 @@ -home=true +fullpage=true +no_footer_links=true +carousel=true page.metaDescription=The official site for Android developers. Provides the Android SDK and documentation for app developers and designers. @jd:body -
    -
    -
    -
    -
    -

    Developer Announcements

    -
    -
    - - -
    -

    Introducing Google Play: An integrated digital content destination where -users buy and enjoy all of their favorite content in one place. It's the new destination for -Android apps!

    -

    Read more »

    -
    -
    -
    -
    +
    + +
    + Prev + Next +
    +
      + +
    - -
     
    -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -

    Download

    -

    The Android SDK has the tools, sample code, and docs you need to create great apps.

    -

    Learn more »

    -
     
    -

    Design

    -

    Learn about principles, building blocks, and patterns for creating world-class Android user interfaces.

    -

    Learn more »

    -
     
    -

    Publish

    -

    Google Play is an open service that lets you distribute your apps to devices.

    -

    Learn more »

    -
     
    -

    Target Devices

    -

    The Device Dashboard -provides information about deployed Android devices to -help you target suitable device configurations as you build and update your -apps.

    -

    Learn more »

    -
    -
    -
    - - - - - - + + +
    + - - diff --git a/docs/html/intl/es/training/monitoring-device-state/battery-monitoring.jd b/docs/html/intl/es/training/monitoring-device-state/battery-monitoring.jd new file mode 100644 index 000000000000..08a42dd1f7f4 --- /dev/null +++ b/docs/html/intl/es/training/monitoring-device-state/battery-monitoring.jd @@ -0,0 +1,120 @@ +page.title=Cómo controlar el nivel de batería y el estado de carga +parent.title=Cómo optimizar la duración de la batería +parent.link=index.html + +trainingnavtop=true +next.title=Cómo determinar y controlar el tipo de conector y el estado de la conexión +next.link=docking-monitoring.html + +@jd:body + + + +

    Al modificar la frecuencia de las actualizaciones en segundo plano para reducir el efecto de las mismas en la duración de la batería, te recomendamos que comiences por comprobar el estado de carga y el nivel actual de la batería.

    + +

    El impacto derivado de actualizar aplicaciones en la duración de la batería varía en función del nivel de batería y del estado de carga del dispositivo, mientras que es insignificante cuando este está conectado a la corriente. Por ello, en la mayoría de los casos, puedes maximizar la frecuencia de actualización cuando el dispositivo esté conectado a un cargador. Por el contrario, si el dispositivo está en proceso de descarga, disminuir la frecuencia de actualización te permitirá aumentar la duración de la batería.

    + +

    Del mismo modo, puedes comprobar el nivel de carga de la batería y reducir la frecuencia de las actualizaciones o incluso detenerlas cuando la batería esté a punto de agotarse.

    + + +

    Cómo determinar el estado de carga actual

    + +

    En primer lugar, te recomendamos que determines el estado de carga actual. {@link android.os.BatteryManager} envía los detalles de carga y de la batería en un {@link android.content.Intent} persistente que incluye el estado de carga.

    + +

    Se trata de un intento persistente, por lo que no es necesario registrar un {@link android.content.BroadcastReceiver}. Para ello, solo tienes que ejecutar {@code registerReceiver} transmitiendo {@code null} como el receptor (como se muestra en el siguiente fragmento). A continuación, se devuelve el intento de estado actual de la batería. Puedes transmitir un objeto {@link android.content.BroadcastReceiver} real, pero hablaremos sobre las actualizaciones en otra sección, por lo que no es necesario ahora.

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    +Intent batteryStatus = context.registerReceiver(null, ifilter);
    + +

    Puedes extraer el estado de carga actual y, si el dispositivo está cargando, puedes saber también si se está usando un cargador de corriente alterna o USB:

    + +

    // Are we charging / charged?
    +int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                     status == BatteryManager.BATTERY_STATUS_FULL;
    +
    +// How are we charging?
    +int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    + +

    Normalmente, debes maximizar la frecuencia de las actualizaciones en segundo plano si el dispositivo está conectado a un cargador de corriente alterna, disminuir esa frecuencia si se utiliza un cargador USB y reducirla aún más si la batería se está descargando.

    + + +

    Cómo supervisar los cambios en el estado de carga

    + +

    Modificar el estado de carga es tan fácil como conectar el dispositivo a un enchufe o USB. Por ello, es importante que supervises el estado de carga por si se producen cambios y modifiques la frecuencia de actualización según corresponda.

    + +

    {@link android.os.BatteryManager} emite una acción siempre que el dispositivo se conecta o desconecta de la corriente. Es importante recibir estos eventos aunque la aplicación no esté en ejecución (especialmente porque estos eventos pueden afectar a la frecuencia con la que inicias tu aplicación para actualizarla en segundo plano), por lo que debes registrar un {@link android.content.BroadcastReceiver} en tu archivo de manifiesto para detectar ambos eventos definiendo {@link android.content.Intent#ACTION_POWER_CONNECTED} y {@link android.content.Intent#ACTION_POWER_DISCONNECTED} en un filtro de intentos.

    + +
    <receiver android:name=".PowerConnectionReceiver">
    +  <intent-filter>
    +    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    +    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    +  </intent-filter>
    +</receiver>
    + +

    En la implementación de {@link android.content.BroadcastReceiver} asociada, puedes extraer el método y el estado de carga actual como se describe en el paso anterior.

    + +
    public class PowerConnectionReceiver extends BroadcastReceiver {
    +    @Override
    +    public void onReceive(Context context, Intent intent) { 
    +        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                            status == BatteryManager.BATTERY_STATUS_FULL;
    +    
    +        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +        boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +        boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    +    }
    +}
    + + +

    Cómo determinar el nivel de batería actual

    + +

    En algunos casos, también es útil determinar el nivel de batería actual. Puedes disminuir la frecuencia de las actualizaciones en segundo plano si el nivel de carga de la batería es inferior a un valor determinado.

    + +

    Puedes consultar la carga actual de la batería extrayendo el nivel actual de la batería y subir a partir del intento de estado de batería, como se muestra a continuación:

    + +
    int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    +int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    +
    +float batteryPct = level / (float)scale;
    + + +

    Cómo supervisar cambios importantes en el nivel de batería

    + +

    No puedes controlar el estado de la batería de forma continua fácilmente, pero tampoco es necesario.

    + +

    En términos generales, el impacto sobre la batería derivado de controlar continuamente el nivel de batería es mayor que el comportamiento habitual de la aplicación. Por ello, te recomendamos que supervises únicamente los cambios en el nivel de batería más significativos, especialmente cuando el dispositivo tenga poca batería o acabe de cargarse.

    + +

    El fragmento de manifiesto que aparece a continuación se ha extraído del elemento de filtro de intento de un receptor de emisión. El receptor detecta {@link android.content.Intent#ACTION_BATTERY_LOW} y {@link android.content.Intent#ACTION_BATTERY_OKAY} y se activa cuando el nivel de batería del dispositivo es bajo o cuando se sale de un estado bajo de batería.

    + +
    <receiver android:name=".BatteryLevelReceiver">
    +<intent-filter>
    +  <action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
    +  <action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
    +  </intent-filter>
    +</receiver>
    + +

    Cuando la batería esté a punto de agotarse, te recomendamos que inhabilites las actualizaciones en segundo plano. Si el teléfono se apaga antes de poder utilizar las aplicaciones, no importa que tengan los datos actualizados.

    + +

    En muchos casos, el hecho de cargar un dispositivo coincide con la acción de utilizar un conector. En la próxima sección, hablaremos sobre cómo determinar el estado de conexión actual y cómo supervisar los cambios que se produzcan al conectar el dispositivo.

    + diff --git a/docs/html/intl/es/training/monitoring-device-state/connectivity-monitoring.jd b/docs/html/intl/es/training/monitoring-device-state/connectivity-monitoring.jd new file mode 100644 index 000000000000..2a5ff120e23d --- /dev/null +++ b/docs/html/intl/es/training/monitoring-device-state/connectivity-monitoring.jd @@ -0,0 +1,70 @@ +page.title=Cómo determinar y controlar el estado de la conectividad +parent.title=Cómo optimizar la duración de la batería +parent.link=index.html + +trainingnavtop=true + +previous.title=Cómo determinar y controlar el tipo de conector y el estado de la conexión +previous.link=docking-monitoring.html +next.title=Cómo manipular los receptores de emisión bajo demanda +next.link=manifest-receivers.html + +@jd:body + + + +

    Algunos de los usos más comunes para las alarmas con repetición y los servicios en segundo plano es programar actualizaciones regulares de los datos de aplicaciones a partir de recursos de Internet, almacenar datos en la memoria caché o ejecutar descargas a largo plazo. Sin embargo, si no estás conectado a Internet o la conexión es demasiado débil para completar la descarga, ¿para qué activar el dispositivo y programar la actualización?

    + +

    Puedes utilizar {@link android.net.ConnectivityManager} para comprobar si estás conectado a Internet y, en ese caso, el tipo de conexión que estás utilizando.

    + + +

    Cómo determinar si tienes conexión a Internet

    + +

    No es necesario programar una actualización basada en un recurso de Internet si no estás conectado. En el fragmento que aparece a continuación, se muestra cómo utilizar {@link android.net.ConnectivityManager} para consultar la red activa y determinar si hay conexión a Internet.

    + +
    ConnectivityManager cm =
    +        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    + 
    +NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    +boolean isConnected = activeNetwork.isConnectedOrConnecting();
    + + +

    Cómo determinar el tipo de conexión a Internet

    + +

    También puedes determinar el tipo de conexión a Internet que hay disponible.

    + +

    El dispositivo se puede conectar a Internet a través de conexiones Ethernet, Wi-Fi, WiMAX y de datos móviles. Al consultar el tipo de red activa, como se muestra a continuación, puedes modificar la frecuencia de actualización en función del ancho de banda disponible.

    + +
    boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
    + +

    El coste de las conexiones de datos móviles suele ser superior al de las conexiones Wi-Fi, por lo que en la mayoría de los casos, la frecuencia de actualización de tu aplicación debería ser menor si utilizas conexiones móviles. Del mismo modo, las descargas grandes deberían cancelarse hasta que estés conectado a una red Wi-Fi.

    + +

    Cuando hayas inhabilitado las actualizaciones, es importante que detectes si se hay cambios en la conectividad para poder reanudarlas cuando se haya establecido una conexión a Internet.

    + + +

    Cómo supervisar los cambios en la conectividad

    + +

    {@link android.net.ConnectivityManager} emite la acción {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} ({@code "android.net.conn.CONNECTIVITY_CHANGE"}) cuando se han modificado los detalles de la conectividad. Puedes registrar un receptor de emisión en el archivo de manifiesto para detectar estos cambios y reanudar (o cancelar) las actualizaciones en segundo plano según corresponda.

    + +
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    + +

    Los cambios en la conectividad de un dispositivo pueden ser muy frecuentes (esta emisión se activa siempre que cambias de una conexión de datos móviles a una conexión Wi-Fi). Como resultado, te recomendamos que supervises esta emisión únicamente cuando hayas cancelado anteriormente las actualizaciones o las descargas para reanudarlas. Normalmente, basta con comprobar la conexión a Internet antes de iniciar una actualización y, si no hay ninguna, cancelar el resto de actualizaciones hasta que se restablezca la conexión.

    + +

    Esta técnica requiere que alternes receptores de emisión que hayas declarado en el archivo de manifiesto, que se describe en la próxima sección.

    diff --git a/docs/html/intl/es/training/monitoring-device-state/docking-monitoring.jd b/docs/html/intl/es/training/monitoring-device-state/docking-monitoring.jd new file mode 100644 index 000000000000..d6122811e422 --- /dev/null +++ b/docs/html/intl/es/training/monitoring-device-state/docking-monitoring.jd @@ -0,0 +1,74 @@ +page.title=Cómo determinar y controlar el tipo de conector y el estado de la conexión +parent.title=Cómo optimizar la duración de la batería +parent.link=index.html + +trainingnavtop=true +previous.title=Cómo controlar el nivel de batería y el estado de carga +previous.link=battery-monitoring.html +next.title=Cómo determinar y controlar el estado de la conectividad +next.link=connectivity-monitoring.html + +@jd:body + + + +

    Los dispositivos Android se pueden conectar a distintos tipos de conectores. Por ejemplo, se puede utilizar conectores para coche o domésticos y tanto digitales como analógicos. Normalmente, el estado del conector está vinculado al estado de carga, ya que muchos conectores cargan el dispositivo mientras está conectado.

    + +

    El modo en el que el estado del conector del teléfono afecta a la frecuencia de actualización depende de tu aplicación. Puedes aumentar la frecuencia de actualización de una aplicación sobre noticias cuando el dispositivo esté conectado a un conector de escritorio o inhabilitar las actualizaciones completamente si está conectado a un conector de coche. Por el contrario, puedes maximizar las actualizaciones si el dispositivo está conectado a un conector de coche y tu servicio en segundo plano se actualiza con el estado del tráfico.

    + +

    El estado del conector se emite también como un {@link android.content.Intent} persistente, lo que te permite consultar si el dispositivo está conectado o no y, si lo está, determinar el tipo de conector.

    + + +

    Cómo determinar el estado de conexión actual

    + +

    La información sobre el estado del conector se incluye como información adicional en una emisión persistente de la acción {@link android.content.Intent#ACTION_DOCK_EVENT}. Por ello, no es necesario registrar un {@link android.content.BroadcastReceiver}. Solo tienes que ejecutar {@link android.content.Context#registerReceiver registerReceiver()} transmitiendo {@code null} como el receptor de emisión, como se muestra en el fragmento de código que aparece a continuación.

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
    +Intent dockStatus = context.registerReceiver(null, ifilter);
    + +

    Puedes extraer el estado actual de la conexión de la información adicional de {@code EXTRA_DOCK_STATE}:

    + +

    int dockState = battery.getIntExtra(EXTRA_DOCK_STATE, -1);
    +boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
    + + +

    Cómo determinar el tipo de conector actual

    + +

    Si un dispositivo está insertado en un conector, se puede conectar a cualquiera de estos cuatro tipos de conectores: +

    • coche,
    • +
    • escritorio,
    • +
    • escritorio de gama baja (analógico),
    • +
    • escritorio de gama alta (digital).

    + +

    Ten en cuenta que las últimas dos opciones se introdujeron en Android únicamente en el nivel 11 del API. Por ello, te recomendamos que compruebes las tres opciones solo cuando te interese más el tipo de conector que si se trata de un conector digital o analógico:

    + +
    boolean isCar = dockState == EXTRA_DOCK_STATE_CAR;
    +boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK || 
    +                 dockState == EXTRA_DOCK_STATE_LE_DESK ||
    +                 dockState == EXTRA_DOCK_STATE_HE_DESK;
    + + +

    Cómo supervisar los cambios en el tipo de conector o en el estado del mismo

    + +

    Cuando el dispositivo está conectado a un conector o desconectado del mismo, se emite la acción {@link android.content.Intent#ACTION_DOCK_EVENT}. Para controlar los cambios que se produzcan en el estado del conector del dispositivo, solo tienes que registrar un receptor de emisión en el archivo de manifiesto de la aplicación, como se muestra en el fragmento que aparece a continuación:

    + +
    <action android:name="android.intent.action.ACTION_DOCK_EVENT"/>
    + +

    Puedes extraer el estado y el tipo de conector en la implementación del receptor con las mismas técnicas que se han descrito en el paso anterior.

    diff --git a/docs/html/intl/es/training/monitoring-device-state/index.jd b/docs/html/intl/es/training/monitoring-device-state/index.jd new file mode 100644 index 000000000000..bf6b1c1e7091 --- /dev/null +++ b/docs/html/intl/es/training/monitoring-device-state/index.jd @@ -0,0 +1,49 @@ +page.title=Cómo optimizar la duración de la batería + +trainingnavtop=true +startpage=true +next.title=Cómo controlar el nivel de batería y el estado de carga +next.link=battery-monitoring.html + +@jd:body + +
    +
    + +

    Dependencias y requisitos previos

    + + +

    También puedes consultar:

    + + +
    +
    + +

    Uno de los objetivos de tu aplicación debe ser limitar su impacto en la duración de la batería del dispositivo en el que esté instalada. Después de leer estas secciones, podrás desarrollar aplicaciones que optimizarán el uso de la batería en función del estado del dispositivo en el que estén instaladas.

    + +

    Al tomar medidas como inhabilitar las actualizaciones de servicios en segundo plano o disminuir la frecuencia de dichas actualizaciones cuando el nivel de batería sea bajo, puedes garantizar que se minimice el impacto de tu aplicación en la duración de la batería sin afectar a la experiencia del usuario.

    + +

    Secciones

    + + + +
    +
    Cómo controlar el nivel de batería y el estado de carga
    +
    Obtén más información sobre cómo determinar y controlar el nivel de batería actual y los cambios en el estado de carga para modificar la frecuencia de actualizaciones en segundo plano de tu aplicación.
    + +
    Cómo determinar y controlar el tipo de conector y el estado de la conexión
    +
    La frecuencia de actualización óptima puede variar en función de cómo se utilice el dispositivo en el que está instalada la aplicación. Obtén más información sobre cómo determinar y controlar cuándo el dispositivo está conectado a algún sistema de acoplamiento u otra conexión.
    + +
    Cómo determinar y controlar el estado de la conectividad
    +
    Si no tienes conexión a Internet, no puedes actualizar tu aplicación a partir de una fuente online. Obtén más información sobre cómo comprobar el estado de la conectividad para modificar la frecuencia de actualización en segundo plano de tu aplicación. También puedes obtener más información sobre cómo comprobar la conectividad móvil o Wi-Fi antes de iniciar operaciones que requieran un nivel elevado de ancho de banda.
    + +
    Cómo manipular los receptores de emisión bajo demanda
    +
    Los receptores de emisión que declaras en el archivo de manifiesto se pueden alternar durante la ejecución para inhabilitar los que no son necesarios debido al estado actual del dispositivo. Obtén más información sobre cómo alternar y superponer receptores de cambio de estado para mejorar el rendimiento y cómo posponer acciones hasta que el dispositivo se encuentre en un estado concreto.
    +
    \ No newline at end of file diff --git a/docs/html/intl/es/training/monitoring-device-state/manifest-receivers.jd b/docs/html/intl/es/training/monitoring-device-state/manifest-receivers.jd new file mode 100644 index 000000000000..a90468e37336 --- /dev/null +++ b/docs/html/intl/es/training/monitoring-device-state/manifest-receivers.jd @@ -0,0 +1,50 @@ +page.title=Cómo manipular los receptores de emisión bajo demanda +parent.title=Cómo optimizar la duración de la batería +parent.link=index.html + +trainingnavtop=true + +previous.title=Cómo determinar y controlar el estado de la conectividad +previous.link=connectivity-monitoring.html + +@jd:body + +
    +
    + +

    En esta sección puedes aprender:

    +
      +
    1. Cómo alternar y superponer receptores de cambio de estado para mejorar el rendimiento
    2. +
    + + +

    También puedes consultar:

    + + +
    +
    + +

    La forma más sencilla de controlar los cambios en el estado del dispositivo es crear un {@link android.content.BroadcastReceiver} para cada estado que vayas a controlar y registrar cada uno de ellos en el archivo de manifiesto de tu aplicación. A continuación, en cada uno de esos receptores solo tienes que volver a programar las alarmas recurrentes en función del estado actual del dispositivo.

    + +

    Un efecto secundario de este método es que tu aplicación activará el dispositivo siempre que uno de los receptores se active (probablemente, con más frecuencia de la necesaria).

    + +

    Te recomendamos que inhabilites o habilites los receptores de emisión en el momento de la ejecución. De este modo, puedes utilizar los receptores que hayas declarado en el archivo de manifiesto como alarmas pasivas que se activan mediante los eventos del sistema solo cuando es necesario.

    + + +

    Cómo alternar y superponer receptores de cambio de estado para mejorar el rendimiento

    + +

    Se puede utilizar el {@link android.content.pm.PackageManager} para alternar el estado habilitado en cualquier componente definido en el archivo de manifiesto, incluidos los receptores de emisión que quieras habilitar o inhabilitar, como se muestra en el fragmento que aparece a continuación:

    + +
    ComponentName receiver = new ComponentName(context, myReceiver.class);
    +
    +PackageManager pm = context.getPackageManager();
    +
    +pm.setComponentEnabledSetting(receiver,
    +        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    +        PackageManager.DONT_KILL_APP)
    + +

    Al utilizar esta técnica, si determinas que la conectividad se ha perdido, puedes inhabilitar todos los receptores excepto el receptor de cambio de conectividad. Por el contrario, cuando estés conectado, puedes dejar de detectar cambios de conectividad y solo comprobar si tienes conexión antes de realizar una actualización y de volver a programar una alarma de actualización recurrente.

    + +

    Puedes utilizar la misma técnica para posponer una descarga que requiera un nivel de ancho de banda superior para completarse. Solo tienes que habilitar un receptor de emisión que detecte los cambios de conectividad y que inicie la descarga solo cuando estés conectado a una red Wi-Fi.

    diff --git a/docs/html/intl/es/training/multiscreen/adaptui.jd b/docs/html/intl/es/training/multiscreen/adaptui.jd new file mode 100644 index 000000000000..61f0735bc409 --- /dev/null +++ b/docs/html/intl/es/training/multiscreen/adaptui.jd @@ -0,0 +1,212 @@ +page.title=Cómo implementar interfaces de usuario adaptables +parent.title=Cómo diseñar aplicaciones para varias pantallas +parent.link=index.html + +trainingnavtop=true +previous.title=Cómo admitir varias densidades de pantalla +previous.link=screendensities.html + +@jd:body + + + + + +

    En función del diseño actual de tu aplicación, la interfaz puede variar. Por ejemplo, si tu aplicación está en modo de panel dual, haz clic en un elemento del panel izquierdo para que aparezca en el panel de la derecha. Asimismo, si está en modo de panel único, el contenido debería aparecer por sí mismo (en otra actividad).

    + + +

    Cómo determinar el diseño actual

    + +

    Dado que la implementación de cada diseño variará en cierta medida, probablemente una de las primeras cosas que tendrás que hacer será determinar el diseño que el usuario puede ver en ese momento. Por ejemplo, puedes determinar si el usuario utiliza el modo de "panel único" o de "panel dual". Para ello, puedes consultar si una vista determinada existe y es visible:

    + +
    +public class NewsReaderActivity extends FragmentActivity {
    +    boolean mIsDualPane;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main_layout);
    +
    +        View articleView = findViewById(R.id.article);
    +        mIsDualPane = articleView != null && 
    +                        articleView.getVisibility() == View.VISIBLE;
    +    }
    +}
    +
    + +

    Ten en cuenta que este código consulta la disponibilidad del panel del "artículo", lo que es mucho más flexible que incluir una consulta para un diseño determinado.

    + +

    Otro ejemplo de cómo puedes adaptar la existencia de diferentes componentes es comprobar su disponibilidad antes de realizar una operación relacionada con los mismos. Por ejemplo, en la aplicación de ejemplo News Reader, hay un botón que abre un menú, pero ese botón solo aparece en las versiones anteriores a Android 3.0 (porque {@link android.app.ActionBar} en el nivel 11 del API y en niveles superiores). Por tanto, para añadir el detector de eventos para este botón, puedes hacer lo siguiente:

    + +
    +Button catButton = (Button) findViewById(R.id.categorybutton);
    +OnClickListener listener = /* create your listener here */;
    +if (catButton != null) {
    +    catButton.setOnClickListener(listener);
    +}
    +
    + + +

    Cómo reaccionar en función del diseño actual

    + +

    El resultado de algunas acciones puede variar en función del diseño actual. Por ejemplo, en el ejemplo de News Reader, al hacer clic en un encabezado de la lista se abrirá el artículo del panel situado a la derecha si la interfaz de usuario está en modo de panel dual, pero se iniciará una actividad independiente si esta está en modo de panel único:

    + +
    +@Override
    +public void onHeadlineSelected(int index) {
    +    mArtIndex = index;
    +    if (mIsDualPane) {
    +        /* display article on the right pane */
    +        mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
    +    } else {
    +        /* start a separate activity */
    +        Intent intent = new Intent(this, ArticleActivity.class);
    +        intent.putExtra("catIndex", mCatIndex);
    +        intent.putExtra("artIndex", index);
    +        startActivity(intent);
    +    }
    +}
    +
    + +

    De igual modo, si la aplicación está en modo de panel dual, debe configurar la barra de acción con pestañas para la navegación, mientras que si la aplicación está en modo de panel único, debe configurar la navegación con un widget giratorio. Por tanto, el código debe comprobar también cuál es el caso adecuado:

    + +
    +final String CATEGORIES[] = { "Top Stories", "Politics", "Economy", "Technology" };
    +
    +public void onCreate(Bundle savedInstanceState) {
    +    ....
    +    if (mIsDualPane) {
    +        /* use tabs for navigation */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
    +        int i;
    +        for (i = 0; i < CATEGORIES.length; i++) {
    +            actionBar.addTab(actionBar.newTab().setText(
    +                CATEGORIES[i]).setTabListener(handler));
    +        }
    +        actionBar.setSelectedNavigationItem(selTab);
    +    }
    +    else {
    +        /* use list navigation (spinner) */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
    +        SpinnerAdapter adap = new ArrayAdapter(this, 
    +                R.layout.headline_item, CATEGORIES);
    +        actionBar.setListNavigationCallbacks(adap, handler);
    +    }
    +}
    +
    + + +

    Cómo volver a utilizar fragmentos en otras actividades

    + +

    Un patrón recurrente a la hora de diseñar para distintas pantallas es utilizar una parte de la interfaz que se implementa como un panel en algunas configuraciones de pantalla y como actividad independiente en otras. Por ejemplo, en el ejemplo de News Reader, el texto del artículo de noticias se presenta en el panel de la derecha en las pantallas grandes, pero es una actividad independiente en las pantallas más pequeñas.

    + +

    En otros casos similares, puedes evitar la duplicación de código reutilizando la misma {@link android.app.Fragment} en distintas actividades. Por ejemplo, ArticleFragment se utiliza en el diseño de panel dual:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    A continuación, se vuelve a utilizar (sin diseño) en el diseño de actividad para pantallas más pequeñas (ArticleActivity):

    + +
    +ArticleFragment frag = new ArticleFragment();
    +getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
    +
    + +

    Evidentemente, esto tiene el mismo efecto que declarar el fragmento en un diseño XML. Sin embargo, en este caso, un diseño XML sería un trabajo innecesario porque el fragmento del artículo es el único componente de esta actividad.

    + +

    Un punto muy importante que debes tener en cuenta al diseñar tus fragmentos es no crear un acoplamiento fuerte para una actividad determinada. Para ello, normalmente puedes definir una interfaz que resuma todas las formas en las que tiene que interactuar el fragmento con su actividad principal y, a continuación, la actividad principal implementa esa interfaz:

    + +

    Por ejemplo, ese es precisamente el objetivo del HeadlinesFragment de la aplicación News Reader:

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    OnHeadlineSelectedListener mHeadlineSelectedListener = null;
    +
    +    /* Must be implemented by host activity */
    +    public interface OnHeadlineSelectedListener {
    +        public void onHeadlineSelected(int index);
    +    }
    +    ...
    +
    +    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
    +        mHeadlineSelectedListener = listener;
    +    }
    +}
    +
    + +

    A continuación, cuando el usuario selecciona un encabezado, el fragmento notifica el detector especificado por la actividad principal (en lugar de notificar una actividad predefinida específica):

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    @Override
    +    public void onItemClick(AdapterView<?> parent, 
    +                            View view, int position, long id) {
    +        if (null != mHeadlineSelectedListener) {
    +            mHeadlineSelectedListener.onHeadlineSelected(position);
    +        }
    +    }
    +    ...
    +}
    +
    + +

    Si quieres obtener más información sobre esta técnica, puedes consultar la guía sobre Cómo admitir tablets y dispositivos móviles.

    + + +

    Cómo gestionar los cambios en la configuración de la pantalla

    + +

    Si utilizas actividades independientes para implementar partes individuales de tu interfaz, debes tener en cuenta que es posible que tengas que reaccionar ante determinados cambios en la configuración (como un cambio de rotación) para mantener la homogeneidad de tu interfaz.

    + +

    Por ejemplo, en un tablet de 7" que utilice Android 3.0 o una versión superior, el ejemplo de News Reader utiliza una actividad independiente para mostrar el artículo de noticias en el modo vertical, pero utiliza el diseño de panel dual en el modo horizontal.

    + +

    Esto significa que cuando el usuario utiliza el modo vertical y está consultando un artículo, tienes que detectar que la orientación ha cambiado al modo horizontal y reaccionar de forma adecuada finalizando la actividad. A continuación, debes volver a la actividad principal para que el contenido pueda mostrarse en el diseño de panel dual:

    + +
    +public class ArticleActivity extends FragmentActivity {
    +    int mCatIndex, mArtIndex;
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
    +        mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
    +
    +        // If should be in two-pane mode, finish to return to main activity
    +        if (getResources().getBoolean(R.bool.has_two_panes)) {
    +            finish();
    +            return;
    +        }
    +        ...
    +}
    +
    + + diff --git a/docs/html/intl/es/training/multiscreen/index.jd b/docs/html/intl/es/training/multiscreen/index.jd new file mode 100644 index 000000000000..0a1461b12cdc --- /dev/null +++ b/docs/html/intl/es/training/multiscreen/index.jd @@ -0,0 +1,63 @@ +page.title=Cómo diseñar aplicaciones para varias pantallas +trainingnavtop=true +startpage=true +next.title=Cómo admitir varios tamaños de pantalla +next.link=screensizes.html + +@jd:body + +
    +
    + +

    Dependencias y requisitos previos

    + + + +

    También puedes consultar:

    + + + +

    ¡Pruébalo!

    + + + +
    +
    + +

    Android se utiliza en cientos de dispositivos con diferentes tamaños de pantalla, desde pequeños teléfonos hasta enormes televisores. Por ello, es importante que diseñes tu aplicación para que sea compatible con todos los tamaños de pantalla y esté disponible para el mayor número de usuarios posible.

    + +

    Sin embargo, no es suficiente con que tu aplicación sea compatible con diferentes dispositivos. Cada tamaño de pantalla ofrece diferentes posibilidades y retos para la interacción del usuario. Por ello, para satisfacer completamente a tus usuarios e impresionarlos, tu aplicación debe ir más allá de simplemente admitir varias pantallas: debe optimizar la experiencia de usuario para cada configuración de pantalla.

    + +

    En esta sección se explica cómo implementar una interfaz de usuario que esté optimizada para diferentes configuraciones de pantalla.

    + +

    El código que aparece en cada sección se ha extraído de una aplicación de ejemplo para explicar las prácticas recomendadas a la hora de optimizar tu aplicación para varias pantallas. Puedes descargar el ejemplo (situado a la derecha) y utilizarlo como fuente de código reutilizable para tu propia aplicación.

    + +

    Nota: en esta sección y en el ejemplo correspondiente, se utiliza la biblioteca de compatibilidad para poder usar las API de {@link android.app.Fragment} en versiones anteriores a Android 3.0. Debes descargar y la biblioteca y añadirla a tu aplicación para poder utilizar todas las API que se indican en esta sección.

    + + +

    Secciones

    + +
    +
    Cómo admitir varios tamaños de pantalla
    +
    En esta sección se explica cómo crear diseños que se adapten a diferentes tamaños de pantalla (mediante dimensiones flexibles para vistas, {@link android.widget.RelativeLayout}, calificadores de orientación y tamaño de pantalla, filtros de alias y mapas de bits de la clase NinePatch).
    + +
    Cómo admitir varias densidades de pantalla
    +
    En esta sección se explica cómo admitir pantallas con diferentes densidades de píxeles (mediante píxeles independientes de la densidad y mapas de bits adecuados a cada densidad).
    + +
    Cómo implementar interfaces de usuario adaptables
    +
    En esta sección se explica cómo implementar tu interfaz de usuario para que se adapte a varias combinaciones de densidad o de tamaño de pantalla (detección de tiempo de ejecución del diseño activo, cómo reaccionar en función del diseño actual y cómo administrar los cambios en la configuración de la pantalla).
    +
    diff --git a/docs/html/intl/es/training/multiscreen/screendensities.jd b/docs/html/intl/es/training/multiscreen/screendensities.jd new file mode 100644 index 000000000000..0edb89fd4707 --- /dev/null +++ b/docs/html/intl/es/training/multiscreen/screendensities.jd @@ -0,0 +1,100 @@ +page.title=Cómo admitir varias densidades de pantalla +parent.title=Cómo diseñar aplicaciones para varias pantallas +parent.link=index.html + +trainingnavtop=true +previous.title=Cómo admitir varios tamaños de pantalla +previous.link=screensizes.html +next.title=Cómo implementar interfaces de usuario adaptables +next.link=adaptui.html + +@jd:body + + + +
    +
    + +

    En esta sección puedes aprender:

    +
      +
    1. Cómo utilizar píxeles independientes de la densidad
    2. +
    3. Cómo proporcionar mapas de bits alternativos
    4. +
    + +

    También puedes consultar:

    + + + +

    ¡Pruébalo!

    + + + + +
    +
    + +

    En esta sección se explica cómo proporcionar diferentes recursos y utilizar unidades de medida de resolución independiente para admitir diferentes densidades de pantalla.

    + +

    Cómo utilizar píxeles independientes de la densidad

    + +

    Un error común que debes evitar al crear tus diseños es utilizar píxeles absolutos para definir distancias o tamaños. Definir dimensiones de diseño mediante píxeles es problemático porque cada pantalla tiene densidades de píxeles diferentes, por lo que es posible que el mismo número de píxeles corresponda a varios tamaños físicos en distintos dispositivos. Por tanto, al especificar dimensiones, debes utilizar siempre unidades dp o sp. dp es un píxel independiente de la densidad que corresponde al tamaño físico de un píxel a 160 dpi. sp es la misma unidad de base, pero aumentada en función del tamaño de letra preferido por el usuario (se trata de un píxel independiente de la escala). Por tanto, debes utilizar esta unidad de medida para definir el tamaño de letra (pero no para tamaños de diseños).

    + +

    Por ejemplo, al especificar un espacio entre dos vistas, debes utilizar dp en lugar de px:

    + +
    +<Button android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content" 
    +    android:text="@string/clickme"
    +    android:layout_marginTop="20dp" />
    +
    + +

    Al especificar el tamaño de letra, debes usar siempre sp:

    + +
    +<TextView android:layout_width="match_parent" 
    +    android:layout_height="wrap_content" 
    +    android:textSize="20sp" />
    +
    + + +

    Cómo proporcionar mapas de bits alternativos

    + +

    Dado que Android se ejecuta en dispositivos con diferentes densidades de pantalla, siempre debes proporcionar tus recursos de mapas de bits adaptados a los conjuntos de densidades generalizados: baja, media, alta y muy alta. De este modo, podrás conseguir un rendimiento y una calidad gráfica óptimos en todas las densidades de pantalla.

    + +

    Para generar estas imágenes, debes empezar con tu recurso genérico en formato vectorial y generar las imágenes para cada densidad con la siguiente escala de tamaños:

    + +

      +
    • xhdpi: 2,0 +
    • hdpi: 1,5 +
    • mdpi: 1.0 (base) +
    • ldpi: 0,75 +

    + +

    Esto significa que si generas una imagen de 200 x 200 para dispositivos xhdpi, debes generar el mismo recurso en 150 x 150 para hdpi, en 100 x 100 para mdpi y, por último, una imagen de 75 x 75 para dispositivos ldpi.

    + +

    A continuación, sitúa los archivos de imagen generados en el subdirectorio adecuado en res/ y el sistema seleccionará el archivo correspondiente automáticamente en función de la densidad de la pantalla del dispositivo en el que se esté ejecutando la aplicación:

    + +
    +MyProject/
    +  res/
    +    drawable-xhdpi/
    +        awesomeimage.png
    +    drawable-hdpi/
    +        awesomeimage.png
    +    drawable-mdpi/
    +        awesomeimage.png
    +    drawable-ldpi/
    +        awesomeimage.png
    +
    + +

    Por tanto, cada vez que hagas referencia a @drawable/awesomeimage, el sistema seleccionará el mapa de bits adecuado en función de los puntos por pulgada de la pantalla.

    + +

    Para consultar más sugerencias y directrices sobre cómo crear recursos de iconos para tu aplicación, consulta la sección Directrices para diseñar iconos.

    + diff --git a/docs/html/intl/es/training/multiscreen/screensizes.jd b/docs/html/intl/es/training/multiscreen/screensizes.jd new file mode 100644 index 000000000000..9a971d1c000c --- /dev/null +++ b/docs/html/intl/es/training/multiscreen/screensizes.jd @@ -0,0 +1,279 @@ +page.title=Cómo admitir varios tamaños de pantalla +parent.title=Cómo diseñar aplicaciones para varias pantallas +parent.link=index.html + +trainingnavtop=true +next.title=Cómo admitir varias densidades de pantalla +next.link=screendensities.html + +@jd:body + + + + + +

    En esta sección se explica cómo admitir varios tamaños de pantalla. Para ello, sigue estos pasos:

    +
      +
    • Asegúrate de que el diseño se haya ajustado correctamente al tamaño de la pantalla.
    • +
    • Configura la pantalla con el diseño de interfaz adecuado.
    • +
    • Asegúrate de aplicar el diseño adecuado a la pantalla correspondiente.
    • +
    • Utiliza el mapa de bits con la escala adecuada.
    • +
    + + +

    Cómo utilizar los valores "wrap_content" y "match_parent"

    + +

    Para garantizar que el diseño es flexible y que se adapta a varios tamaños de pantalla, debes utilizar los valores "wrap_content" y "match_parent" para la altura y el ancho de algunos componentes de la vista. Si utilizas "wrap_content", el ancho o la altura de la vista se establece en el tamaño mínimo necesario para adaptar el contenido a esta vista, mientras que "match_parent" (también conocido como "fill_parent" antes del nivel 8 del API) provoca que el componente se amplíe hasta coincidir con el tamaño de la vista principal.

    + +

    Al utilizar los valores de tamaño "wrap_content" y "match_parent" en lugar de los tamaños predefinidos, las vistas pueden utilizar únicamente el espacio requerido para esa vista o ampliarse hasta rellenar el espacio disponible respectivamente. Por ejemplo:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    Observa cómo se utilizan en el ejemplo los valores "wrap_content" y "match_parent" para los tamaños de los componentes en lugar de dimensiones específicas. Esto permite que el diseño se adapte correctamente a diferentes tamaños y orientaciones de la pantalla.

    + +

    Por ejemplo, esta es la apariencia del diseño en modo horizontal y vertical. Ten en cuenta que los tamaños de los componentes se adaptan automáticamente a la altura y al ancho:

    + + +

    Figura 1. La aplicación de ejemplo News Reader en modo vertical (izquierda) y horizontal (derecha)

    + + +

    Cómo utilizar RelativeLayout

    + +

    Puedes crear diseños de un cierto nivel de complejidad con instancias anidadas de {@link android.widget.LinearLayout} y combinaciones de los valores de tamaño "wrap_content" y "match_parent". Sin embargo, {@link android.widget.LinearLayout} no te permite controlar con precisión las relaciones espaciales de las vistas secundarias; las vistas de {@link android.widget.LinearLayout} simplemente se alinean en paralelo. Si quieres orientar las vistas secundarias de una forma que no sea una línea recta, a menudo la mejor solución es utilizar {@link android.widget.RelativeLayout}que te permite especificar el diseño según las relaciones espaciales entre los componentes. Por ejemplo, puedes alinear una vista secundaria en el lateral izquierdo y otra vista en el lateral derecho de la pantalla.

    + +

    Por ejemplo:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="match_parent"
    +    android:layout_height="match_parent">
    +    <TextView
    +        android:id="@+id/label"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:text="Type here:"/>
    +    <EditText
    +        android:id="@+id/entry"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/label"/>
    +    <Button
    +        android:id="@+id/ok"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/entry"
    +        android:layout_alignParentRight="true"
    +        android:layout_marginLeft="10dp"
    +        android:text="OK" />
    +    <Button
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_toLeftOf="@id/ok"
    +        android:layout_alignTop="@id/ok"
    +        android:text="Cancel" />
    +</RelativeLayout>
    +
    + +

    La figura 2 indica cómo se muestra este diseño en una pantalla QVGA.

    + + +

    Figura 2. Captura de pantalla de una pantalla QVGA (pantalla pequeña)

    + +

    La figura 3 indica cómo se muestra este diseño en una pantalla más grande.

    + + +

    Figura 3. Captura de pantalla de una pantalla WSVGA (pantalla grande)

    + +

    Ten en cuenta que aunque el tamaño de los componentes es diferente, las relaciones espaciales se mantienen según se ha especificado con {@link android.widget.RelativeLayout.LayoutParams}.

    + + +

    Cómo utilizar calificadores de tamaño

    + +

    Hay mucha diferencia entre un diseño flexible y un diseño relativo como el que se ha utilizado en las secciones anteriores. Aunque ambos diseños se adaptan a diferentes pantalla estirando el espacio dentro de los componentes y alrededor de los mismos, puede que no ofrezcan la mejor experiencia de usuario para cada tamaño de pantalla. Por tanto, tu aplicación no solo debe implementar los diseños flexibles, sino que también debe ofrecer varios diseños alternativos para diferentes configuraciones de pantalla. Para ello, se utilizan calificadores de configuración, que permiten que el tiempo de ejecución seleccione el recurso adecuado en función de la configuración actual del dispositivo (por ejemplo, un diseño diferente para diferentes tamaños de pantalla).

    + +

    Por ejemplo, muchas aplicaciones implementan el patrón de "panel dual" para pantallas grandes (la aplicación mostraría una lista de elementos en un panel y el contenido en otro panel). Aunque los tablets y las televisiones son lo suficientemente grandes como para que los dos paneles aparezcan simultáneamente en la pantalla, las pantallas de los teléfonos tienen que mostrarlos por separado. Para implementar estos diseños, puedes utilizar los siguientes archivos:

    + +
      +
    • res/layout/main.xml, diseño de panel único (predeterminado): + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-large/main.xml, diseño de panel dual: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    Observa el calificador large en el nombre de directorio del segundo diseño. Este diseño se seleccionará en dispositivos con pantallas clasificadas como grandes (por ejemplo, tablets de 7" y superiores). El otro diseño (sin calificadores) se seleccionará en el caso de dispositivos más pequeños.

    + + +

    Cómo utilizar el calificador de ancho mínimo

    + +

    Una de las dificultades a las que se enfrentaron los desarrolladores con los dispositivos Android anteriores a la versión 3.2 fue el contenedor de tamaño de pantalla "grande". Algunos ejemplos de este tipo de dispositivo son el tablet Dell Streak, el tablet Galaxy Tab original y los tablets de 7" en general. Sin embargo, es posible que muchas aplicaciones quieran mostrar varios diseños para diferentes dispositivos de esta categoría (por ejemplo, para dispositivos de 5" y de 7"), aunque todos estos dispositivos se consideren de pantalla grande. Por esta razón, Android introdujo el calificador de "ancho mínimo" (entre otros) en Android 3.2.

    + +

    Este calificador te permite mostrar contenido en pantallas que tengan un ancho mínimo determinado en píxeles independientes de la densidad. Por ejemplo, el tablet típico de 7" tiene un ancho mínimo de 600 dp, por lo que si quieres que la interfaz de usuario sea de panel dual en esta pantalla (y una única lista en pantallas más pequeñas), puedes utilizar los mismos dos diseños de la sección anterior para los diseños de panel único y de panel dual, solo que en lugar de utilizar el calificador de tamaño large, debes utilizar sw600dp para indicar que el diseño de panel dual se utiliza con las pantallas cuyo ancho mínimo sea de 600 dp:

    + +
      +
    • res/layout/main.xml, diseño de panel único (predeterminado): + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-sw600dp/main.xml, diseño de panel dual: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    Esto significa que los dispositivos cuyo ancho mínimo sea igual o superior a 600 dp utilizarán el diseño layout-sw600dp/main.xml (panel dual), mientras que las pantallas más pequeñas utilizarán el diseño layout/main.xml (panel único).

    + +

    No obstante, esto no funcionará en los dispositivos anteriores a Android 3.2 porque no reconocen sw600dp como calificador de tamaño, por lo que también tendrás que seguir utilizando el calificador large. Por tanto, debes tener un archivo con el nombre res/layout-large/main.xml idéntico a res/layout-sw600dp/main.xml. En la siguiente sección, obtendrás información sobre una técnica que te permite evitar que se dupliquen los archivos de diseños.

    + + +

    Cómo utilizar alias de diseño

    + +

    El calificador de ancho mínimo solo está disponible en Android 3.2 o superior. Por tanto, tendrás que seguir utilizando los contenedores de tamaño abstractos (pequeño, normal, grande y extragrande) para que sean compatibles con versiones anteriores. Por ejemplo, si quieres que tu interfaz de usuario sea de panel único en teléfonos pero multipanel en tablets de 7", televisiones y otros dispositivos grandes, tendrás que utilizar los siguientes archivos:

    + +

      +
    • res/layout/main.xml: diseño de panel único,
    • +
    • res/layout-large: diseño multipanel,
    • +
    • res/layout-sw600dp: diseño multipanel.
    • +

    + +

    Los dos últimos archivos son idénticos porque uno de ellos se utilizará con dispositivos Android 3.2 y el otro con tablets y televisiones que utilicen versiones anteriores de Android.

    + +

    Para evitar la duplicación del mismo archivo para tablets y televisiones (así como todos los problemas que esto conlleva), puedes utilizar archivos alias. Por ejemplo, puedes establecer los siguientes diseños:

    + +
      +
    • res/layout/main.xml: diseño de panel único,
    • +
    • res/layout/main_twopanes.xml: diseño de panel dual.
    • +
    + +

    Añade estos dos archivos:

    + +

      +
    • res/values-large/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      +
    • + +
    • res/values-sw600dp/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      + +
    • +

    + +

    Estos dos últimos archivos tienen el mismo contenido, pero en realidad no definen el diseño. Solo configuran {@code main} para que sea un alias de {@code main_twopanes}. Como los archivos tienen selectores large y sw600dp, se aplican a tablets y a televisiones independientemente de la versión de Android (las televisiones y los tablets anteriores a la versión 3.2 utilizarán +{@code large}y las televisiones y los tablets posteriores a la versión 3.2 utilizarán sw600dp).

    + + +

    Cómo utilizar calificadores de orientación

    + +

    Aunque algunos diseños se pueden utilizar tanto en modo horizontal como vertical, la mayoría de ellos pueden beneficiarse de los ajustes. A continuación, se indica cómo se comporta el diseño según cada tamaño y orientación de la pantalla en la aplicación de ejemplo News Reader:

    + +

      +
    • pantalla pequeña, vertical: panel único con logotipo,
    • +
    • pantalla pequeña, horizontal: panel único con logotipo,
    • +
    • tablet de 7", vertical: panel único con barra de acciones,
    • +
    • tablet de 7", horizontal: panel dual ancho con barra de acciones,
    • +
    • tablet de 10", vertical: panel dual estrecho con barra de acciones,
    • +
    • tablet de 10", horizontal: panel dual ancho con barra de acciones,
    • +
    • televisión, horizontal: panel dual ancho con barra de acciones.
    • +

    + +

    Cada uno de estos diseños se establecen en un archivo XML en el directorio res/layout/. Para definir posteriormente las diferentes configuraciones de pantalla, la aplicación utiliza alias de diseño para asignarlos a cada configuración:

    + +

    res/layout/onepane.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} + +

    res/layout/onepane_with_bar.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    res/layout/twopanes.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    res/layout/twopanes_narrow.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes_narrow.xml all} + +

    Una vez que se hayan definido todos los diseños posibles, solo se debe asignar el diseño adecuado a cada configuración a través de calificadores de configuración. Ahora ya puedes utilizar la técnica de los alias de diseño:

    + +

    res/values/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values/layouts.xml all} + +

    res/values-sw600dp-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-land/layouts.xml +all} + +

    res/values-sw600dp-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-port/layouts.xml +all} + +

    res/values-large-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-land/layouts.xml all} + +

    res/values-large-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-port/layouts.xml all} + + + +

    Cómo utilizar mapas de bits de la clase NinePatch

    + +

    Admitir diferentes tamaños de pantalla normalmente implica que las fuentes de imagen también deben poder adaptarse a varios tamaños. Por ejemplo, un fondo de botón debe adaptarse a cualquier forma de botón a la que se aplique.

    + +

    Si utilizas imágenes sencillas en componentes que pueden cambiar de tamaño, observarás rápidamente que los resultados no es que sean precisamente impresionantes, ya que las imágenes se estirarán o estrecharán. La solución es utilizar mapas de bits de la clase NinePatch, que son archivos PNG con un formato especial que indican las áreas que se pueden y no se pueden estirar.

    + +

    Por tanto, al diseñar mapas de bits que se vayan a utilizar en componentes con tamaño variable, utiliza siempre mapas de bits de la clase NinePatch. Para convertir un mapa de bits en uno de la clase NinePatch, puedes empezar con una imagen normal (consulta la figura 4, que se ha ampliado cuatro veces para obtener una mayor claridad).

    + + +

    Figura 4. button.png

    + +

    A continuación, puedes pasar a la utilidad draw9patch del SDK (que se localiza en el directorio tools/) en la que puedes marcar las áreas que se deben estirar dibujando píxeles a lo largo de los bordes superior e izquierdo. También puedes marcar el área que debe incluir el contenido dibujando píxeles a lo largo de los bordes inferior y derecho, como se muestra en la figura 5.

    + + +

    Figura 5. button.9.png

    + +

    Observa los píxeles de color negro situados junto a los bordes. Los que aparecen en los bordes superior e izquierdo indican los lugares en los que se puede estirar la imagen, mientras que los que aparecen en los bordes inferior y derecho indican dónde se debe situar el contenido.

    + +

    Además, observa la extensión .9.png. Debes utilizar esta extensión, ya que, de este modo, el marco detecta que se trata de una imagen de la clase NinePatch, en lugar de una imagen PNG normal.

    + +

    Cuando aplicas este fondo a un componente (definiendo android:background="@drawable/button"), el marco estira la imagen de forma adecuada para adaptarla al botón, como se muestra en varios tamaños de la figura 6.

    + + +

    Figura 6. Botón que utiliza la clase NinePatch button.9.png en varios tamaños

    + diff --git a/docs/html/intl/ja/guide/developing/eclipse-adt.jd b/docs/html/intl/ja/guide/developing/eclipse-adt.jd index 397c0068ab75..2cd69496145e 100644 --- a/docs/html/intl/ja/guide/developing/eclipse-adt.jd +++ b/docs/html/intl/ja/guide/developing/eclipse-adt.jd @@ -29,8 +29,8 @@ page.title=Eclipse 内で ADT を使用
  • プロジェクトを、ユーザーに配布可能な署名済みの APK 形式でエクスポートすることもできます。
  • -

    ADT を組み込んだ Eclipse 総合開発環境で Android アプリケーションの開発を始めるには、最初に Eclipse 総合開発環境をダウンロードしてから、ADT プラグインをダウンロードしてインストールする必要があります。そのためには、Eclipse 用 ADT プラグインのインストールに記載されている手順どおりに操作します。

    -

    バージョン 0.9 より前の ADT を使用してアプリケーションを既に開発中の場合は、必ず最新バージョンにアップグレードしてから続行してください。Eclipse ADT プラグインをアップデートするためのガイドをご覧ください。

    +

    ADT を組み込んだ Eclipse 総合開発環境で Android アプリケーションの開発を始めるには、最初に Eclipse 総合開発環境をダウンロードしてから、ADT プラグインをダウンロードしてインストールする必要があります。そのためには、Eclipse 用 ADT プラグインのインストールに記載されている手順どおりに操作します。

    +

    バージョン 0.9 より前の ADT を使用してアプリケーションを既に開発中の場合は、必ず最新バージョンにアップグレードしてから続行してください。Eclipse ADT プラグインをアップデートするためのガイドをご覧ください。

    注: このガイドでは、ADT プラグインの最新バージョンを使用していることを前提としています。説明の大半は、以前のバージョンにも当てはまりますが、以前のバージョンを使用している場合は、このドキュメントのオンライン版ではなく、SDK パッケージに付属された資料内の同ドキュメントをご覧ください。

    @@ -84,9 +84,9 @@ page.title=Eclipse 内で ADT を使用

    アプリケーションの実行

    -

    注意してください。アプリケーションを Android エミュレータで実行する前に、Android 仮想デバイス(AVD)を作成する必要があります。AVD では、エミュレータで使用する Android プラットフォームを指定します。詳しくは Android 仮想デバイス のドキュメントをご覧ください。ただし、すぐにアプリケーションを実行したい場合は、次の簡単な手順に従って AVD を作成してください。

    +

    注意してください。アプリケーションを Android エミュレータで実行する前に、Android 仮想デバイス(AVD)を作成する必要があります。AVD では、エミュレータで使用する Android プラットフォームを指定します。詳しくは Android 仮想デバイス のドキュメントをご覧ください。ただし、すぐにアプリケーションを実行したい場合は、次の簡単な手順に従って AVD を作成してください。

    -

    携帯端末の実機でのみアプリケーションを実行する場合は、AVD は必要ありません。この場合のアプリケーションの実行について詳しくは、Developing On a Device をご覧ください。

    +

    携帯端末の実機でのみアプリケーションを実行する場合は、AVD は必要ありません。この場合のアプリケーションの実行について詳しくは、Developing On a Device をご覧ください。

    AVD の作成

    @@ -119,7 +119,7 @@ id:2

    これで AVD が作成できました。次のセクションでは、エミュレータでアプリケーションを起動する際に、AVD がどのように使用されるかについて説明します。

    -

    AVD の作成と管理について詳しくは、Android 仮想デバイス のドキュメントをご覧ください。

    +

    AVD の作成と管理について詳しくは、Android 仮想デバイス のドキュメントをご覧ください。

    アプリケーションの実行

    @@ -193,7 +193,7 @@ id:2

    Android アプリケーションの開発を始めると、Android アプリケーションをシステムがエミュレータや実機にインストールする前に、どの Android アプリケーションにもデジタル署名が必要であることがわかります。署名には、デバッグ キーを使用する方法(エミュレータや開発用端末ですぐにテストする場合)と、非公開キーを使用する方法(アプリケーションを配布する場合)の 2 つがあります。

    ADT プラグインでは、アプリケーションをエミュレータや開発用端末にインストールする前に、.apk ファイルがデバッグ キーを使用して署名されるので、開発を早めることができます。つまり、独自の非公開キーを生成する必要がなく、Eclipse からアプリケーションをすぐに実行できます。Keytool に ADT がアクセスできれば、デベロッパーが特に操作する必要はありません。ただし、アプリケーションを公開する場合は、SDK ツールが生成するデバッグ キーではなく、独自の非公開キーを使用してアプリケーションに署名する必要があります

    -

    アプリケーションへの署名をご覧ください。Android でのアプリケーションへの署名と、Android アプリケーション デベロッパーにとっての署名の意味について説明しています。このドキュメントには、ADT のエクスポート ウィザードを使用してアプリケーションをエクスポートし、署名するためのガイドも含まれています。

    +

    アプリケーションへの署名をご覧ください。Android でのアプリケーションへの署名と、Android アプリケーション デベロッパーにとっての署名の意味について説明しています。このドキュメントには、ADT のエクスポート ウィザードを使用してアプリケーションをエクスポートし、署名するためのガイドも含まれています。

    Eclipse のヒント

    @@ -224,7 +224,7 @@ id:2

    DDMS の手動による実行

    -

    ADT プラグインを使用するデバッグをおすすめしますが、手動で DDMS を実行し、ポート 8700 でデバッグするように Eclipse を設定することができます(注: 最初に必ず DDMS を起動してください)。

    +

    ADT プラグインを使用するデバッグをおすすめしますが、手動で DDMS を実行し、ポート 8700 でデバッグするように Eclipse を設定することができます(注: 最初に必ず DDMS を起動してください)。

    + +
    +
    電池残量と充電状態の監視
    +
    アプリの更新頻度を変更するために現在の電池残量や充電状態の変化を特定および監視する方法を学習します。
    + +
    ホルダーの装着状態とタイプの特定と監視
    +
    最適な更新頻度は、ホスト端末がどのように使用されているかによって異なります。ホルダーの装着状態とタイプに応じてアプリの動作を変更するために、これらを特定および監視する方法を学習します。
    + +
    接続状態の特定と監視
    +
    インターネットに接続していないときは、オンライン ソースからアプリを更新することはできません。接続状態を調べ、それに応じてバックグラウンド更新の頻度を変更する方法を学習します。また、大量の帯域幅を消費する処理を開始する前に接続が Wi-Fi かモバイル データかを調べる方法も学習します。
    + +
    オンデマンドでのブロードキャスト レシーバ操作
    +
    マニフェスト内で宣言したブロードキャスト レシーバのオンとオフを実行時に切り替えます。端末の状態に応じて、不要なレシーバを無効にすることができます。効率を上げるために、状態変化レシーバのオンとオフを切り替える方法や、端末が特定の状態になるまでアクションを延期する方法を学習します。
    +
    \ No newline at end of file diff --git a/docs/html/intl/ja/training/monitoring-device-state/manifest-receivers.jd b/docs/html/intl/ja/training/monitoring-device-state/manifest-receivers.jd new file mode 100644 index 000000000000..7635d9f87c02 --- /dev/null +++ b/docs/html/intl/ja/training/monitoring-device-state/manifest-receivers.jd @@ -0,0 +1,50 @@ +page.title=オンデマンドでのブロードキャスト レシーバ操作 +parent.title=電池消費量の最適化 +parent.link=index.html + +trainingnavtop=true + +previous.title=接続状態の特定と監視 +previous.link=connectivity-monitoring.html + +@jd:body + + + +

    端末の状態変化を監視する最も単純な方法は、監視対象とする状態ごとに {@link android.content.BroadcastReceiver} を作成し、それぞれをアプリのマニフェスト内で登録するというものです。これらの各レシーバ内で、端末の現在の状態に基づいて反復アラームのスケジュールを再設定します。

    + +

    この方法のデメリットは、これらのレシーバのいずれかがトリガされるたびに端末がスリープから復帰することですが、このことは必要以上に頻繁に発生する可能性があります。

    + +

    これよりも良い方法は、実行時にブロードキャスト レシーバをオンまたはオフにするというものです。このようにすれば、マニフェスト内で宣言したレシーバを受動的アラームとして使用できます。つまり、このアラームは、必要なときにだけシステム イベントによって呼び出されます。

    + + +

    効率を上げるために状態変化レシーバのオンとオフを切り替える

    + +

    {@link android.content.pm.PackageManager} を使用すると、マニフェスト内で定義されているコンポーネントの有効化状態を切り替えることができます。このコンポーネントにはブロードキャスト レシーバも該当するので、次に示すようにオンとオフを切り替えることができます。

    + +
    ComponentName receiver = new ComponentName(context, myReceiver.class);
    +
    +PackageManager pm = context.getPackageManager();
    +
    +pm.setComponentEnabledSetting(receiver,
    +        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    +        PackageManager.DONT_KILL_APP)
    + +

    この手法を使用すれば、接続が失われたことが判明した場合に、接続状態変化レシーバ以外のレシーバをすべて無効にすることができます。逆に、接続が確立された後は、接続状態変化の受信を停止します。オンラインかどうかを調べるのは、更新を実行する直前や、反復更新アラームのスケジュール再設定の直前だけで十分です。

    + +

    同じ手法を使用して、大量の帯域幅を必要とするダウンロードを延期することもできます。それには、接続状態の変化をリッスンするブロードキャスト レシーバを有効にしておき、端末が Wi-Fi に接続されたらダウンロードを開始します。

    diff --git a/docs/html/intl/ja/training/multiscreen/adaptui.jd b/docs/html/intl/ja/training/multiscreen/adaptui.jd new file mode 100644 index 000000000000..8b1e6acdee05 --- /dev/null +++ b/docs/html/intl/ja/training/multiscreen/adaptui.jd @@ -0,0 +1,212 @@ +page.title=順応性のある UI フローの実装 +parent.title=複数画面のデザイン +parent.link=index.html + +trainingnavtop=true +previous.title=さまざまな画面密度のサポート +previous.link=screendensities.html + +@jd:body + + + + + +

    アプリが現在表示しているレイアウトによって、UI フローが異なる可能性があります。たとえば、アプリがデュアルペイン モードであれば、左ペインのアイテムをクリックすると、単に右ペインにコンテンツが表示されるだけですが、シングルペイン モードであれば、コンテンツは(別のアクティビティ内の)コンテンツ専用のペインに表示される必要があります。

    + + +

    現在のレイアウトを判別する

    + +

    レイアウトによって実装が多少異なるので、まず、ユーザーが現在どのようなレイアウトを表示しているかを判別する必要があります。たとえば、ユーザーが表示しているレイアウトが「シングルペイン」モードなのか、「デュアルペイン」モードなのかを確認する必要があります。それは、以下のようなコードで、ある特定のビューが存在し、かつ可視になっているかを照会することで可能です:

    + +
    +public class NewsReaderActivity extends FragmentActivity {
    +    boolean mIsDualPane;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main_layout);
    +
    +        View articleView = findViewById(R.id.article);
    +        mIsDualPane = articleView != null && 
    +                        articleView.getVisibility() == View.VISIBLE;
    +    }
    +}
    +
    + +

    このコードにおいて「article」ペインが使用可能かどうかを照会している点に注目してください。特定のレイアウトの照会をハードコーディングするよりもはるかに柔軟性があります。

    + +

    その他にも、さまざまなコンポーネントでも対応できる方法として、コンポーネントを操作する前に使用可能かどうかを確認する方法もあります。たとえば、News Reader サンプル アプリでは、メニューを開くボタンがありますが、このボタンは Android 3.0 よりも古いバージョンで動作しているときにしか表示されません(この機能は、API レベル 11 以上の {@link android.app.ActionBar} で提供されるため)。そこで、以下のようなコードを追加して、このボタンのイベント リスナーを追加します:

    + +
    +Button catButton = (Button) findViewById(R.id.categorybutton);
    +OnClickListener listener = /* create your listener here */;
    +if (catButton != null) {
    +    catButton.setOnClickListener(listener);
    +}
    +
    + + +

    現在のレイアウトに合わせて応答する

    + +

    現在のレイアウトによって、一部のアクションの結果が異なる可能性があります。たとえば、News Reader サンプルでは、見出しリストで見出しをクリックしたとき、デュアルペイン モードの UI の場合は右ペインに記事が表示されますが、シングルペインの UI の場合は別のアクティビティが起動します:

    + +
    +@Override
    +public void onHeadlineSelected(int index) {
    +    mArtIndex = index;
    +    if (mIsDualPane) {
    +        /* display article on the right pane */
    +        mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
    +    } else {
    +        /* start a separate activity */
    +        Intent intent = new Intent(this, ArticleActivity.class);
    +        intent.putExtra("catIndex", mCatIndex);
    +        intent.putExtra("artIndex", index);
    +        startActivity(intent);
    +    }
    +}
    +
    + +

    同様に、アプリがデュアルペイン モードの場合は、ナビ用タブでアクション バーを設定し、一方、シングルペイン モードの場合は、スピナー ウィジェットでナビを設定することになります。したがって、コードでは以下のようにどちらのケースが適切かを調べることも必要です:

    + +
    +final String CATEGORIES[] = { "トップ ニュース 政治", "政治", "経済", "Technology" };
    +
    +public void onCreate(Bundle savedInstanceState) {
    +    ....
    +    if (mIsDualPane) {
    +        /* use tabs for navigation */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
    +        int i;
    +        for (i = 0; i < CATEGORIES.length; i++) {
    +            actionBar.addTab(actionBar.newTab().setText(
    +                CATEGORIES[i]).setTabListener(handler));
    +        }
    +        actionBar.setSelectedNavigationItem(selTab);
    +    }
    +    else {
    +        /* use list navigation (spinner) */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
    +        SpinnerAdapter adap = new ArrayAdapter(this, 
    +                R.layout.headline_item, CATEGORIES);
    +        actionBar.setListNavigationCallbacks(adap, handler);
    +    }
    +}
    +
    + + +

    他のアクティビティのフラグメントを再利用する

    + +

    複数の画面に対応するように設計する場合、あるパターンが繰り返されますが、そうしたパターンは、ある画面設定ではペインとして、別の画面設定では別のアクティビティとして実装されるインターフェースの一部に存在します。たとえば、News Reader サンプルでは、ラージ画面の場合はニュース記事のテキストが右ペインに表示されますが、それよりも小さい画面の場合は別のアクティビティになります。

    + +

    このような場合、通常、複数のアクティビティで同じ {@link android.app.Fragment} サブクラスを再利用することでコードの重複を回避できます。たとえば、ArticleFragment は以下のようにデュアルペイン レイアウトで使用されます:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    また、より小さな画面向けのアクティビティ レイアウト内では(レイアウトを使用せずに)再利用されます(ArticleActivity):

    + +
    +ArticleFragment frag = new ArticleFragment();
    +getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
    +
    + +

    当然、これは XML レイアウトでフラグメントを宣言するのと同じ効果がありますが、この場合は、XML レイアウトは必要ありません。このアクティビティのコンポーネントは記事フラグメントしかないからです。

    + +

    フラグメントを設計する際に注意すべき非常に重要なポイントの 1 つとして、特定のアクティビティに対して強い結合を作成しないことがあります。通常、これは、フラグメントが自分のホスト アクティビティとやり取りするのに必要なあらゆる手段を抽象化したインターフェースを定義し、さらに、そのインターフェースをホスト アクティビティに実装することで可能になります:

    + +

    たとえば、News Reader アプリの HeadlinesFragment は、まさにそのようになっています:

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    OnHeadlineSelectedListener mHeadlineSelectedListener = null;
    +
    +    /* Must be implemented by host activity */
    +    public interface OnHeadlineSelectedListener {
    +        public void onHeadlineSelected(int index);
    +    }
    +    ...
    +
    +    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
    +        mHeadlineSelectedListener = listener;
    +    }
    +}
    +
    + +

    これにより、ユーザーが見出しを選択すると、フラグメントは以下のように(特定のハードコーディングされたアクティビティに通知するのではなく)ホスト アクティビティが指定したリスナーに通知します:

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    @Override
    +    public void onItemClick(AdapterView<?> parent, 
    +                            View view, int position, long id) {
    +        if (null != mHeadlineSelectedListener) {
    +            mHeadlineSelectedListener.onHeadlineSelected(position);
    +        }
    +    }
    +    ...
    +}
    +
    + +

    このテクニックについては、タブレットと携帯端末のサポートで詳しく説明されています。

    + + +

    画面設定の変更を処理する

    + +

    インターフェースの各パーツを実装するのに個別のアクティビティを使用している場合、インターフェースの一貫性を維持するために、(向きの変更などの)特定の設定変更に対応できるように注意する必要があります。

    + +

    たとえば、Android 3.0 以上が動作する一般的な 7 インチ タブレットでは、News Reader サンプルがニュース記事を表示する場合、縦表示では個別のアクティビティを使用しますが、横表示では 2 ペイン レイアウトを使用します。

    + +

    つまり、縦表示のときに記事閲覧用アクティビティが画面上にある場合、画面の向きが横方向に変わったことを検出したら、コンテンツを 2 ペイン レイアウトで表示するために、そのアクティビティを終了してメインのアクティビティに戻り、適切に応答しなければなりません:

    + +
    +public class ArticleActivity extends FragmentActivity {
    +    int mCatIndex, mArtIndex;
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
    +        mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
    +
    +        // If should be in two-pane mode, finish to return to main activity
    +        if (getResources().getBoolean(R.bool.has_two_panes)) {
    +            finish();
    +            return;
    +        }
    +        ...
    +}
    +
    + + diff --git a/docs/html/intl/ja/training/multiscreen/index.jd b/docs/html/intl/ja/training/multiscreen/index.jd new file mode 100644 index 000000000000..ff84f8a718e6 --- /dev/null +++ b/docs/html/intl/ja/training/multiscreen/index.jd @@ -0,0 +1,64 @@ +page.title=複数画面のデザイン + +trainingnavtop=true +startpage=true +next.title=さまざまな画面サイズのサポート +next.link=screensizes.html + +@jd:body + +
    +
    + +

    必要な知識と前提条件

    + + + +

    関連ドキュメント

    + + + +

    試してみる

    + + + +
    +
    + +

    Android は、小さな携帯電話から大きなテレビまで、画面サイズも種類もさまざまなデバイスに搭載できます。そのため、できる限り多くのユーザーが使用できるように、すべての画面サイズに対応できるようアプリを設計することが重要になります。

    + +

    しかし、さまざまな種類のデバイスに対応できるだけでは十分ではありません。画面サイズによって、ユーザーが操作できることが決まってくるため、本当にユーザーを満足させてよい印象を持ってもらうためには、アプリが単に複数の画面をサポートするだけでは不十分です: 画面設定ごとにユーザー エクスペリエンスを最適化する必要があります。

    + +

    このクラスは、いくつかの画面設定に合わせて最適化されたユーザー インターフェースを実装する方法を提供します。

    + +

    各レッスンで紹介されているコードは、複数の画面に合わせて最適化する際、ベスト プラクティスとなるサンプル アプリから抜粋したものです。このサンプルを(右側から)ダウンロードして、再利用可能なコードのソースとしてご自分のアプリに使用することができます。

    + +

    注: このクラスと関連サンプルでは、サポート ライブラリを使用します。理由は、Android 3.0 未満のバージョンで {@link android.app.Fragment} API を使用するためです。このクラスのすべての API を使用するには、ライブラリをダウンロードして、アプリに追加する必要があります。

    + + +

    レッスン

    + +
    +
    さまざまな画面サイズのサポート
    +
    このレッスンでは、さまざまな画面サイズに適したレイアウトを(柔軟なビュー サイズ、 {@link android.widget.RelativeLayout}、画面サイズと画面の向きの修飾子、エイリアス フィルタ、ナインパッチ ビットマップを使用して)設計する方法について学習します。
    + +
    さまざまな画面密度のサポート
    +
    このレッスンでは、(密度非依存ピクセルを使用し、各密度に適したビットマップを提供して)ピクセル密度が異なる画面をサポートする方法について学習します。
    + +
    順応性のある UI フローの実装
    +
    このレッスンでは、いくつかの画面サイズ/密度の組み合わせに適した方法(実行時にアクティブなレイアウトを検出する方法、現在のレイアウトに合わせて応答する方法、画面設定の変更を処理する方法)で UI を実装する方法について学習します。
    +
    diff --git a/docs/html/intl/ja/training/multiscreen/screendensities.jd b/docs/html/intl/ja/training/multiscreen/screendensities.jd new file mode 100644 index 000000000000..3482d5c5117e --- /dev/null +++ b/docs/html/intl/ja/training/multiscreen/screendensities.jd @@ -0,0 +1,100 @@ +page.title=さまざまな画面密度のサポート +parent.title=複数画面のデザイン +parent.link=index.html + +trainingnavtop=true +previous.title=さまざまな画面サイズのサポート +previous.link=screensizes.html +next.title=順応性のある UI フローの実装 +next.link=adaptui.html + +@jd:body + + + +
    +
    + +

    このレッスンでの学習内容

    +
      +
    1. 密度非依存ピクセルを使用する
    2. +
    3. 代替ビットマップを生成する
    4. +
    + +

    関連ドキュメント

    + + + +

    試してみる

    + + + + +
    +
    + +

    このレッスンでは、異なるリソースを生成し、かつ解像度非依存単位を使用して、異なる画面密度をサポートする方法について学習します。

    + +

    密度非依存ピクセルを使用する

    + +

    レイアウトを設計する際に回避すべきよくある落とし穴の 1 つとして、絶対ピクセルを使用して距離やサイズを定義することがあります。ピクセルを使用してレイアウトのサイズを定義すると、画面によってピクセル密度が異なるため、問題が起こります。したがって、同じピクセル数では、デバイスが異なる場合に物理サイズが異なる可能性があります。そのため、サイズを指定する場合は、常に dp 単位や sp 単位を使用します。dp とは、1 ピクセルの物理サイズが 160 dpi に相当する密度非依存ピクセルです。sp も基本単位は同じですが、ユーザーの優先テキスト サイズによってサイズが決まるので(スケール非依存ピクセル)、テキスト サイズを定義する際にはこの単位を使用する必要があります(ただし、レイアウト サイズには絶対に使用しないこと)。

    + +

    たとえば、2 つのビューの間にスペースを挿入する場合は、px ではなくて dp を使用します:

    + +
    +<Button android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content" 
    +    android:text="@string/clickme"
    +    android:layout_marginTop="20dp" />
    +
    + +

    テキスト サイズを指定する場合は、常に sp を使用します:

    + +
    +<TextView android:layout_width="match_parent" 
    +    android:layout_height="wrap_content" 
    +    android:textSize="20sp" />
    +
    + + +

    代替ビットマップを生成する

    + +

    Android は、画面密度がさまざまなデバイスで動作するため、それぞれの汎用密度バケット(低密度、中密度、高密度、超高密度)に合わせてビットマップ リソースを生成する必要があります。そうすることで、すべての画面密度で画質とパフォーマンスが向上します。

    + +

    これらの画像を生成するには、ベクター形式の未加工リソースから、次のサイズ スケールを使用して密度別に画像を生成する必要があります:

    + +

      +
    • xhdpi: 2.0 +
    • hdpi: 1.5 +
    • mdpi: 1.0(基準) +
    • ldpi: 0.75 +

    + +

    つまり、200×200 画像(xhdpi デバイス用)を生成する場合、同じリソースを 150×150 画像(hdpi デバイス用)、100×100 画像(mdpi デバイス用)、75×75(ldpi デバイス用)でも生成する必要があります。

    + +

    さらに、生成した画像を res/ 下の適切なサブディレクトリに配置することで、アプリが動作するデバイスの画面密度に基づいて、自動的に適切な画像が表示されます:

    + +
    +MyProject/
    +  res/
    +    drawable-xhdpi/
    +        awesomeimage.png
    +    drawable-hdpi/
    +        awesomeimage.png
    +    drawable-mdpi/
    +        awesomeimage.png
    +    drawable-ldpi/
    +        awesomeimage.png
    +
    + +

    また、@drawable/awesomeimage を参照する場合は常に画面の dpi に基づいて、適切なビットマップが選択されます。

    + +

    アプリ用のアイコン アセットを作成するためのヒントとガイドラインについては、アイコン設計のガイドラインをご覧ください。

    + diff --git a/docs/html/intl/ja/training/multiscreen/screensizes.jd b/docs/html/intl/ja/training/multiscreen/screensizes.jd new file mode 100644 index 000000000000..3655a33be2b9 --- /dev/null +++ b/docs/html/intl/ja/training/multiscreen/screensizes.jd @@ -0,0 +1,279 @@ +page.title=さまざまな画面サイズのサポート +parent.title=複数画面のデザイン +parent.link=index.html + +trainingnavtop=true +next.title=さまざまな画面密度のサポート +next.link=screendensities.html + +@jd:body + + + + + +

    このレッスンでは、異なる画面サイズを以下のような方法でサポートする方法について学習します:

    +
      +
    • 画面に収まるようにレイアウト サイズを適切に変更する
    • +
    • 画面設定に基づいて適切な UI レイアウトを表示する
    • +
    • 適切な画面に適切なレイアウトを適用する
    • +
    • 適切にサイズ調整したビットマップを表示する
    • +
    + + +

    「wrap_content」と「match_parent」を使用する

    + +

    レイアウトをさまざまな画面サイズに柔軟に対応させるには、一部のビュー コンポーネントの幅と高さに "wrap_content""match_parent" を使用する必要があります。"wrap_content" を使用すると、ビューの幅や高さがそのビュー内にコンテンツが収まるのに必要な最小サイズに設定されます。一方、"match_parent"(API レベル 8 より前の名称は "fill_parent")を使用すると、コンポーネントがその親ビューのサイズに一致するまで拡大されます。

    + +

    ハードコーディングされたサイズの代わりに "wrap_content""match_parent" を使用することで、ビューはそれぞれ、そのビューに必要なスペースだけを使用したり、空きスペースを埋めるまで拡大したりします。次に例を示します:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    このサンプルでは、特定のサイズではない "wrap_content""match_parent" をコンポーネント サイズにどのように使用しているかに注目してください。こうすることで、異なる画面のサイズと向きにレイアウトを正しく対応させることができます。

    + +

    たとえば、このレイアウトを縦表示と横表示で表示したときの見え方を以下に示します。コンポーネントのサイズが幅と高さに自動的に適合している点に注目してください:

    + + +

    図 1. News Reader サンプル アプリの縦表示(左)と横表示(右)

    + + +

    RelativeLayout を使用する

    + +

    ネストされた {@link android.widget.LinearLayout} インスタンスや、 "wrap_content""match_parent" のサイズの組み合わせを使用すると、かなり複雑なレイアウトを作成できます。しかし、 {@link android.widget.LinearLayout} では、子ビューの空間的な位置関係を正確に制御することはできません。 {@link android.widget.LinearLayout} のビューは、 単に一列に並ぶだけです。子ビューに対して直線以外のさまざまな配置を実現する必要がある場合は、 {@link android.widget.RelativeLayout}を使用することでうまくいくことがよくあります。たとえば、1 つの子ビューを画面の左側に配置し、もう 1 つの子ビューを右側に配置できます。

    + +

    次に例を示します:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="match_parent"
    +    android:layout_height="match_parent">
    +    <TextView
    +        android:id="@+id/label"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:text="Type here:"/>
    +    <EditText
    +        android:id="@+id/entry"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/label"/>
    +    <Button
    +        android:id="@+id/ok"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/entry"
    +        android:layout_alignParentRight="true"
    +        android:layout_marginLeft="10dp"
    +        android:text="OK" />
    +    <Button
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_toLeftOf="@id/ok"
    +        android:layout_alignTop="@id/ok"
    +        android:text="Cancel" />
    +</RelativeLayout>
    +
    + +

    図 2 は、このレイアウトの QVGA 画面での見え方を示しています。

    + + +

    図 2. QVGA 画面(スモール画面)のスクリーンショット

    + +

    図 3 は、このレイアウトのラージ画面での見え方を示しています。

    + + +

    図 3. WSVGA 画面(ラージ画面)のスクリーンショット

    + +

    コンポーネントのサイズが変更されても、 {@link android.widget.RelativeLayout.LayoutParams}で指定されたとおりに空間的な位置関係が維持されていることがわかります。

    + + +

    サイズ修飾子を使用する

    + +

    柔軟なレイアウトや相対的なレイアウトから得られる恩恵は、前のセクションで説明したことくらいです。これらのレイアウトはコンポーネントの内部や周囲のスペースを引き延ばすことでさまざまな画面に対応しますが、それぞれの画面サイズに合った最高のユーザー エクスペリエンスを実現していない可能性があります。したがって、アプリでは、柔軟なレイアウトの実装だけではなく、さまざまな画面設定に合わせた複数の代替レイアウトも必要になります。これは、設定修飾子を使用することで実現可能です。設定修飾子により、ランタイムが現在のデバイスの設定に基づいて適切なリソース(画面サイズ別のレイアウト デザインなど)を自動的に選択できます。

    + +

    たとえば、多くのアプリでは、ラージ画面用に「2 ペイン」パターンを実装しています(一方のペインに項目リスト、もう一方のペインにそのコンテンツを表示することが可能です)。タブレットやテレビは両方のペインを同時に表示できるほど十分に大きい画面ですが、携帯端末の画面では 2 つのペインを別々に表示する必要があります。そのようなレイアウトを実装するには、次のようなファイルが必要になります:

    + +
      +
    • res/layout/main.xml、シングルペイン(デフォルト)レイアウト: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-large/main.xml、2 ペイン レイアウト: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    2 番目のレイアウトのディレクトリ名の large 修飾子に注目してください。このレイアウトは、ラージ(7 インチ以上のタブレットなど)と分類された画面のデバイスで選択されます。それよりも小さいデバイスでは、その他のレイアウト(修飾子なし)が選択されます。

    + + +

    最小幅修飾子を使用する

    + +

    Android 3.2 未満のデバイスでデベロッパーが抱えていた問題の 1 つに、Dell Streak、初代 Galaxy Tab、7 インチ タブレット全般を含む、「ラージ」画面サイズの分類があります。しかし、多くのアプリでは、すべて「ラージ」画面と見なされたとしても、このカテゴリ内のデバイスのサイズに合わせて異なるレイアウト(5 インチと 7 インチのデバイス用など)を表示したい場合があります。そこで、Android 3.2 では「最小幅」修飾子などが導入されました。

    + +

    最小幅修飾子を使用すると、dp で指定した特定の最小幅の画面を対象とすることができます。たとえば、一般的な 7 インチ タブレットは最小幅が 600 dp なので、これらの画面の UI で 2 つのペイン(ただし、それよりも小さい画面ではシングル リスト)を表示したい場合は、前のセクションで説明した 2 つのレイアウトをシングルペイン レイアウト用と 2 ペイン レイアウト用としてそのまま利用できます。ただし、large サイズ修飾子の代わりに、sw600dp を使用して、最小幅が 600 dp の画面では 2 ペイン レイアウトになるよう指定します:

    + +
      +
    • res/layout/main.xml、シングルペイン(デフォルト)レイアウト: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-sw600dp/main.xml、2 ペイン レイアウト: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    つまり、最小幅が 600dp 以上のデバイスでは layout-sw600dp/main.xml(2 ペイン)レイアウトが選択され、それよりも小さい画面では layout/main.xml(シングルペイン)レイアウトが選択されるということです。

    + +

    ただし、Android 3.2 未満のデバイスではこの修飾子は機能しません。これは sw600dp をサイズ修飾子として認識できないためです。したがって、引き続き large 修飾子も使用する必要があります。そこで、res/layout-sw600dp/main.xml と同じ内容の res/layout-large/main.xml という名前のファイルも必要になります。次のセクションでは、このようにレイアウト ファイルの重複を避けるためのテクニックについて学習します。

    + + +

    レイアウト エイリアスを使用する

    + +

    最小幅修飾子は、Android 3.2 以上でしか利用できません。したがって、旧バージョンとの互換性を維持するために、あいまいなサイズ分類(small、normal、large、xlarge)も併用することが必要です。たとえば、携帯端末ではシングルペイン UI、7 インチ タブレットやテレビなどの大きなデバイスではマルチペイン UI を表示するよう UI を設計する場合、以下のようなファイルが必要になります:

    + +

      +
    • res/layout/main.xml: シングルペイン レイアウト
    • +
    • res/layout-large: マルチペイン レイアウト
    • +
    • res/layout-sw600dp: マルチペイン レイアウト
    • +

    + +

    最後の 2 つのファイルは同じものです。一方は Android 3.2 デバイス用で、もう一方は旧バージョンの Android を搭載したタブレットとテレビ用です。

    + +

    このようにタブレット/テレビ用として同じファイルを使用することで起こる重複(さらに、その結果メンテナンスが困難になる状況)を避けるために、エイリアス ファイルを使用できます。たとえば、次のようなレイアウトを定義できます:

    + +
      +
    • res/layout/main.xml、シングルペイン レイアウト
    • +
    • res/layout/main_twopanes.xml、2 ペイン レイアウト
    • +
    + +

    さらに、次の 2 つのファイルを追加します:

    + +

      +
    • res/values-large/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      +
    • + +
    • res/values-sw600dp/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      + +
    • +

    + +

    最後の 2 つのファイルの内容は同じですが、実際のレイアウトは定義していません。これらのファイルは、単に {@code main}{@code main_twopanes}へのエイリアスになるように設定しただけです。これらのファイルには largesw600dp セレクタが含まれているので、Android のバージョンに関係なく( +Android 3.2 未満のタブレット/テレビは {@code large} に一致し、Android 3.2 以上のタブレット/テレビは sw600dp に一致します)タブレット/テレビに適用されます。

    + + +

    画面の向きの修飾子を使用する

    + +

    横表示と縦表示が両方とも正しく表示されるレイアウトもありますが、ほとんどのレイアウトは調整が必要になります。以下に、News Reader サンプル アプリの各画面のサイズと向きでレイアウトがどのように表示されるかを示します:

    + +

      +
    • スモール画面、縦表示: シングル ペイン、ロゴ付き
    • +
    • スモール画面、横表示: シングル ペイン、ロゴ付き
    • +
    • 7 インチ タブレット、縦表示: シングル ペイン、アクション バー付き
    • +
    • 7 インチ タブレット、横表示: デュアル ペイン、ワイド、アクション バー付き
    • +
    • 10 インチ タブレット、縦表示: デュアル ペイン、ナロー、アクション バー付き
    • +
    • 10 インチ タブレット、横表示: デュアル ペイン、ワイド、アクション バー付き
    • +
    • テレビ、横表示: デュアル ペイン、ワイド、アクション バー付き
    • +

    + +

    これらの各レイアウトは、res/layout/ ディレクトリ内の XML ファイルに定義されています。各レイアウトをさまざまな画面設定に割り当てるには、アプリでレイアウト エイリアスを使用して、各設定に対応付けます:

    + +

    res/layout/onepane.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} + +

    res/layout/onepane_with_bar.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    res/layout/twopanes.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    res/layout/twopanes_narrow.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes_narrow.xml all} + +

    これで、考えられるすべてのレイアウトが定義されました。あとは、設定修飾子を使用して、適切なレイアウトを各設定にマッピングするだけです。そのためには、以下のようなレイアウト エイリアス テクニックを使用することができます:

    + +

    res/values/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values/layouts.xml all} + +

    res/values-sw600dp-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-land/layouts.xml +all} + +

    res/values-sw600dp-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-port/layouts.xml +all} + +

    res/values-large-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-land/layouts.xml all} + +

    res/values-large-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-port/layouts.xml all} + + + +

    ナインパッチ ビットマップを使用する

    + +

    異なる画面サイズをサポートするには、画像リソースも異なるサイズに対応できないといけません。たとえば、ボタンの背景は、適用されるボタンの形状が異なってもサイズが合わなければいけません。

    + +

    サイズ変更可能なコンポーネントでシンプルな画像を使用すると、ランタイムによって画像が一様に拡大縮小されるので、いくぶん期待はずれの結果になることがすぐにわかります。これは、ナインパッチ ビットマップを使用することで解決します。ナインパッチ ビットマップとは、拡大可能な領域と拡大不可能な領域が指定された特殊なフォーマットの PNG ファイルです。

    + +

    そのため、サイズが変化するコンポーネントで使用するビットマップをデザインする場合は、常にナインパッチを使用してください。ビットマップをナインパッチに変換するには、まず、通常の画像を用意します(図 4: わかりやすく 4 倍に拡大しています)。

    + + +

    図 4. button.png

    + +

    次に、 SDK の draw9patch ユーティリティ(tools/ ディレクトリにあります)からナインパッチを実行して、左境界線と上境界線上にピクセル(ドット)を描くことで拡大する領域にマークを付けます。また、右境界線と下境界線上にピクセルを描くことで、コンテンツを入れる領域をマークできます(図 5)。

    + + +

    図 5. button.9.png

    + +

    境界線上に黒いピクセルがあることに注目してください。左境界線と上境界線上のものは画像を拡大できる領域で、右境界線と下境界線上のものはコンテンツを配置する領域を示しています。

    + +

    さらに、.9.png という拡張子にも注目してください。この拡張子は必ず使用してください。そうすることで、通常の PNG 画像ではなく、ナインパッチ画像であることがフレームワークによって検出されます。

    + +

    この背景を(android:background="@drawable/button" を設定して)コンポーネントに適用すると、ボタンのサイズに合わせて適切に画像が拡大します(図 6 のさまざまなサイズを参照)。

    + + +

    図 6button.9.png ナインパッチを使用したさまざまなサイズのボタン

    + diff --git a/docs/html/intl/ko/training/monitoring-device-state/battery-monitoring.jd b/docs/html/intl/ko/training/monitoring-device-state/battery-monitoring.jd new file mode 100644 index 000000000000..2eacccf64106 --- /dev/null +++ b/docs/html/intl/ko/training/monitoring-device-state/battery-monitoring.jd @@ -0,0 +1,120 @@ +page.title=배터리 수준 및 충전 상태 모니터링 +parent.title=배터리 수명 최적화 +parent.link=index.html + +trainingnavtop=true +next.title=도킹 상태와 유형 확인 및 모니터링 +next.link=docking-monitoring.html + +@jd:body + + + +

    백그라운드 업데이트가 배터리 수명에 미치는 영향을 줄이기 위하여 백그라운드 업데이트 빈도수를 변경하는 경우, 현재 배터리 수준과 충전 상태부터 확인하는 것이 좋습니다.

    + +

    애플리케이션 업데이트 수행이 배터리 수명에 미치는 영향은 배터리 수준 및 기기의 충전 상태에 따라 다릅니다. 기기를 AC 충전기로 충전하는 동안 업데이트 수행이 미치는 영향은 무시해도 좋습니다. 따라서 기기가 범용 충전기에 연결되어 있을 때는 대부분 새로고침 빈도를 최대화할 수 있습니다. 반대로 기기가 충전 중이 아니라면, 업데이트 빈도를 줄이는 것이 배터리 수명 연장에 도움이 됩니다.

    + +

    마찬가지로 배터리가 거의 방전된 경우, 업데이트 빈도를 줄이거나 중단할 수 있습니다.

    + + +

    현재 충전 상태 확인

    + +

    먼저 현재 충전 상태를 확인하는 것부터 시작합니다. {@link android.os.BatteryManager}는 배터리 충전 상태 등 충전 정보를 스티키 {@link android.content.Intent}를 통해 브로드캐스트합니다.

    + +

    스티키 인텐트이므로 {@link android.content.BroadcastReceiver}를 등록할 필요가 없으며 아래 코드 상의 리시버와 같이 간단히 {@code registerReceiver}을(를) 호출하여 {@code null}에 제출하면 현재 배터리 상태가 담긴 인텐트가 반환됩니다. 여기에 실제 {@link android.content.BroadcastReceiver} 개체 사용할 수 있으나, 이후 섹션에서 업데이트를 다루게 되므로 그럴 필요는 없습니다.

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    +Intent batteryStatus = context.registerReceiver(null, ifilter);
    + +

    현재 충전 상태와 어떤 충전기(USB 또는 AC 전원)로 충전하는지 추출할 수 있습니다.

    + +

    // Are we charging / charged?
    +int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                     status == BatteryManager.BATTERY_STATUS_FULL;
    +
    +// How are we charging?
    +int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    + +

    일반적으로 기기가 AC 충전기에 연결된 경우 백그라운드 업데이트 빈도를 최대화합니다. USB를 통해 충전하는 경우 업데이트 빈도를 낮춥니다. 배터리가 방전 중이라면 빈도를 더 많이 낮추도록 합니다.

    + + +

    충전 상태 변경사항 모니터링

    + +

    충전 상태는 수시로 변하므로 충전 상태의 변경사항을 확인하고 이에 따라 업데이트 주기를 변경하는 것이 중요합니다.

    + +

    {@link android.os.BatteryManager}는 기기가 전원에 연결되어 있는지 여부와 관계없이 언제나 액션을 브로드캐스트합니다. 앱이 실행되지 않는 동안에도 이벤트를 수신하는 것이 중요합니다. 특히 백그라운드 업데이트를 실행하기 위해 앱을 시작하는 빈도수에 이벤트가 영향을 주기 때문입니다. 따라서 두 이벤트를 수신하려면 매니페스트에서 {@link android.content.BroadcastReceiver}를 등록하여 인텐트 필터 내에 {@link android.content.Intent#ACTION_POWER_CONNECTED}와 {@link android.content.Intent#ACTION_POWER_DISCONNECTED}를 정의해야 합니다.

    + +
    <receiver android:name=".PowerConnectionReceiver">
    +  <intent-filter>
    +    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    +    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    +  </intent-filter>
    +</receiver>
    + +

    다음의 {@link android.content.BroadcastReceiver} 구현에서 이전 단계에서 설명한 대로 현재 충전 상태와 방법을 알아낼 수 있습니다.

    + +
    public class PowerConnectionReceiver extends BroadcastReceiver {
    +    @Override
    +    public void onReceive(Context context, Intent intent) { 
    +        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                            status == BatteryManager.BATTERY_STATUS_FULL;
    +    
    +        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +        boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +        boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    +    }
    +}
    + + +

    현재 배터리 수준 확인

    + +

    현재 배터리 수준을 확인하는 것이 유용한 경우도 있습니다. 배터리 충전이 수준 이하인 경우 백그라운드 업데이트 빈도를 줄일 수 있습니다.

    + +

    다음은 배터리 상태 정보가 담긴 인텐트에서 현재 배터리 수준 및 충전 상태를 추출하는 방법입니다.

    + +
    int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    +int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    +
    +float batteryPct = level / (float)scale;
    + + +

    배터리 수준 중요 변경사항 모니터링

    + +

    배터리 상태를 지속적으로 확인하는 것은 쉽지 않지만, 꼭 그럴 필요도 없습니다.

    + +

    배터리 수준을 지속적으로 모니터링하는 것은 앱의 다른 작업보다 배터리에 더 큰 영향을 미칩니다. 따라서 기기가 배터리 전원 부족 상태가 되거나 이를 벗어날 때 등 중요한 변경사항만 확인하는 것이 좋습니다.

    + +

    다음 코드는 매니페스트의 브로드캐스트 리시버 내의 인텐트 필터를 보여줍니다. 배터리가 얼마 남지 않거나{@link android.content.Intent#ACTION_BATTERY_LOW} 배터리 상태가 회복되었을 때{@link android.content.Intent#ACTION_BATTERY_OKAY} 전달되는 메시지를 수신할 수 있습니다.

    + +
    <receiver android:name=".BatteryLevelReceiver">
    +<intent-filter>
    +  <action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
    +  <action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
    +  </intent-filter>
    +</receiver>
    + +

    배터리 충전 상태가 매우 낮은 경우 백그라운드 업데이트를 사용하지 않는 것이 좋습니다. 전화기가 꺼져버리면 최신 데이터를 제공하는 것이 의미가 없기 때문입니다.

    + +

    기기를 충전하는 것은 곧 기기를 도크에 집어넣는 것과 같은 경우가 많습니다. 다음 강의는 현재 도크 상태를 확인하고 기기 도킹의 변경사항을 모니터링하는 방법을 보여줍니다.

    + diff --git a/docs/html/intl/ko/training/monitoring-device-state/connectivity-monitoring.jd b/docs/html/intl/ko/training/monitoring-device-state/connectivity-monitoring.jd new file mode 100644 index 000000000000..5666b98c9045 --- /dev/null +++ b/docs/html/intl/ko/training/monitoring-device-state/connectivity-monitoring.jd @@ -0,0 +1,70 @@ +page.title=연결 상태 확인 및 모니터링 +parent.title=배터리 수명 최적화 +parent.link=index.html + +trainingnavtop=true + +previous.title=도킹 상태와 유형 확인 및 모니터링 +previous.link=docking-monitoring.html +next.title=온디맨드로 브로드캐스트 수신기 조작 +next.link=manifest-receivers.html + +@jd:body + + + +

    반복 알람과 백그라운드 서비스는 일반적으로 인터넷 리소스 및 캐시 데이터로부터 애플리케이션의 업데이트를 예약하거나 긴 시간이 필요한 다운로드를 실행하는 데 사용됩니다. 하지만 인터넷에 연결되어 있지 않거나 연결이 매우 느려 다운로드를 완료하지 못한다면 업데이트 예약을 해도 소용이 없겠죠?

    + +

    인터넷에 연결되었는지, 어떤 연결 방식인지를 확인하기 위하여 {@link android.net.ConnectivityManager}를 사용할 수 있습니다.

    + + +

    인터넷에 연결되어 있는지 확인

    + +

    인터넷에 연결되어 있지 않는 경우 인터넷 리소스를 기반으로 한 업데이트 예약을 할 필요가 없습니다. 다음은 활성 네트워크를 쿼리하고 인터넷이 연결되어 있는지 확인하기 위한 {@link android.net.ConnectivityManager} 사용법을 보여줍니다.

    + +
    ConnectivityManager cm =
    +        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    + 
    +NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    +boolean isConnected = activeNetwork.isConnectedOrConnecting();
    + + +

    인터넷 연결 유형 확인

    + +

    현재 사용할 수 있는 인터넷 연결 유형을 확인할 수도 있습니다.

    + +

    연결은 모바일 데이터, WiMAZ, Wi-Fi 및 이더넷 연결을 통해 제공될 수 있습니다. 아래와 같이 활성 네트워크의 유형을 쿼리하면, 사용 가능한 대역폭에 따라 업데이트 빈도를 변경할 수 있습니다.

    + +
    boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
    + +

    모바일 데이터 비용은 Wi-Fi보다 높은 경향이 있으므로, 모바일 연결인 경우 앱의 업데이트 빈도를 줄여야 합니다. 마찬가지로 Wi-Fi로 연결되기까지 큰 용량의 다운로드는 일시 중지해야 합니다.

    + +

    업데이트를 비활성화한 경우, 인터넷 연결이 재개되면 업데이트를 다시 시작하기 위해 연결 변경사항을 알고 있는 것이 중요합니다.

    + + +

    연결 변경사항 모니터링

    + +

    연결 정보가 변경될 때마다 {@link android.net.ConnectivityManager}는 {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION}({@code "android.net.conn.CONNECTIVITY_CHANGE"}) 액션을 브로드캐스트합니다. 변경사항을 수신하거나 적절히 백그라운드 업데이트를 다시 시작 또는 일시 중지하기 위해 매니페스트에서 브로드캐스트 리시버를 등록할 수 있습니다.

    + +
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    + +

    연결 정보는 수시로 변경될 수 있습니다. 모바일과 Wi-Fi 간에 이동할 때마다 브로드캐스트가 실행됩니다. 따라서 업데이트나 다운로드를 일시 중지한 경우에만 브로드캐스트를 확인하는 것이 좋습니다. 업데이트를 시작하기 전이나 이전에 업데이트를 일시 중지했던 경우에만 확인하는 것으로 충분합니다.

    + +

    이 기술은 다음 강의에서 설명하는 매니페스트에서 선언한 브로드캐스트 리시버의 전환이 필요합니다.

    diff --git a/docs/html/intl/ko/training/monitoring-device-state/docking-monitoring.jd b/docs/html/intl/ko/training/monitoring-device-state/docking-monitoring.jd new file mode 100644 index 000000000000..0cd61a067d93 --- /dev/null +++ b/docs/html/intl/ko/training/monitoring-device-state/docking-monitoring.jd @@ -0,0 +1,74 @@ +page.title=도킹 상태와 유형 확인 및 모니터링 +parent.title=배터리 수명 최적화 +parent.link=index.html + +trainingnavtop=true +previous.title= 배터리 수준 및 충전 상태 모니터링 +previous.link=battery-monitoring.html +next.title= 연결 상태 확인 및 모니터링 +next.link=connectivity-monitoring.html + +@jd:body + + + +

    Android 기기는 여러 종류의 도크로 도킹될 수 있습니다. 여기에는 카폰 또는 홈 도크와 디지털 및 아날로그 도크가 포함됩니다. 많은 도크가 도킹된 기기에 전기를 공급하므로 일반적으로 충전 상태와 도크 상태는 밀접한 관련이 있습니다.

    + +

    전화의 도크 상태가 업데이트 빈도에 어떻게 영향을 미치는지는 앱에 따라 다릅니다. 스포츠 센터 앱이라면 데스크톱 도크에서 업데이트 빈도를 높이고 카폰 도크에 연결된 경우 업데이트를 완전히 사용 중지해도 좋습니다. 반대로 교통 상황을 제공하는 앱이라면 카폰 도크에서 업데이트를 최대화해도 좋습니다.

    + +

    도크 상태는 스티키 {@link android.content.Intent}로 브로드캐스트되어 기기가 도킹되었는지 여부와 도킹되었다면 어떤 종류의 도크인지 알아낼 수 있습니다.

    + + +

    현재 도킹 상태 확인

    + +

    도크 상태의 세부사항은 {@link android.content.Intent#ACTION_DOCK_EVENT} 액션의 스티키 브로드캐스트 내에 추가로 포함됩니다. 스티키 브로드캐스트이므로 {@link android.content.BroadcastReceiver}를 등록할 필요가 없습니다. 다음 스니펫에 표시된 브로드캐스트 수신기와 같이 간단히 {@link android.content.Context#registerReceiver registerReceiver()}를 호출하여 {@code null}에 제출할 수 있습니다.

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
    +Intent dockStatus = context.registerReceiver(null, ifilter);
    + +

    {@code EXTRA_DOCK_STATE} 추가로부터 현재 도킹 상태를 추출할 수 있습니다.

    + +

    int dockState = battery.getIntExtra(EXTRA_DOCK_STATE, -1);
    +boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
    + + +

    현재 도크 유형 확인

    + +

    4가지 유형의 도크가 있습니다. +

    • 카폰
    • +
    • 데스크
    • +
    • 저가형(아날로그) 데스크
    • +
    • 고가형(디지털) 데스크

    + +

    마지막 두 가지 옵션은 API 수준 11의 Android에만 제공되어 있으므로, 디지털 또는 아날로그에 상관하지 않고 관심 있는 세 가지 도크 유형에 대해 확인하는 것이 좋습니다.

    + +
    boolean isCar = dockState == EXTRA_DOCK_STATE_CAR;
    +boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK || 
    +                 dockState == EXTRA_DOCK_STATE_LE_DESK ||
    +                 dockState == EXTRA_DOCK_STATE_HE_DESK;
    + + +

    도크 상태 또는 유형 변경사항 모니터링

    + +

    도킹 상태가 바뀌면 {@link android.content.Intent#ACTION_DOCK_EVENT} 액션이 브로드캐스트됩니다. 기기의 도크 상태 변경사항을 모니터링하려면 아래에 표시된 대로 애플리케이션 매니페스트에서 브로드캐스트 리시버를 등록하세요.

    + +
    <action android:name="android.intent.action.ACTION_DOCK_EVENT"/>
    + +

    이전 단계에서 설명한 기술을 사용하여 리시버 구현에서 도크 유형 및 상태를 추출할 수 있습니다.

    diff --git a/docs/html/intl/ko/training/monitoring-device-state/index.jd b/docs/html/intl/ko/training/monitoring-device-state/index.jd new file mode 100644 index 000000000000..f96e2e16dc57 --- /dev/null +++ b/docs/html/intl/ko/training/monitoring-device-state/index.jd @@ -0,0 +1,49 @@ +page.title=배터리 수명 최적화 + +trainingnavtop=true +startpage=true +next.title=배터리 수준 및 충전 상태 모니터링 +next.link=battery-monitoring.html + +@jd:body + +
    +
    + +

    요구사항과 선행조건

    + + +

    참고자료

    + + +
    +
    + +

    좋은 앱은 호스트 기기의 배터리 수명에 미치는 영향이 미미해야 합니다. 강의를 통해 호스트 기기의 상태에 따라 기능과 동작을 수정하는 것을 모니터링하는 앱을 구축할 수 있게 됩니다.

    + +

    연결이 끊겼을 때 백그라운드 서비스 업데이트를 사용 중지하거나, 배터리 수준이 낮을 때 업데이트 빈도를 줄이는 조치를 취하여, 사용자 환경을 손상시키지 않고 배터리 수명에 미치는 영향을 최소화할 수 있습니다.

    + +

    강의

    + + + +
    +
    배터리 수준 및 충전 상태 모니터링
    +
    충전 상태에서 현재 배터리 수준 및 변경사항을 확인 및 모니터링하여 앱의 업데이트 빈도를 변경하는 법을 알아보세요.
    + +
    도킹 상태와 유형 확인 및 모니터링
    +
    최적의 새로고침 빈도는 호스트 기기의 사용 방법에 따라 달라질 수 있습니다. 앱의 동작에 영향을 미치는 도킹 상태와 도크 유형을 확인 및 모니터링하는 방법을 알아보세요.
    + +
    연결 상태 확인 및 모니터링
    +
    인터넷 연결 없이 온라인 소스를 통해 앱을 업데이트할 수 없습니다. 연결 상태를 확인하여 백그라운드 업데이트 빈도를 변경하는 방법을 알아보세요. 고대역폭 작업을 시작하기 전에 Wi-Fi 또는 모바일 연결을 확인하는 방법도 알 수 있습니다.
    + +
    온디맨드로 브로드캐스트 수신기 조작
    +
    매니페스트 내에 선언했던 브로드캐스트 리시버는 현재 기기 상태에서 필요 없는 것을 사용 중지하도록 런타임 때 전환될 수 있습니다. 기기가 특정 상태에 도달할 때까지 상태 변화 리시버 및 지연 액션을 전환 및 단계적으로 연결하여 효율성을 향상하는 법을 알아보세요.
    +
    \ No newline at end of file diff --git a/docs/html/intl/ko/training/monitoring-device-state/manifest-receivers.jd b/docs/html/intl/ko/training/monitoring-device-state/manifest-receivers.jd new file mode 100644 index 000000000000..c5c311b75f6b --- /dev/null +++ b/docs/html/intl/ko/training/monitoring-device-state/manifest-receivers.jd @@ -0,0 +1,50 @@ +page.title=온디맨드로 브로드캐스트 수신기 조작 +parent.title=배터리 수명 최적화 +parent.link=index.html + +trainingnavtop=true + +previous.title=연결 상태 확인 및 모니터링 +previous.link=connectivity-monitoring.html + +@jd:body + + + +

    기기 상태 변경을 모니터링하는 가장 간단한 방법은 모니터링하는 각 상태에 대해 {@link android.content.BroadcastReceiver}를 만들어 각각을 애플리케이션 매니페스트에 등록하는 것입니다. 그러면 각 리시버 내에서 현재 기기 상태를 기반으로 반복 알람의 일정을 간단히 변경할 수 있습니다.

    + +

    이 방법의 부작용은 리시버 중 하나라도 실행되면 매번 앱이 기기의 절전 모드를 해제시킨다는 것입니다.

    + +

    더 나은 방법은 런타임 때 브로드캐스트 리시버를 사용 중지 또는 사용하도록 설정하는 것입니다. 이렇게 하면 매니페스트에 선언한 리시버를 필요할 때만 시스템 이벤트에 의해 실행되는 수동적인 알람으로 사용할 수 있습니다.

    + + +

    효율성 향상을 위한 상태 변화 수신기의 전환 및 단계적 연결

    + +

    {@link android.content.pm.PackageManager}를 사용하여 아래에서 표시된 대로 모든 사용 또는 사용 중지하기 원하는 브로드캐스트 리시버를 포함하여 매니페스트 내에 정의된 모든 요소의 사용 가능 상태를 전환할 수 있습니다.

    + +
    ComponentName receiver = new ComponentName(context, myReceiver.class);
    +
    +PackageManager pm = context.getPackageManager();
    +
    +pm.setComponentEnabledSetting(receiver,
    +        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    +        PackageManager.DONT_KILL_APP)
    + +

    이 방법을 사용하면 연결이 없음을 확인한 경우 연결 변경 리시버를 제외한 모든 리시버를 사용 중지할 수 있습니다. 반대로 한 번 연결되면 연결 변경사항의 수신을 중지할 수 있으며, 업데이트를 수행하고 반복 업데이트 알람의 일정을 변경하기 전에 온라인 상태인지만 간단히 확인할 수 있습니다.

    + +

    높은 대역폭을 요구하는 다운로드를 중지시키는 데 동일한 기술을 사용할 수 있습니다. 연결 변경을 수신하는 브로드캐스트 리시버를 사용하도록 설정하고 반드시 Wi-Fi에 연결한 후에 다운로드를 시작하도록 합니다.

    diff --git a/docs/html/intl/ko/training/multiscreen/adaptui.jd b/docs/html/intl/ko/training/multiscreen/adaptui.jd new file mode 100644 index 000000000000..cb7b66c90238 --- /dev/null +++ b/docs/html/intl/ko/training/multiscreen/adaptui.jd @@ -0,0 +1,212 @@ +page.title=조정형 UI 플로우 구현 +parent.title=다양한 화면 지원 +parent.link=index.html + +trainingnavtop=true +previous.title=다양한 화면 밀도 지원 +previous.link=screendensities.html + +@jd:body + + + + + +

    현재 애플리케이션이 표시하는 레이아웃에 따라 UI 플로가 달라질 수 있습니다. 예를 들어 애플리케이션이 이중 창 모드로 되어 있는 경우에는 왼쪽 창에 있는 항목을 클릭하면 오른쪽 창에 콘텐츠가 표시되고, 단일 창 모드로 되어 있는 경우에는 콘텐츠가 해당 창에 표시됩니다(다른 액티비티에서).

    + + +

    현재 레이아웃 확인

    + +

    각 레이아웃을 구현하는 방식이 약간씩 다르므로 가장 먼저 해야 할 일은 현재 사용자에게 어떤 레이아웃이 표시되는지 확인하는 것입니다. 예를 들어, 사용자가 '단일 창' 모드에 있는지 혹은 '이중 창' 모드에 있는지 파악할 수 있습니다. 이는 특정 뷰가 존재하고 그 뷰가 표시되는지 조회하면 됩니다.

    + +
    +public class NewsReaderActivity extends FragmentActivity {
    +    boolean mIsDualPane;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main_layout);
    +
    +        View articleView = findViewById(R.id.article);
    +        mIsDualPane = articleView != null && 
    +                        articleView.getVisibility() == View.VISIBLE;
    +    }
    +}
    +
    + +

    이 코드는 'article' 창을 사용할 수 있는지 여부를 조회하며 이러한 방식이 특정 레이아웃에 대한 조회를 하드코딩하는 것보다 훨씬 유연한 방식입니다.

    + +

    다른 구성요소의 존재 여부에 맞게 앱을 조정하는 또 다른 방법은 구성요소에 대한 작업을 수행하기 전에 해당 구성요소를 사용할 수 있는지 확인하는 것입니다. 예를 들어 뉴스 리더 샘플 앱의 경우, 메뉴를 여는 버튼이 있긴 하지만 이 버튼은 Android 3.0 이전 버전에서 실행되는 경우에만 존재합니다(API 수준 11 이상에서 {@link android.app.ActionBar} 가 그 기능을 대신하기 때문). 따라서 이 버튼에 대한 이벤트 리스너를 추가하기 위해 다음과 같이 할 수 있습니다.

    + +
    +Button catButton = (Button) findViewById(R.id.categorybutton);
    +OnClickListener listener = /* create your listener here */;
    +if (catButton != null) {
    +    catButton.setOnClickListener(listener);
    +}
    +
    + + +

    현재 레이아웃에 대한 대응

    + +

    현재 레이아웃에 따라 일부 액션의 결과가 달라질 수 있습니다. 예를 들어 뉴스 리더 샘플의 헤드라인 목록에서 헤드라인을 클릭하면 UI가 이중 창 모드인 경우에는 기사가 오른쪽 창에서 열리지만, UI가 단일 창 모드인 경우에는 별도의 액티비티가 실행됩니다.

    + +
    +@Override
    +public void onHeadlineSelected(int index) {
    +    mArtIndex = index;
    +    if (mIsDualPane) {
    +        /* display article on the right pane */
    +        mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
    +    } else {
    +        /* start a separate activity */
    +        Intent intent = new Intent(this, ArticleActivity.class);
    +        intent.putExtra("catIndex", mCatIndex);
    +        intent.putExtra("artIndex", index);
    +        startActivity(intent);
    +    }
    +}
    +
    + +

    마찬가지로, 앱이 이중 창 모드인 경우에는 탐색용 탭이 포함된 작업 표시줄이 설정되지만, 앱이 단일 창 모드인 경우에는 스피너 위젯이 포함된 탐색 메뉴가 설정됩니다. 따라서 어떤 경우가 적합한지도 코드에서 확인해야 합니다.

    + +
    +final String CATEGORIES[] = { "Top Stories", "Politics", "Economy", "Technology" };
    +
    +public void onCreate(Bundle savedInstanceState) {
    +    ....
    +    if (mIsDualPane) {
    +        /* use tabs for navigation */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
    +        int i;
    +        for (i = 0; i < CATEGORIES.length; i++) {
    +            actionBar.addTab(actionBar.newTab().setText(
    +                CATEGORIES[i]).setTabListener(handler));
    +        }
    +        actionBar.setSelectedNavigationItem(selTab);
    +    }
    +    else {
    +        /* use list navigation (spinner) */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
    +        SpinnerAdapter adap = new ArrayAdapter(this, 
    +                R.layout.headline_item, CATEGORIES);
    +        actionBar.setListNavigationCallbacks(adap, handler);
    +    }
    +}
    +
    + + +

    다른 액티비티에 프래그먼트 재사용

    + +

    다양한 화면의 디자인에 반복되는 패턴에는 일부 화면 구성에서는 창으로 구현되고 다른 화면 구성에서는 별도의 액티비티로 구현되는 인터페이스가 일부 있습니다. 예를 들어 뉴스 리더 샘플에서 뉴스 기사 텍스트가 큰 화면에서는 오른쪽 창에 표시되지만 작은 화면에서는 별도의 액티비티입니다.

    + +

    이러한 경우 일반적으로 동일한 {@link android.app.Fragment} 하위 클래스를 여러 액티비티에 재사용하여 코드 중복을 피할 수 있습니다. 예를 들어 ArticleFragment는 이중 창 레이아웃에서 사용되며

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    작은 화면의 액티비티 레이아웃에 레이아웃 없이 재사용됩니다(ArticleActivity).

    + +
    +ArticleFragment frag = new ArticleFragment();
    +getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
    +
    + +

    당연히 이는 XML 레이아웃에서 프래그먼트(fragment)를 명시하는 것과 같은 효과가 있지만 이 경우에는 아티클 프래그먼트가 이 액티비티의 유일한 구성요소이기 때문에 XML 레이아웃은 불필요한 작업이 됩니다.

    + +

    프래그먼트를 디자인할 때 염두에 두어야 할 매우 중요한 점 한 가지는 특정 액티비티에 대한 강한 커플링을 만들지 말아야 한다는 점입니다. 이렇게 하려면 일반적으로 프래그먼트가 호스트 액티비티와 상호작용해야 하는 모든 방식을 추상화하는 인터페이스를 정의하면 됩니다. 그러면 호스트 액티비티가 해당 인터페이스를 구현합니다.

    + +

    예를 들어 뉴스 리더 앱의 HeadlinesFragment가 정확하게 그 일을 해 줍니다.

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    OnHeadlineSelectedListener mHeadlineSelectedListener = null;
    +
    +    /* Must be implemented by host activity */
    +    public interface OnHeadlineSelectedListener {
    +        public void onHeadlineSelected(int index);
    +    }
    +    ...
    +
    +    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
    +        mHeadlineSelectedListener = listener;
    +    }
    +}
    +
    + +

    그런 다음 사용자가 헤드라인을 선택하면 프래그먼트가 하드코딩된 특정 액티비티를 알리지 않고 호스트 액티비티가 지정한 리스너를 알립니다.

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    @Override
    +    public void onItemClick(AdapterView<?> parent, 
    +                            View view, int position, long id) {
    +        if (null != mHeadlineSelectedListener) {
    +            mHeadlineSelectedListener.onHeadlineSelected(position);
    +        }
    +    }
    +    ...
    +}
    +
    + +

    이 기술은 태블릿 및 휴대전화 지원 가이드에서 자세히 설명되어 있습니다.

    + + +

    화면 구성 변경 처리

    + +

    인터페이스 중 일부를 구현하는데 별도의 액티비티를 사용 중인 경우 인터페이스의 일관성을 유지하기 위해 특정 구성의 변경(예: 화면 전환)에 대응해야 합니다.

    + +

    예를 들어 Android 3.0 이상을 실행하는 일반적인 7인치 태블릿에서 뉴스 리더 샘플은 세로 모드에서 실행될 때에는 뉴스 기사를 표시하는 데 별도의 액티비티를 사용하지만 가로모드에서는 이중 창(two-pane) 레이아웃을 사용합니다.

    + +

    즉 사용자가 세로 모드에 있고 기사를 보기 위한 액티비티가 화면에 있는 경우, 방향이 가로로 바뀌었음을 감지하고, 액티비티를 종료한 다음 주요 액티비티로 돌아감으로써 콘텐츠가 이중 창 레이아웃에서 표시되도록 적절하게 대응해야 합니다.

    + +
    +public class ArticleActivity extends FragmentActivity {
    +    int mCatIndex, mArtIndex;
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
    +        mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
    +
    +        // If should be in two-pane mode, finish to return to main activity
    +        if (getResources().getBoolean(R.bool.has_two_panes)) {
    +            finish();
    +            return;
    +        }
    +        ...
    +}
    +
    + + diff --git a/docs/html/intl/ko/training/multiscreen/index.jd b/docs/html/intl/ko/training/multiscreen/index.jd new file mode 100644 index 000000000000..d9e09b08ae48 --- /dev/null +++ b/docs/html/intl/ko/training/multiscreen/index.jd @@ -0,0 +1,64 @@ +page.title=다양한 화면 지원 + +trainingnavtop=true +startpage=true +next.title=다양한 화면 크기 지원 +next.link=screensizes.html + +@jd:body + +
    +
    + +

    요구사항과 선행조건

    + + + +

    참고자료

    + + + +

    다운로드

    + +
    +샘플 앱 다운로드 +

    NewsReader.zip

    +
    + +
    +
    + +

    Android는 소형 휴대전화에서부터 대형 TV에 이르기까지 다양한 화면 크기의 수많은 기기 유형을 지원합니다. 따라서 애플리케이션이 모든 화면 크기와 호환되어 최대한 많은 사용자가 사용할 수 있도록 디자인하는 것이 중요합니다.

    + +

    하지만 다양한 기기 유형과 호환되는 것만으로는 충분하지 않습니다. 각 화면 크기에 따라 사용자 상호작용에 유리한 점과 불리한 점이 다릅니다. 따라서 사용자에게 만족을 주고 깊은 인상을 심어주려면 애플리케이션이 단지 여러 화면을 지원하는 데 그치지 않고 화면 구성별로 사용자 환경을 최적화해야 합니다.

    + +

    이번 강의에서는 여러 화면 구성에 최적화된 사용자 인터페이스를 구현하는 방법을 설명합니다.

    + +

    각 강의에서 사용되는 코드는 여러 화면에 대한 최적화의 모범 사례를 보여주는 샘플 애플리케이션에서 가져온 것입니다. 샘플(오른쪽)을 다운로드하여 본인의 애플리케이션에 코드로 재사용할 수 있습니다.

    + +

    참고: 이 강의 및 강의와 관련된 샘플은 호환성 라이브러리를 사용하며 이는 Android 3.0 이하 버전에서 {@link android.app.Fragment} API를 사용하기 위해서입니다. 이 강의에서 API를 모두 사용하려면 라이브러리를 다운로드하여 애플리케이션에 추가해야 합니다.

    + + +

    강의

    + +
    +
    다양한 화면 크기 지원
    +
    이 강의에서는 여러 다양한 화면 크기에 조정되는 레이아웃을 디자인하는 방법(유연한 보기 크기, {@link android.widget.RelativeLayout}, 화면 크기 및 방향 한정자, 별칭 필터 및 나인-패치 비트맵 사용하기)을 안내합니다.
    + +
    다양한 화면 밀도 지원
    +
    이 강의에서는 다양한 픽셀 밀도를 가진 화면을 지원하는 방법(밀도 독립형 픽셀(density-independent pixel) 사용하기 및 밀도별로 적합한 비트맵 제공하기)을 설명합니다.
    + +
    조정형 UI 플로우 구현
    +
    이 강의에서는 여러 화면 크기/밀도 조합에 조정되도록 UI 플로우를 구현하는 방법(활성 레이아웃의 런타임 감지, 현재 레이아웃에 따른 대응, 화면 구성 변경 처리)을 설명합니다.
    +
    diff --git a/docs/html/intl/ko/training/multiscreen/screendensities.jd b/docs/html/intl/ko/training/multiscreen/screendensities.jd new file mode 100644 index 000000000000..5d6e2f3c59b7 --- /dev/null +++ b/docs/html/intl/ko/training/multiscreen/screendensities.jd @@ -0,0 +1,100 @@ +page.title=다양한 화면 밀도 지원 +parent.title=다양한 화면 지원 +parent.link=index.html + +trainingnavtop=true +previous.title=다양한 화면 크기 지원 +previous.link=screensizes.html +next.title=조정형 UI 플로우 구현 +next.link=adaptui.html + +@jd:body + + + +
    +
    + +

    강의 목표

    +
      +
    1. DIP(Density Independent Pixel) 사용
    2. +
    3. 대체 비트맵 제공
    4. +
    + +

    참고자료

    + + + +

    다운로드

    + +
    +샘플 앱 다운로드 +

    NewsReader.zip

    +
    + + +
    +
    + +

    이 강의에서는 다양한 리소스를 제공하고 해상도 독립형(resolution-independent) 측정 단위를 사용함으로써 다양한 화면 밀도를 지원하는 방법을 설명합니다.

    + +

    DIP(Density Independent Pixel) 사용

    + +

    레이아웃을 디자인할 때 범하기 쉬운 실수 중 하나는 절대 픽셀(absolute pixel)을 사용하여 거리나 크기를 정의하는 것입니다. 각 화면은 픽셀 밀도가 서로 다른데 레이아웃 크기를 픽셀로 정의하면 동일한 픽셀 수치가 다른 기기에서 다른 물리적 크기와 대응할 수 있어 문제가 됩니다. 따라서 크기를 지정할 때에는 항상 dp 또는 sp 단위를 사용하시기 바랍니다. dp는 160dpi에서 픽셀의 물리적 크기에 대응하는 밀도 독립형 픽셀(Density Independent Pixel)입니다. sp는 동일한 기본 단위이지만 사용자의 기본 텍스트 크기에 따라 확대/축소될 수 있으므로(배율 독립형 픽셀(Scale Independent Pixel)임) 텍스트 크기를 정의할 때 이 측정 단위를 사용해야 합니다(레이아웃 크기에 사용해서는 안됨).

    + +

    예를 들어 두 개의 보기 사이에 여백을 지정할 때 px가 아닌 dp를 사용합니다.

    + +
    +<Button android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content" 
    +    android:text="@string/clickme"
    +    android:layout_marginTop="20dp" />
    +
    + +

    텍스트 크기를 지정할 때에는 항상 sp를 사용합니다.

    + +
    +<TextView android:layout_width="match_parent" 
    +    android:layout_height="wrap_content" 
    +    android:textSize="20sp" />
    +
    + + +

    대체 비트맵 제공

    + +

    Android는 화면 밀도가 다양한 기기에서 실행되므로 각각의 일반화된 밀도 종류(저, 중, 고 및 초고 밀도)에 맞춤화된 비트맵 리소스를 제공해야 합니다. 이렇게 하면 모든 화면 밀도에서 좋은 그래픽 품질 및 성능을 얻는데 도움이 됩니다.

    + +

    이러한 이미지를 생성하려면 벡터 형식의 원본 리소스부터 시작해야 하며 다음 크기 배율을 사용하여 각 밀도에 사용할 이미지를 생성해야 합니다.

    + +

      +
    • xhdpi: 2.0 +
    • hdpi: 1.5 +
    • mdpi: 1.0 (기선) +
    • ldpi: 0.75 +

    + +

    xhdpi 기기에 대해 200x200 이미지를 생성하는 경우 hdpi 기기에 대해 동일한 리소스를 150x150으로 생성해야 하며 mdpi 기기에 대해서는 100x100, ldpi 기기에 대해서는 75x75으로 동일한 리소스를 생성해야 합니다.

    + +

    그런 다음 생성된 이미지 파일을 res/ 아래의 적절한 하위 디렉토리에 배치하면 시스템에서 애플리케이션이 실행되는 기기의 화면 밀도에 따라 정확한 이미지 파일을 자동으로 선택합니다.

    + +
    +MyProject/
    +  res/
    +    drawable-xhdpi/
    +        awesomeimage.png
    +    drawable-hdpi/
    +        awesomeimage.png
    +    drawable-mdpi/
    +        awesomeimage.png
    +    drawable-ldpi/
    +        awesomeimage.png
    +
    + +

    그런 다음 언제든지 @drawable/awesomeimage를 참조하면 시스템이 화면의 dpi에 따라 적합한 비트맵을 선택합니다.

    + +

    애플리케이션에 사용할 아이콘 저작물 제작에 대한 자세한 도움말 및 가이드라인은 아이콘 디자인 가이드라인을 참조하세요.

    + diff --git a/docs/html/intl/ko/training/multiscreen/screensizes.jd b/docs/html/intl/ko/training/multiscreen/screensizes.jd new file mode 100644 index 000000000000..f2e77a6e2b04 --- /dev/null +++ b/docs/html/intl/ko/training/multiscreen/screensizes.jd @@ -0,0 +1,279 @@ +page.title=다양한 화면 크기 지원 +parent.title=다양한 화면 지원 +parent.link=index.html + +trainingnavtop=true +next.title=다양한 화면 밀도 지원 +next.link=screendensities.html + +@jd:body + + + + + +

    이 강의에서는 다양한 화면 크기를 지원하는 방법을 설명합니다.

    +
      +
    • 화면에 맞게 레이아웃 크기 조정
    • +
    • 화면 구성에 따라 적합한 UI 레이아웃 제공
    • +
    • 올바른 화면에 올바른 레이아웃 적용
    • +
    • 정확하게 확대되는 비트맵 제공
    • +
    + + +

    'wrap_content' 및 'match_parent' 사용

    + +

    레이아웃이 다양한 화면 크기에 따라 유연하게 조정되도록 하려면 일부 뷰 구성요소의 너비와 높이에 "wrap_content""match_parent"를 사용해야 합니다. "wrap_content"를 사용하면 뷰의 너비와 높이가 해당 뷰 내에 콘텐츠가 들어가는데 필요한 최소 크기로 설정되는 반면, "match_parent"(API 수준 8 이전에는 "fill_parent"라고도 함)를 사용하면 구성요소가 확장되어 부모뷰의 크기와 일치하게 됩니다.

    + +

    하드코딩된 크기 대신 "wrap_content" 크기 값을 사용하면 뷰가 해당 뷰에 필요한 여백만을 사용하며 "match_parent" 크기 값을 사용하면 뷰가 확대되어 사용 가능한 여백을 채웁니다. 예를 들면 다음과 같습니다.

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    샘플에서 구성요소 크기에 특정 크기가 아닌 "wrap_content""match_parent"가 사용된 것을 눈여겨 보시기 바랍니다. 이렇게 하면 레이아웃이 다양한 화면 크기 및 방향에 맞게 조정됩니다.

    + +

    예를 들어 세로 및 가로 모드에서 레이아웃은 다음과 같이 표시됩니다. 구성요소의 크기가 너비와 높이에 맞게 자동으로 조정됩니다.

    + + +

    그림 1. 세로 모드(왼쪽) 및 가로 모드(오른쪽)에서의 뉴스 리더 샘플 앱

    + + +

    RelativeLayout 사용

    + +

    비교적 복잡한 레이아웃을 만들려면 {@link android.widget.LinearLayout}의 중첩 인스턴스와 "wrap_content""match_parent" 크기의 조합을 사용합니다. 하지만 {@link android.widget.LinearLayout} 을 사용하면 자식뷰의 여백 관계를 정확하게 제어할 수 없으며 {@link android.widget.LinearLayout} 단순히 나란하게 표시됩니다. 자식뷰를 일직선이 아닌 다양한 방향으로 표시해야 하는 경우 구성요소 사이의 여백 관계를 중심으로 레이아웃을 지정할 수 있는 {@link android.widget.RelativeLayout}을 사용하는 것이 더 좋은 방법일 수 있습니다. 예를 들어 화면 왼쪽에 하나의 자식뷰를, 오른쪽에 다른 자식뷰를 정렬할 수 있습니다.

    + +

    예를 들면 다음과 같습니다.

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="match_parent"
    +    android:layout_height="match_parent">
    +    <TextView
    +        android:id="@+id/label"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:text="Type here:"/>
    +    <EditText
    +        android:id="@+id/entry"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/label"/>
    +    <Button
    +        android:id="@+id/ok"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/entry"
    +        android:layout_alignParentRight="true"
    +        android:layout_marginLeft="10dp"
    +        android:text="OK" />
    +    <Button
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_toLeftOf="@id/ok"
    +        android:layout_alignTop="@id/ok"
    +        android:text="Cancel" />
    +</RelativeLayout>
    +
    + +

    그림 2는 이 레이아웃이 QVGA 화면에 어떻게 표시되는지 보여줍니다.

    + + +

    그림 2. QVGA 화면(작은 화면)의 스크린샷

    + +

    그림 3은 이 레이아웃이 큰 화면에서 어떻게 표시되는지 보여줍니다.

    + + +

    그림 3. WSVGA 화면(큰 화면)의 스크린샷

    + +

    구성요소의 크기가 변하더라도 여백 관계가 {@link android.widget.RelativeLayout.LayoutParams}.

    + + +

    크기 한정자 사용

    + +

    이전 섹션에서 다룬 유연한 레이아웃이나 상대적 레이아웃으로는 한계가 있습니다. 이러한 레이아웃이 구성요소 내부 및 주위의 여백을 확장하여 다양한 화면에 맞게 조정되긴 하지만 화면 크기별로 최적의 사용자 환경을 제공하지는 못할 수 있습니다. 따라서 애플리케이션은 유연한 레이아웃을 구현할 뿐 아니라 다양한 화면 구성을 타겟팅할 수 있도록 다양한 대체 레이아웃을 제공해야 합니다. 그 방법은 런타임이 현재 기기의 구성에 따라 적합한 리소스(예: 화면 크기별로 다른 레이아웃 디자인)를 자동으로 선택하도록 해 주는 구성 한정자를 사용하는 것입니다.

    + +

    예를 들어 많은 애플리케이션이 큰 화면에 '이중 창(two pane)' 패턴을 구현합니다(한 쪽 창에는 아이템의 목록을 표시하고 다른 창에는 콘텐츠를 표시). 태블릿 및 TV는 두 개의 창 모두가 화면에 동시에 들어갈 정도로 크지만 휴대전화 화면은 두 창을 따로 표시해야 합니다. 따라서 이러한 레이아웃을 구현하려면 다음 파일이 있어야 합니다.

    + +
      +
    • res/layout/main.xml, 단일 창(기본값) 레이아웃: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-large/main.xml, 이중 창 레이아웃: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    두 번째 레이아웃의 디렉토리 이름에서 large 한정자를 눈여겨 보시기 바랍니다. 이 레이아웃은 대형(예: 7인치 태블릿 이상)으로 분류된 화면을 가진 기기에서 선택됩니다. 한정자가 없는 다른 레이아웃은 소형 기기에서 선택됩니다.

    + + +

    최소 너비 한정자 사용

    + +

    Android 3.2 이전 기기에서 개발자가 어려움을 느꼈던 문제 중의 하나는 Dell Streak, 최초의 Galaxy 탭 및 7인치 태블릿에 두루 사용되는 '큰' 화면 크기 빈이었습니다. 하지만 많은 애플리케이션은 화면이 '큰' 기기라 하더라도 이 카테고리(예: 5인치 및 7인치 기기)에 속하는 다양한 기기에 다양한 레이아웃을 표시하고 싶어 합니다. 이것이 Android에서 Android 3.2에 '최소 너비' 한정자를 도입한 이유입니다.

    + +

    최소 너비 한정자를 사용하면 dp 단위의 특정 최소 너비를 가진 화면을 타겟팅할 수 있습니다. 예를 들어 일반적인 7인치 태블릿에는 600dp라는 최소 너비가 있으므로 이러한 화면에서 두 개의 창에 UI를 사용(작은 화면에서는 단일 목록 사용) 하고 싶은 경우 단일 및 이중 창 레이아웃에 이전 섹션과 동일한 레이아웃을 사용하면 되지만, 이중 창 레이아웃은 최소 너비가 600dp인 화면에 사용한다는 것을 나타내기 위해서 large 크기 한정자 대신 sw600dp를 사용해야 합니다.

    + +
      +
    • res/layout/main.xml, 단일 창(기본값) 레이아웃: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-sw600dp/main.xml, 이중 창 레이아웃: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    이는 최소 너비가 600dp 이상인 기기는 layout-sw600dp/main.xml(이중 창) 레이아웃을 선택하는 반면 소형 화면은 layout/main.xml (단일 창) 레이아웃을 선택한다는 것을 의미합니다.

    + +

    하지만 Android 3.2 이전 기기는 sw600dp를 크기 한정자로 인식하지 않기 때문에 최소 너비 한정자가 제대로 작동하지 않으며 따라서 large 한정자도 계속 사용해야 합니다. 따라서 res/layout-large/main.xml라는 이름의 파일이 있어야 하며 이 파일은 res/layout-sw600dp/main.xml과 동일한 파일입니다. 다음 섹션에서는 이런 식으로 레이아웃 파일이 중복되지 않게 하는 기술을 살펴보겠습니다.

    + + +

    레이아웃 별칭 사용

    + +

    최소 너비 한정자는 Android 3.2 이상 버전에서만 사용할 수 있습니다. 따라서 이전 버전과 호환되도록 하려면 추상화 크기 빈(소형, 보통, 대형 및 초대형)을 계속 사용해야 합니다. 예를 들어 휴대전화에서는 단일 창 UI가 표시되고 7인치 태블릿, TV 및 기타 대형 기기에서는 다중 창 UI가 표시되도록 UI를 디자인하려면 다음 파일을 제공해야 합니다.

    + +

      +
    • res/layout/main.xml: 단일 창 레이아웃
    • +
    • res/layout-large: 다중 창 레이아웃
    • +
    • res/layout-sw600dp: 다중 창 레이아웃
    • +

    + +

    마지막 두 개의 파일은 하나는 Android 3.2 기기와 일치하고 다른 하나는 이전 버전의 Android가 탑재된 태블릿 및 TV를 위한 것으로 서로 동일한 파일입니다.

    + +

    이 경우 별칭 파일을 사용하면 태블릿 및 TV용으로 동일한 파일이 중복되지 않도록 하고 이를 관리해야 하는 번거로움을 없앨 수 있습니다. 예를 들어 다음 레이아웃을 지정할 수 있습니다.

    + +
      +
    • res/layout/main.xml, 단일 창 레이아웃
    • +
    • res/layout/main_twopanes.xml, 이중 창 레이아웃
    • +
    + +

    또한 다음 두 개의 파일을 추가합니다.

    + +

      +
    • res/values-large/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      +
    • + +
    • res/values-sw600dp/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      + +
    • +

    + +

    뒤에 있는 두 개의 파일은 콘텐츠는 동일하지만 실제로 레이아웃을 지정하지는 않으며 단지 {@code main}{@code main_twopanes}에 대한 별칭이 되도록 설정합니다. 이 파일에는 largesw600dp 선택기가 있으므로 Android 버전에 관계없이 태블릿 및 TV에 적용됩니다(3.2 버전 이전의 태블릿 및 TV는 +{@code large},3.2 이후 버전은 sw600dp와 일치).

    + + +

    방향 한정자 사용

    + +

    일부 레이아웃은 가로 및 세로 방향 모두에서 잘 작동하지만 대부분의 레이아웃은 조정을 통해 많은 이점을 누릴 수 있습니다. 다음은 뉴스 리더 샘플 앱에서 화면 크기와 방향별로 레이아웃이 어떻게 작동하는지 보여줍니다.

    + +

      +
    • 소형 화면, 세로: 단일 창, 로고 표시
    • +
    • 소형 화면, 가로: 단일 창, 로고 표시
    • +
    • 7인치 태블릿, 세로: 단일 창, 작업 표시줄 표시
    • +
    • 7인치 태블릿, 가로: 이중 창, 와이드, 작업 표시줄 표시
    • +
    • 10인치 태블릿, 세로: 이중 창, 내로우, 작업 표시줄 표시
    • +
    • 10인치 태블릿, 가로: 이중 창, 와이드, 작업 표시줄 표시
    • +
    • TV, 가로: 이중 창, 와이드, 작업 표시줄 표시
    • +

    + +

    따라서 이러한 각 레이아웃은 res/layout/ 디렉토리의 XML 파일에서 지정됩니다. 그러면 앱은 각 레이아웃을 다양한 화면 구성에 지정하기 위해 레이아웃 별칭을 사용해 레이아웃을 각 구성과 일치시킵니다.

    + +

    res/layout/onepane.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} + +

    res/layout/onepane_with_bar.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    res/layout/twopanes.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    res/layout/twopanes_narrow.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes_narrow.xml all} + +

    가능한 레이아웃을 모두 지정했으므로 구성 한정자를 사용하여 올바른 레이아웃을 각 구성에 매핑하기만 하면 되며 이는 레이아웃 별칭 기술을 사용하면 됩니다.

    + +

    res/values/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values/layouts.xml all} + +

    res/values-sw600dp-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-land/layouts.xml +all} + +

    res/values-sw600dp-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-port/layouts.xml +all} + +

    res/values-large-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-land/layouts.xml all} + +

    res/values-large-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-port/layouts.xml all} + + + +

    나인-패치 비트맵 사용

    + +

    일반적으로 다양한 화면 크기를 지원하려면 이미지 리소스도 다양한 크기에 맞게 조정될 수 있어야 합니다. 예를 들어 버튼 배경은 버튼 배경이 적용되는 모든 버튼 모양과 맞아야 합니다.

    + +

    구성요소에 크기가 바뀔 수 있는 단순한 이미지를 사용하는 경우 런타임이 이미지를 균등하게 확대하거나 축소하기 때문에 기대에 미치지 못하는 결과가 나옵니다. 이에 대한 해결 방법은 확대될 수 있는 영역과 확대될 수 없는 영역을 나타내는 특별한 형식의 PNG 파일인 나인-패치 비트맵을 사용하는 것입니다.

    + +

    따라서 다양한 크기를 가진 구성요소에 사용할 비트맵을 디자인할 때에는 항상 나인-패치를 사용하시기 바랍니다. 비트맵을 나인-패치로 변환하려면 일반적인 이미지부터 시작합니다(그림 4, 명확하게 보이도록 4배 줌으로 표시).

    + + +

    그림 4. button.png

    + +

    그 다음 이 이미지에 SDK의 draw9patch 유틸리티(tools/ 디렉토리에 있음)를 실행합니다. 이 때 왼쪽 및 상단 테두리를 따라 픽셀을 그려 확대되어야 할 영역을 표시할 수 있습니다. 또한 오른쪽 및 하단 테두리를 따라 픽셀을 그려 콘텐츠가 들어가야 할 영역을 표시할 수 있으며 그 결과는 그림 5와 같습니다.

    + + +

    그림 5. button.9.png

    + +

    테두리를 따라 있는 검은색 픽셀을 눈여겨 보시기 바랍니다. 상단 및 왼쪽 테두리의 픽셀은 이미지가 확대될 수 있는 영역을 나타내며 오른쪽 및 하단 테두리는 콘텐츠가 위치해야 하는 영역을 나타냅니다.

    + +

    또한 .9.png 확장자를 확인하시기 바랍니다. 프레임워크는 이 확장자를 통해 이미지가 일반적인 PNG 이미지가 아닌 나인-패치 이미지임을 감지할 수 있으므로 이 확장자를 사용해야 합니다.

    + +

    android:background="@drawable/button"을 설정하여 이 배경을 구성요소에 적용하면 그림 6의 다양한 크기로 표시된 것처럼 프레임워크가 버튼의 크기를 수용할 수 있도록 이미지를 올바르게 확대합니다.

    + + +

    그림 6. 다양한 크기에 button.9.png 나인-패치를 사용하는 버튼

    + diff --git a/docs/html/intl/ru/training/monitoring-device-state/battery-monitoring.jd b/docs/html/intl/ru/training/monitoring-device-state/battery-monitoring.jd new file mode 100644 index 000000000000..26daf04bd1ce --- /dev/null +++ b/docs/html/intl/ru/training/monitoring-device-state/battery-monitoring.jd @@ -0,0 +1,120 @@ +page.title=Monitoring the Battery Level and Charging State +parent.title=Optimizing Battery Life +parent.link=index.html + +trainingnavtop=true +next.title=Determining and Monitoring the Docking State and Type +next.link=docking-monitoring.html + +@jd:body + + + +

    Если вы хотите изменить частоту фоновых обновлений, чтобы продлить время работы устройства от батареи, сначала рекомендуется проверить текущий уровень заряда и состояние зарядки.

    + +

    Именно от этих двух факторов зависит, как обновления повлияют на время работы устройства от батареи. Когда устройство подключено к сети переменного тока, приложение можно обновлять максимально часто, поскольку процесс обновления не будет сказываться на уровне заряда батареи. Если устройство не подключено к сети, следует воздержаться от обновлений, чтобы продлить время его работы от батареи.

    + +

    Если заряд батареи практически исчерпан, можно снизить частоту обновлений (вплоть до их полного прекращения).

    + + +

    Определение текущего состояния зарядки

    + +

    Начните с определения текущего состояния зарядки. {@link android.os.BatteryManager} передает все сведения о батарее и зарядке в закрепленном намерении {@link android.content.Intent}, которое содержит также информацию о состоянии зарядки.

    + +

    Поскольку это намерение является закрепленным, регистрировать {@link android.content.BroadcastReceiver} не нужно. Чтобы получить текущее состояние батареи в виде намерения, нужно вызвать {@code registerReceiver}, передав {@code null} в качестве приемника, как показано в коде ниже. Можно также передать фактический объект {@link android.content.BroadcastReceiver}, но это необязательно, поскольку обработка обновлений будет выполняться позднее.

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    +Intent batteryStatus = context.registerReceiver(null, ifilter);
    + +

    Можно извлечь данные как о текущем состоянии, так и об источнике зарядки (USB или сеть переменного тока), если устройство заряжается:

    + +

    // Are we charging / charged?
    +int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                     status == BatteryManager.BATTERY_STATUS_FULL;
    +
    +// How are we charging?
    +int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    + +

    Как правило, если устройство подключено к сети переменного тока, фоновые обновления можно выполнять с максимальной частотой. Если устройство заряжается через USB, частоту можно несколько сократить, а если устройство не подключено к сети – сократить еще больше.

    + + +

    Отслеживание изменений состояния зарядки

    + +

    Состояние зарядки изменяется всякий раз, когда пользователь подключает устройство к источнику питания. Поскольку это случается довольно часто, важно отслеживать изменения этого состояния и соответствующим образом корректировать частоту обновления приложения.

    + +

    {@link android.os.BatteryManager} передает действие каждый раз, когда устройство подключается к источнику питания или отключается от него. Важно получать эти события, даже если приложение не работает. Они помогут, в частности, определить, как часто будет запускаться приложение для выполнения фоновых обновлений. Чтобы отслеживать их, зарегистрируйте {@link android.content.BroadcastReceiver} в манифесте, задав {@link android.content.Intent#ACTION_POWER_CONNECTED} и {@link android.content.Intent#ACTION_POWER_DISCONNECTED} в фильтре намерений.

    + +
    <receiver android:name=".PowerConnectionReceiver">
    +  <intent-filter>
    +    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    +    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    +  </intent-filter>
    +</receiver>
    + +

    Соответствующая реализация {@link android.content.BroadcastReceiver} позволяет извлечь данные о текущем состоянии и способе зарядки, как описано в предыдущем шаге.

    + +
    public class PowerConnectionReceiver extends BroadcastReceiver {
    +    @Override
    +    public void onReceive(Context context, Intent intent) { 
    +        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                            status == BatteryManager.BATTERY_STATUS_FULL;
    +    
    +        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +        boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +        boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    +    }
    +}
    + + +

    Определение текущего уровня заряда батареи

    + +

    В некоторых случаях целесообразно определять текущий уровень заряда батареи. Если он ниже определенного значения, частоту фоновых обновлений следует уменьшить.

    + +

    Узнать, каков в настоящий момент заряд батареи, можно путем извлечения данных о текущем и максимальном уровне заряда из намерения состояния батареи, как показано в этом коде:

    + +
    int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    +int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    +
    +float batteryPct = level / (float)scale;
    + + +

    Отслеживание существенных изменений уровня заряда батареи

    + +

    Отслеживать состояние батареи непрерывно не следует,

    + +

    поскольку при этом нагрузка на батарею будет значительно выше, чем при обычной работе приложения. Рекомендуется отслеживать только существенные изменения уровня заряда, в частности, переход устройства в состояние низкого заряда и обратно.

    + +

    Фрагмент манифеста, приведенный ниже, относится к фильтру намерений в приемнике широковещательных намерений. Приемник срабатывает, когда батарея устройства переходит в состояние низкого заряда или выходит из него. Для этого прослушиваются события {@link android.content.Intent#ACTION_BATTERY_LOW} и {@link android.content.Intent#ACTION_BATTERY_OKAY}.

    + +
    <receiver android:name=".BatteryLevelReceiver">
    +<intent-filter>
    +  <action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
    +  <action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
    +  </intent-filter>
    +</receiver>
    + +

    Общепринятой практикой является отключение всех фоновых обновлений, когда заряд батареи достигает критически низкого уровня. Будет уже неважно, насколько актуальны данные в вашем приложении, если телефон самопроизвольно выключится, прежде чем пользователь успеет их просмотреть.

    + +

    Во многих случаях начало зарядки устройства совпадает с моментом его установки в док-станцию. В следующем уроке описаны способы определения текущего состояния подключения устройства к док-станции и отслеживания изменений этого состояния.

    + diff --git a/docs/html/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd b/docs/html/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd new file mode 100644 index 000000000000..ca1a9423692f --- /dev/null +++ b/docs/html/intl/ru/training/monitoring-device-state/connectivity-monitoring.jd @@ -0,0 +1,70 @@ +page.title=Determining and Monitoring the Connectivity Status +parent.title=Optimizing Battery Life +parent.link=index.html + +trainingnavtop=true + +previous.title=Determining and Monitoring the Docking State and Type +previous.link=docking-monitoring.html +next.title=Manipulating Broadcast Receivers On Demand +next.link=manifest-receivers.html + +@jd:body + + + +

    Чаще всего повторяющиеся оповещения и фоновые службы используются для планового обновления приложения из Интернета, кэширования или загрузки больших объемов данных. Однако если подключение к Интернету не установлено или скорость соединения слишком низкая, выполнять загрузку не имеет смысла.

    + +

    Проверить наличие подключения к Интернету и его тип можно с помощью {@link android.net.ConnectivityManager}.

    + + +

    Определение наличия подключения к Интернету

    + +

    Если подключение отсутствует, нет смысла планировать обновление из Интернета. В приведенном ниже коде показано, как использовать {@link android.net.ConnectivityManager} для отправки запросов об активной сети и определять возможности подключения.

    + +
    ConnectivityManager cm =
    +        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    + 
    +NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    +boolean isConnected = activeNetwork.isConnectedOrConnecting();
    + + +

    Определение типа подключения к Интернету

    + +

    Также можно определить тип доступного в настоящий момент подключения к Интернету.

    + +

    Устройство может подключаться по сети мобильной связи, WiMAX, Wi-Fi и Ethernet. Получив ответ на запрос о типе активной сети, как показано ниже, можно изменить частоту обновлений на основе ее пропускной способности.

    + +
    boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
    + +

    Стоимость передачи данных по мобильной сети, как правило, значительно выше, чем по сети Wi-Fi, поэтому частота обновлений в первом случае должна быть ниже. То же касается загрузки большого количества данных: ее следует отложить, пока не будет установлено подключение к сети Wi-Fi.

    + +

    Когда обновления отключены, необходимо отслеживать изменения доступных соединений, чтобы возобновить их сразу после подключения устройства к Интернету.

    + + +

    Отслеживание изменения возможностей подключения

    + +

    {@link android.net.ConnectivityManager} передает действие {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} ({@code "android.net.conn.CONNECTIVITY_CHANGE"}) при каждом изменении сведений о подключении. Зарегистрируйте в манифесте приемник широковещательных намерений, чтобы отслеживать эти изменения и запускать (или приостанавливать) фоновые обновления соответствующим образом.

    + +
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    + +

    Доступные соединения могут меняться очень часто – эта передача инициируется при каждом переключении между сетью мобильной связи и Wi-Fi. Ее рекомендуется отслеживать, только когда необходимо запускать ранее приостановленные обновления или загрузки. Как правило, достаточно проверить наличие подключения к Интернету перед запуском обновления и, если оно отсутствует, приостановить дальнейшие обновления до восстановления соединения.

    + +

    Для использования этого метода необходимо включать и отключать приемники широковещательных намерений, объявленные в манифесте. В следующем уроке описано, как это делать.

    diff --git a/docs/html/intl/ru/training/monitoring-device-state/docking-monitoring.jd b/docs/html/intl/ru/training/monitoring-device-state/docking-monitoring.jd new file mode 100644 index 000000000000..d94f3570458c --- /dev/null +++ b/docs/html/intl/ru/training/monitoring-device-state/docking-monitoring.jd @@ -0,0 +1,74 @@ +page.title=Determining and Monitoring the Docking State and Type +parent.title=Optimizing Battery Life +parent.link=index.html + +trainingnavtop=true +previous.title= Monitoring the Battery Level and Charging State +previous.link=battery-monitoring.html +next.title= Determining and Monitoring the Connectivity Status +next.link=connectivity-monitoring.html + +@jd:body + + + +

    Устройства под управлением ОС Android можно подключать к нескольким типам док-станций: настольным, которые делятся на цифровые и аналоговые, и автомобильным. В большинстве случаев устройства заряжаются при подключении к док-станции, поэтому состояние подключения к док-станции часто связано с состоянием зарядки.

    + +

    Насколько состояние подключения к док-станции влияет на частоту обновления, зависит от конкретного приложения. Например, можно увеличить частоту обновлений приложения, показывающего спортивные новости, когда устройство подключено к настольной док-станции, и полностью отключить обновления при подключении к автомобильной. И наоборот, если используется приложение, которое в фоновом режиме загружает данные о дорожной обстановке, то при подключении устройства к автомобильной док-станции следует выполнять обновления максимально часто.

    + +

    Состояние подключения к док-станции также передается в виде закрепленного намерения {@link android.content.Intent}, что позволяет запрашивать сведения о наличии подключения к док-станции и ее типе.

    + + +

    Определение текущего состояния подключения к док-станции

    + +

    Сведения о состоянии подключения к док-станции передаются в качестве дополнительных данных в закрепленном оповещении действия {@link android.content.Intent#ACTION_DOCK_EVENT}. Поскольку это закрепленное намерение, регистрировать {@link android.content.BroadcastReceiver} не требуется. Достаточно вызвать {@link android.content.Context#registerReceiver registerReceiver()}, передав {@code null} в качестве приемника широковещательных намерений, как показано в коде ниже.

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
    +Intent dockStatus = context.registerReceiver(null, ifilter);
    + +

    Сведения о текущем состоянии подключения к док-станции можно извлечь из дополнительных данных {@code EXTRA_DOCK_STATE}:

    + +

    int dockState = battery.getIntExtra(EXTRA_DOCK_STATE, -1);
    +boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
    + + +

    Определение типа док-станции

    + +

    Док-станция, к которой подключено устройство, может быть одного из четырех типов: +

    • автомобильная;
    • +
    • настольная;
    • +
    • настольная с минимальным набором функций (аналоговая);
    • +
    • настольная с широким набором функций (цифровая).

    + +

    Обратите внимание, что последние два типа поддерживаются только на уровне API 11, поэтому, даже если вас не интересует, является ли док-станция цифровой или аналоговой, а интересует только ее тип, рекомендуется выполнять проверку по всем трем типам:

    + +
    boolean isCar = dockState == EXTRA_DOCK_STATE_CAR;
    +boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK || 
    +                 dockState == EXTRA_DOCK_STATE_LE_DESK ||
    +                 dockState == EXTRA_DOCK_STATE_HE_DESK;
    + + +

    Отслеживание изменений состояния подключения к док-станции и ее типа

    + +

    При каждом подключении устройства к док-станции или отключении от нее передается действие {@link android.content.Intent#ACTION_DOCK_EVENT}. Чтобы отслеживать состояние подключения к док-станции, достаточно зарегистрировать в манифесте приложения приемник широковещательных намерений, как показано ниже.

    + +
    <action android:name="android.intent.action.ACTION_DOCK_EVENT"/>
    + +

    Данные о типе док-станции и о состоянии подключения к ней можно извлечь внутри реализации приемника с помощью методов, описанных в предыдущем шаге.

    diff --git a/docs/html/intl/ru/training/monitoring-device-state/index.jd b/docs/html/intl/ru/training/monitoring-device-state/index.jd new file mode 100644 index 000000000000..c87d9af5da4d --- /dev/null +++ b/docs/html/intl/ru/training/monitoring-device-state/index.jd @@ -0,0 +1,49 @@ +page.title=Optimizing Battery Life + +trainingnavtop=true +startpage=true +next.title=Monitoring the Battery Level and Charging State +next.link=battery-monitoring.html + +@jd:body + +
    +
    + +

    Требования

    + + +

    Дополнительные материалы

    + + +
    +
    + +

    Качественное приложение должно оказывать минимальное влияние на время работы устройства от батареи. В этом уроке вы научитесь создавать приложения, способные изменять функционал и режим работы в зависимости от состояния устройства.

    + +

    Отключение обновления данных фоновых служб при потере подключения и снижение частоты обновления при низком заряде батареи позволяет снизить расход энергии и продлить работу устройства без подзарядки.

    + +

    Уроки

    + + + +
    +
    Отслеживание уровня заряда батареи и состояния зарядки
    +
    Вы узнаете, как изменять частоту обновления приложения, определяя и отслеживая текущий уровень заряда батареи и изменение состояния зарядки.
    + +
    Отслеживание состояния подключения к док-станции и определение ее типа
    +
    Оптимальная частота обновления зависит от способа использования устройства. Вы узнаете, как определять и отслеживать состояние подключения к док-станции и ее тип, чтобы соответствующим образом корректировать работу приложения.
    + +
    Определение и отслеживание состояния подключения
    +
    Приложение невозможно обновить через Интернет, если отсутствует подключение. Вы узнаете, как проверить состояние подключения, чтобы при необходимости изменить частоту фоновых обновлений. Также вы научитесь проверять наличие мобильного подключения или подключения по сети Wi-Fi перед началом операций, требующих передачи больших объемов данных.
    + +
    Операции с приемниками широковещательных намерений по запросу
    +
    Приемники широковещательных намерений, объявленные в манифесте, можно включать и отключать во время работы приложения. Это позволяет отключать ненужные приемники в зависимости от состояния устройства. Вы узнаете, как повысить эффективность путем включения, отключения или каскадирования приемников изменения состояния и как отложить действие до момента перехода устройства в заданное состояние.
    +
    \ No newline at end of file diff --git a/docs/html/intl/ru/training/monitoring-device-state/manifest-receivers.jd b/docs/html/intl/ru/training/monitoring-device-state/manifest-receivers.jd new file mode 100644 index 000000000000..724ee93e2822 --- /dev/null +++ b/docs/html/intl/ru/training/monitoring-device-state/manifest-receivers.jd @@ -0,0 +1,50 @@ +page.title=Manipulating Broadcast Receivers On Demand +parent.title=Optimizing Battery Life +parent.link=index.html + +trainingnavtop=true + +previous.title=Determining and Monitoring the Connectivity Status +previous.link=connectivity-monitoring.html + +@jd:body + + + +

    Самый простой способ отслеживать изменения состояния устройства – создать приемники {@link android.content.BroadcastReceiver} для каждого отслеживаемого состояния и зарегистрировать их в манифесте приложения. Затем в каждом из этих приемников можно переопределять график повторяющихся оповещений в зависимости от текущего состояния устройства.

    + +

    Этот способ имеет недостатки: приложение активирует устройство при каждом запуске любого из этих приемников, что далеко не всегда оправданно.

    + +

    Оптимальный вариант – включать и выключать приемники широковещательных намерений во время работы приложения. Это позволяет использовать приемники, объявленные в манифесте, как пассивные оповещения, которые инициируются системными событиями только в случае необходимости.

    + + +

    Включение, отключение и каскадирование приемников изменения состояния для повышения эффективности

    + +

    {@link android.content.pm.PackageManager} позволяет включать и выключать любые компоненты, определенные в манифесте, в том числе все приемники широковещательных намерений:

    + +
    ComponentName receiver = new ComponentName(context, myReceiver.class);
    +
    +PackageManager pm = context.getPackageManager();
    +
    +pm.setComponentEnabledSetting(receiver,
    +        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    +        PackageManager.DONT_KILL_APP)
    + +

    При разрыве соединения этот метод позволяет выключить все приемники, кроме приемника изменения состояния подключения. И наоборот, когда подключение уже установлено, отслеживать изменения его состояния не требуется. Достаточно проверить наличие подключения к Интернету непосредственно перед обновлением или изменением графика оповещений о регулярном обновлении.

    + +

    Точно так же можно отложить загрузку, для выполнения которой требуется более высокая пропускная способность. Просто включите приемник широковещательных намерений, который будет отслеживать изменения возможности подключения и инициировать загрузку только после подключения к сети Wi-Fi.

    diff --git a/docs/html/intl/ru/training/multiscreen/adaptui.jd b/docs/html/intl/ru/training/multiscreen/adaptui.jd new file mode 100644 index 000000000000..490a64ad2de6 --- /dev/null +++ b/docs/html/intl/ru/training/multiscreen/adaptui.jd @@ -0,0 +1,212 @@ +page.title=Implementing Adaptative UI Flows +parent.title=Designing for Multiple Screens +parent.link=index.html + +trainingnavtop=true +previous.title=Supporting Different Screen Densities +previous.link=screendensities.html + +@jd:body + + + + + +

    Алгоритм пользовательского интерфейса зависит от макета, который в данный момент отображается. Например, если приложение работает в двухпанельном режиме, то при нажатии на элемент в левой панели содержание отобразится в правой. В однопанельном режиме содержание откроется отдельно (в другой активности).

    + + +

    Определение текущего макета

    + +

    Так как в реализации макетов существуют отличия, первое, что необходимо сделать, – определить, какой макет отображается в данный момент. Например, работает ли приложение в однопанельном или двухпанельном режиме. Для этого создадим запрос о том, существует ли данное представление и отображается ли оно в настоящий момент:

    + +
    +public class NewsReaderActivity extends FragmentActivity {
    +    boolean mIsDualPane;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main_layout);
    +
    +        View articleView = findViewById(R.id.article);
    +        mIsDualPane = articleView != null && 
    +                        articleView.getVisibility() == View.VISIBLE;
    +    }
    +}
    +
    + +

    Обратите внимание: представленный выше код содержит запрос о том, доступна ли панель article, поскольку это удобнее, чем писать отдельные запросы для каждого макета.

    + +

    Кроме того, для работы с учетом существующих компонентов можно также проверять их доступность, прежде чем выполнять с ними какие-либо операции. Например, в учебном приложении News Reader есть кнопка, которая служит для доступа в меню, однако она отображается только в операционных системах Android версии ниже, чем 3.0, потому что в последующих версиях ее функцию выполняет элемент {@link android.app.ActionBar} на уровне API 11 и выше. Чтобы проверить наличие этой кнопки, добавим прослушиватель событий с помощью следующего кода:

    + +
    +Button catButton = (Button) findViewById(R.id.categorybutton);
    +OnClickListener listener = /* create your listener here */;
    +if (catButton != null) {
    +    catButton.setOnClickListener(listener);
    +}
    +
    + + +

    Дальнейшие действия в зависимости от текущего макета

    + +

    Результаты некоторых операций зависят от текущего макета. Например, если в приложении News Reader в двухпанельном режиме нажать на заголовок в списке, то статья откроется в правой панели. Если же интерфейс работает в однопанельном режиме, будет запущена отдельная активность:

    + +
    +@Override
    +public void onHeadlineSelected(int index) {
    +    mArtIndex = index;
    +    if (mIsDualPane) {
    +        /* display article on the right pane */
    +        mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
    +    } else {
    +        /* start a separate activity */
    +        Intent intent = new Intent(this, ArticleActivity.class);
    +        intent.putExtra("catIndex", mCatIndex);
    +        intent.putExtra("artIndex", index);
    +        startActivity(intent);
    +    }
    +}
    +
    + +

    Аналогично, в двухпанельном режиме должна отображаться панель действий с навигационными вкладками, а в однопанельном навигация должна быть реализована с помощью раскрывающегося списка. Приложение должно проверять, какой из этих вариантов следует использовать:

    + +
    +final String CATEGORIES[] = { "Лучшие статьи", "Политика", "Экономика", "Новости технологий" };
    +
    +public void onCreate(Bundle savedInstanceState) {
    +    ....
    +    if (mIsDualPane) {
    +        /* use tabs for navigation */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
    +        int i;
    +        for (i = 0; i < CATEGORIES.length; i++) {
    +            actionBar.addTab(actionBar.newTab().setText(
    +                CATEGORIES[i]).setTabListener(handler));
    +        }
    +        actionBar.setSelectedNavigationItem(selTab);
    +    }
    +    else {
    +        /* use list navigation (spinner) */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
    +        SpinnerAdapter adap = new ArrayAdapter(this, 
    +                R.layout.headline_item, CATEGORIES);
    +        actionBar.setListNavigationCallbacks(adap, handler);
    +    }
    +}
    +
    + + +

    Повторное использование фрагментов в других активностях

    + +

    Одним из примеров повторяющегося фрагмента является реализация части интерфейса как панели в одних конфигурациях и как отдельной активности в других. Например, если приложение News Reader работает на достаточно большом экране, текст новостной статьи отображается в правой панели, а если на маленьком, то он открывается в отдельной активности.

    + +

    В таких случаях следует повторно использовать подкласс {@link android.app.Fragment} в нескольких активностях. Например, в двухпанельном макете используется подкласс ArticleFragment:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    Он же (без макета) используется при работе на маленьком экране (активность ArticleActivity):

    + +
    +ArticleFragment frag = new ArticleFragment();
    +getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
    +
    + +

    Результат будет таким же, как если бы мы объявили фрагмент в макете XML, однако в этом случае макет XML не требуется, так как фрагмент article является единственным компонентом этой активности.

    + +

    При создании фрагментов важно не привязывать их строго к конкретной активности. Для этого можно определить интерфейс с абстрактным описанием всех необходимых способов взаимодействия фрагмента с активностью, в которой он содержится. Затем этот интерфейс нужно реализовать в самой активности.

    + +

    Например, именно так работает фрагмент HeadlinesFragment в приложении News Reader:

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    OnHeadlineSelectedListener mHeadlineSelectedListener = null;
    +
    +    /* Must be implemented by host activity */
    +    public interface OnHeadlineSelectedListener {
    +        public void onHeadlineSelected(int index);
    +    }
    +    ...
    +
    +    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
    +        mHeadlineSelectedListener = listener;
    +    }
    +}
    +
    + +

    Затем, когда пользователь выбирает заголовок, фрагмент оповещает об этом не указанную в коде активность, а заданный ею прослушиватель:

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    @Override
    +    public void onItemClick(AdapterView<?> parent, 
    +                            View view, int position, long id) {
    +        if (null != mHeadlineSelectedListener) {
    +            mHeadlineSelectedListener.onHeadlineSelected(position);
    +        }
    +    }
    +    ...
    +}
    +
    + +

    Этот метод рассматривается подробнее в разделе Поддержка планшетных ПК и мобильных телефонов.

    + + +

    Обработка изменений конфигурации экрана

    + +

    При реализации отдельных частей интерфейса с помощью разных активностей нужно учитывать, что интерфейс должен уметь реагировать на определенные изменения конфигурации, такие как поворот экрана.

    + +

    Например, на типичном планшетном ПК с размером экрана 7 дюймов под управлением ОС Android 3.0 или более поздней версии при вертикальной ориентации статья в приложении News Reader открывается с помощью отдельной активности, а при горизонтальной используется двухпанельный макет.

    + +

    Это означает, что если пользователь держит планшетный ПК вертикально и на экране запущена активность для просмотра статьи, приложение должно уметь определить, что ориентация была изменена на горизонтальную. Затем оно должно соответствующим образом отреагировать на изменение, то есть завершить эту активность и вернуться к основной активности, чтобы содержание отобразилось в двухпанельном макете:

    + +
    +public class ArticleActivity extends FragmentActivity {
    +    int mCatIndex, mArtIndex;
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
    +        mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
    +
    +        // If should be in two-pane mode, finish to return to main activity
    +        if (getResources().getBoolean(R.bool.has_two_panes)) {
    +            finish();
    +            return;
    +        }
    +        ...
    +}
    +
    + + diff --git a/docs/html/intl/ru/training/multiscreen/index.jd b/docs/html/intl/ru/training/multiscreen/index.jd new file mode 100644 index 000000000000..023eaecff494 --- /dev/null +++ b/docs/html/intl/ru/training/multiscreen/index.jd @@ -0,0 +1,64 @@ +page.title=Designing for Multiple Screens + +trainingnavtop=true +startpage=true +next.title=Supporting Different Screen Sizes +next.link=screensizes.html + +@jd:body + +
    +
    + +

    Требования

    + + + +

    Дополнительные материалы

    + + + +

    Упражнение

    + + + +
    +
    + +

    На платформе Android работают устройства с самыми разными размерами экрана: от телефонов до телевизоров. Чтобы с вашим приложением могли работать как можно больше пользователей, оно должно корректно отображаться на всех этих устройствах.

    + +

    Однако совместимость с разными типами устройств – это еще не все. От размера экрана зависит, какие возможности будет иметь пользователь при работе с приложением. Чтобы пользователи действительно остались довольны вашим приложением, оно должно не просто поддерживать разные экраны, но и быть оптимизировано для каждого из них.

    + +

    Этот модуль посвящен реализации пользовательского интерфейса, оптимизированного для разных конфигураций экрана.

    + +

    Код, приведенный в каждом уроке, взят из учебного приложения, в котором демонстрируются способы оптимизации для разных экранов. Вы можете загрузить его (в правой части экрана) и использовать части кода в собственном приложении.

    + +

    Примечание. В этом модуле и в учебном приложении используется вспомогательная библиотека, позволяющая работать с API {@link android.app.Fragment} в версиях до Android 3.0. Чтобы иметь возможность использовать все необходимые API, загрузите библиотеку и добавьте ее в свое приложение.

    + + +

    Уроки

    + +
    +
    Поддержка разных размеров экрана
    +
    В этом уроке рассказывается, как создать макет, который адаптируется к разным размерам экрана, используя масштабируемые представления, объекты {@link android.widget.RelativeLayout}, квалификаторы размера и ориентации, фильтры псевдонимов и растровые изображений формата nine-patch.
    + +
    Поддержка разных разрешений экрана
    +
    В этом уроке рассказывается, как работать с экранами разного разрешения с помощью не зависящих от разрешения пикселей и как подготовить растровые изображения для каждого из них.
    + +
    Реализация адаптируемых алгоритмов работы пользовательского интерфейса
    +
    В этом уроке рассказывается, как реализовать алгоритм работы интерфейса, адаптирующийся к размеру и разрешению экрана, то есть способный определять активный макет во время выполнения приложения, выбирать дальнейшие действия на основе текущего макета и обрабатывать изменения конфигурации экрана.
    +
    diff --git a/docs/html/intl/ru/training/multiscreen/screendensities.jd b/docs/html/intl/ru/training/multiscreen/screendensities.jd new file mode 100644 index 000000000000..cfd472462824 --- /dev/null +++ b/docs/html/intl/ru/training/multiscreen/screendensities.jd @@ -0,0 +1,100 @@ +page.title=Supporting Different Densities +parent.title=Designing for Multiple Screens +parent.link=index.html + +trainingnavtop=true +previous.title=Supporting Different Screen Sizes +previous.link=screensizes.html +next.title=Implementing Adaptative UI Flows +next.link=adaptui.html + +@jd:body + + + + + +

    В этом уроке рассказывается, как создать интерфейс, поддерживающий разные разрешения экрана, за счет использования разных ресурсов и не зависящих от разрешения единиц измерения.

    + +

    Использование пикселей, не зависящих от разрешения

    + +

    Разработчики часто допускают одну и ту же ошибку при создании макетов – указывают размеры и расстояния с помощью абсолютных значений в пикселях. Задавать размеры в пикселях не рекомендуется, поскольку из-за различной плотности пикселей на экранах разных устройств фактический размер макета будет неодинаков. Всегда задавайте размеры в единицах dp или sp. dp – это не зависящий от разрешения пиксель, равный физическому пикселю на экране с плотностью 160 точек/дюйм. sp является аналогичной единицей измерения, но масштабируется на основе выбранного пользователем размера текста, поэтому ее следует применять для указания величины шрифта, но не размера макета.

    + +

    Например, если вы задаете расстояние между двумя представлениями, рекомендуется использовать dp, а не px:

    + +
    +<Button android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content" 
    +    android:text="@string/clickme"
    +    android:layout_marginTop="20dp" />
    +
    + +

    Для определения размера шрифта всегда используйте sp:

    + +
    +<TextView android:layout_width="match_parent" 
    +    android:layout_height="wrap_content" 
    +    android:textSize="20sp" />
    +
    + + +

    Предоставление альтернативных растровых изображений

    + +

    Так как платформа Android предназначена для устройств с разными разрешениями экрана, необходимо позаботиться о наличии растровых изображений для каждого из четырех обобщенных типов разрешения: низкого, среднего, высокого и очень высокого. Это обеспечит оптимальное сочетание качества графики и производительности на всех устройствах.

    + +

    На основе исходного векторного рисунка создайте растровые изображения для каждого из указанных разрешений согласно следующей шкале размеров:

    + +

      +
    • xhdpi: 2,0 +
    • hdpi: 1,5 +
    • mdpi: 1,0 (стандартный размер) +
    • ldpi: 0,75 +

    + +

    Это означает, что изображение, которое на устройствах с разрешением экрана xhdpi имеет размер 200 x 200, на устройствах hdpi должно иметь размер 150 x 150, на устройствах mdpi – 100 x 100, а на устройствах ldpi – 75 x 75.

    + +

    Поместите файлы изображений в соответствующие подкаталоги в папке res/, и система автоматически выберет подходящий в зависимости от разрешения экрана устройства, на котором выполняется приложение:

    + +
    +MyProject/
    +  res/
    +    drawable-xhdpi/
    +        awesomeimage.png
    +    drawable-hdpi/
    +        awesomeimage.png
    +    drawable-mdpi/
    +        awesomeimage.png
    +    drawable-ldpi/
    +        awesomeimage.png
    +
    + +

    При каждом обращении к файлу @drawable/awesomeimage система будет выбирать изображение, отвечающее разрешению экрана.

    + +

    Дополнительную информацию и советы можно найти в разделе Рекомендации по созданию значков.

    + diff --git a/docs/html/intl/ru/training/multiscreen/screensizes.jd b/docs/html/intl/ru/training/multiscreen/screensizes.jd new file mode 100644 index 000000000000..9684d77486dd --- /dev/null +++ b/docs/html/intl/ru/training/multiscreen/screensizes.jd @@ -0,0 +1,279 @@ +page.title=Supporting Different Screen Sizes +parent.title=Designing for Multiple Screens +parent.link=index.html + +trainingnavtop=true +next.title=Supporting Different Screen Densities +next.link=screendensities.html + +@jd:body + + + + + +

    В этом уроке описаны следующие аспекты обеспечения совместимости интерфейса с разными экранами:

    +
      +
    • обеспечение способности макета адаптироваться к размеру экрана;
    • +
    • выбор макета интерфейса, отвечающего конфигурации экрана;
    • +
    • контроль правильности применяемого макета;
    • +
    • использование масштабируемых растровых изображений.
    • +
    + + +

    Использование параметров wrap_content и match_parent

    + +

    Чтобы создать масштабируемый макет, способный адаптироваться к разным экранам, используйте в качестве значений ширины и высоты отдельных компонентов представления параметры "wrap_content" и "match_parent". Если используется "wrap_content", для ширины или высоты представления устанавливается минимальное значение, позволяющее уместить содержание на экран, а параметр "match_parent" (известный как "fill_parent" в API до 8 уровня) служит для растягивания компонента по размеру родительского представления.

    + +

    Если указать параметры "wrap_content" и "match_parent" вместо строго заданных размеров, в представлениях будет использоваться минимально необходимое место или они будут растягиваться на всю доступную длину и ширину соответственно. Например:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    Обратите внимание на то, что в коде учебного приложения размеры компонентов заданы с помощью параметров "wrap_content" и "match_parent". В результате макет правильно отображается на экранах разных размеров при разных ориентациях.

    + +

    Например, вот так он выглядит в вертикальной и горизонтальной ориентациях. Обратите внимание на то, как размеры компонентов автоматически адаптируются к длине и ширине:

    + + +

    Рисунок 1. Приложение News Reader при вертикальной (слева) и горизонтальной (справа) ориентации.

    + + +

    Использование объекта RelativeLayout

    + +

    С помощью вложенных экземпляров объекта {@link android.widget.LinearLayout} и параметров "wrap_content" и "match_parent" можно создавать достаточно сложные макеты. Однако {@link android.widget.LinearLayout} не дает возможности точно управлять взаимным расположением дочерних представлений: в {@link android.widget.LinearLayout} они просто помещаются в ряд друг за другом. Если необходимо расположить дочерние представления иным образом, используйте объект {@link android.widget.RelativeLayout}, позволяющий задать относительные позиции компонентов. Например, одно дочернее представление можно выровнять по левому краю экрана, а другое – по правому.

    + +

    Например:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="match_parent"
    +    android:layout_height="match_parent">
    +    <TextView
    +        android:id="@+id/label"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:text="Type here:"/>
    +    <EditText
    +        android:id="@+id/entry"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/label"/>
    +    <Button
    +        android:id="@+id/ok"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/entry"
    +        android:layout_alignParentRight="true"
    +        android:layout_marginLeft="10dp"
    +        android:text="OK" />
    +    <Button
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_toLeftOf="@id/ok"
    +        android:layout_alignTop="@id/ok"
    +        android:text="Cancel" />
    +</RelativeLayout>
    +
    + +

    На рис. 2 показано, как этот макет выглядит на экране QVGA.

    + + +

    Рисунок 2. Скриншот экрана QVGA (маленького размера).

    + +

    На рис. 3 показано, как он выглядит на экране с большей диагональю.

    + + +

    Рисунок 3. Скриншот экрана WSVGA (большего размера).

    + +

    Обратите внимание: несмотря на изменение размера компонентов их взаимное расположение остается прежним, так как оно задано объектом {@link android.widget.RelativeLayout.LayoutParams}.

    + + +

    Использование квалификаторов размера

    + +

    Масштабируемые или относительные макеты, один из которых продемонстрирован выше, имеют свои ограничения. Хотя они позволяют создать интерфейс, способный адаптироваться к разным экранам за счет растягивания пространства внутри и вокруг компонентов, пользователю может оказаться не слишком удобно работать с таким интерфейсом. Поэтому в приложении должен использоваться не один масштабируемый макет, а несколько альтернативных вариантов для разных конфигураций экрана. Их можно создать с помощью квалификаторов конфигураций, которые позволяют оперативно выбирать ресурсы, отвечающие текущим параметрам экрана (например, разные варианты макетов для экранов разных размеров).

    + +

    Многие приложения отображаются на больших экранах в двухпанельном режиме, при котором список элементов расположен в одной панели, а их содержание открывается в другой. Такой режим просмотра удобен на достаточно больших экранах планшетных ПК и телевизоров, однако на экране телефона эти панели следует отображать по отдельности. Для каждого режима просмотра нужно создать отдельный файл.

    + +
      +
    • res/layout/main.xml, однопанельный макет (по умолчанию): + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-large/main.xml, двухпанельный макет: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    Обратите внимание, что во втором случае в названии каталога использован квалификатор large. Этот макет будет выбран на устройствах, экраны которых считаются большими (например, 7 дюймов и более). Первый макет (без квалификаторов) будет выбран для устройств с маленьким экраном.

    + + +

    Использование квалификатора Smallest-width

    + +

    Одной из проблем, с которой сталкивались разработчики приложений для устройств Android версий до 3.2, было слишком общее определение "большого" экрана. Это касалось устройств Dell Streak, первой модели Galaxy Tab и планшетных ПК с экраном размером 7 дюймов. Многие приложения требовалось по-разному отображать на разных устройствах (например, с 5- и 7-дюймовыми экранами), хотя они и относились к одной категории "больших" экранов. В Android версии 3.2 и более поздних доступен квалификатор Smallest-width.

    + +

    Он позволяет определять экраны с заданной минимальной шириной в dp. Например, типичный планшетный ПК с экраном 7 дюймов имеет минимальную ширину 600 dp, и если вы хотите, чтобы приложение работало на нем в двухпанельном режиме (а на меньших экранах в однопанельном), используйте два макета из предыдущего раздела, но вместо квалификатора размера large укажите sw600dp. В таком случае на экранах, минимальная ширина которых составляет 600 dp, будет использоваться двухпанельный макет.

    + +
      +
    • res/layout/main.xml, однопанельный макет (по умолчанию): + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-sw600dp/main.xml, двухпанельный макет: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    Это означает, что на устройствах, минимальная ширина экрана которых не меньше 600 dp, будет выбран layout-sw600dp/main.xml (двухпанельный макет), а на экранах меньшего размера – layout/main.xml (однопанельный макет).

    + +

    Следует учесть, что на Android-устройствах до версии 3.2 квалификатор sw600dp не будет работать, поэтому для них по-прежнему нужно использовать large. Таким образом, вам потребуется еще один файл с названием res/layout-large/main.xml, идентичный файлу res/layout-sw600dp/main.xml. В следующем разделе вы познакомитесь с методом, который позволяет избежать дублирования таких файлов макета.

    + + +

    Использование псевдонимов макетов

    + +

    Квалификатор Smallest-width работает только на устройствах Android 3.2 или более поздних версий. Для совместимости с более ранними устройствами по-прежнему следует использовать абстрактные размеры (small, normal, large и xlarge). Например, чтобы интерфейс открывался в однопанельном режиме на телефонах и в многопанельном на планшетных ПК с 7-дюймовым экраном, телевизорах и других крупных устройствах, подготовьте следующие файлы:

    + +

      +
    • res/layout/main.xml: однопанельный макет;
    • +
    • res/layout-large: многопанельный макет;
    • +
    • res/layout-sw600dp: многопанельный макет.
    • +

    + +

    Последние два файла идентичны: один из них предназначен для устройств Android 3.2 и новее, а второй для более старых планшетных ПК и телевизоров на платформе Android.

    + +

    Чтобы не создавать дубликаты файлов и упростить процесс поддержки приложения, используйте псевдонимы. Например, можно определить следующие макеты:

    + +
      +
    • res/layout/main.xml (однопанельный макет);
    • +
    • res/layout/main_twopanes.xml (двухпанельный макет).
    • +
    + +

    Затем добавьте следующие два файла:

    + +

      +
    • res/values-large/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      +
    • + +
    • res/values-sw600dp/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      + +
    • +

    + +

    Содержание последних двух файлов одинаково, но сами по себе они не определяют макет. Они служат для того, чтобы назначить файл {@code main} в качестве псевдонима {@code main_twopanes}. Так как в них используются селекторы large и sw600dp, они применяются к планшетным ПК и телевизорам на платформе Android независимо от версии (для версий до 3.2 используется +{@code large}, а для более новых – sw600dp).

    + + +

    Использование квалификаторов ориентации

    + +

    Хотя некоторые макеты одинаково хорошо смотрятся в вертикальной и горизонтальной ориентациях, в большинстве случаев интерфейс все же приходится адаптировать. Ниже показано, как изменяется макет в приложении News Reader в зависимости от размера и ориентации экрана.

    + +

      +
    • Маленький экран, вертикальная ориентация: однопанельный вид с логотипом.
    • +
    • Маленький экран, горизонтальная ориентация: однопанельный вид с логотипом.
    • +
    • Планшетный ПК с 7-дюймовым экраном, вертикальная ориентация: однопанельный вид с панелью действий.
    • +
    • Планшетный ПК с 7-дюймовым экраном, горизонтальная ориентация: двухпанельный вид с панелью действий.
    • +
    • Планшетный ПК с 10-дюймовым экраном, вертикальная ориентация: двухпанельный вид (узкий вариант) с панелью действий.
    • +
    • Планшетный ПК с 10-дюймовым экраном, горизонтальная ориентация: двухпанельный вид (широкий вариант) с панелью действий.
    • +
    • Телевизор, горизонтальная ориентация: двухпанельный вид с панелью действий.
    • +

    + +

    Каждый из этих макетов определен в XML-файле в каталоге res/layout/. Чтобы сопоставить их с определенными конфигурациями экрана, в приложении используются псевдонимы:

    + +

    res/layout/onepane.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} + +

    res/layout/onepane_with_bar.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    res/layout/twopanes.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    res/layout/twopanes_narrow.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes_narrow.xml all} + +

    После того как все возможные макеты определены, остается сопоставить каждый из них с подходящей конфигурацией, используя квалификаторы конфигураций. Воспользуемся псевдонимами макетов:

    + +

    res/values/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values/layouts.xml all} + +

    res/values-sw600dp-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-land/layouts.xml +all} + +

    res/values-sw600dp-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-port/layouts.xml +all} + +

    res/values-large-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-land/layouts.xml all} + +

    res/values-large-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-port/layouts.xml all} + + + +

    Использование растровых изображений nine-patch

    + +

    Чтобы интерфейс был совместим с экранами разных размеров, используемые в нем графические элементы также должны быть адаптированы соответствующим образом. Например, фон кнопки должен одинаково хорошо выглядеть независимо от ее формы.

    + +

    Если использовать для компонентов, размеры которых меняются, обычные изображения, то они будут равномерно сжиматься и растягиваться, и результат будет далек от идеального. Решением являются растровые изображения формата nine-patch – специальные PNG-файлы, содержащие информацию о том, какие области можно растягивать, а какие нет.

    + +

    Создавая растровые изображения для масштабируемых компонентов, обязательно используйте формат nine-patch. На рис. 4 показано обычное растровое изображение (увеличенное в 4 раза для наглядности), которое мы переведем в формат nine-patch.

    + + +

    Рисунок 4. button.png

    + +

    Откройте его с помощью утилиты draw9patch, входящей в комплект разработчика (в каталоге tools/). Установите метки на левом и верхнем краях, чтобы ограничить области, которые можно растягивать. Можно также провести линию вдоль правого и нижнего краев, как показано на рис. 5, чтобы отметить области, в которых содержание должно быть зафиксировано.

    + + +

    Рисунок 5. button.9.png

    + +

    Обратите внимание на черные пиксели по краям. Метки у верхней и левой границ обозначают те области, которые можно растягивать, а метки у правой и нижней границ – те, куда должно быть помещено содержание.

    + +

    Также обратите внимание на расширение .9.png. Оно должно быть задано именно в таком виде, чтобы система могла определить, что это формат nine-patch, а не обычный PNG-файл.

    + +

    При применении этого фона к компоненту (с помощью android:background="@drawable/button") изображение будет растянуто по размеру кнопки, как показано на рис. 6.

    + + +

    Рисунок 6. Кнопки разных размеров с файлом фона button.9.png в формате nine-patch.

    + diff --git a/docs/html/intl/zh-CN/training/monitoring-device-state/battery-monitoring.jd b/docs/html/intl/zh-CN/training/monitoring-device-state/battery-monitoring.jd new file mode 100644 index 000000000000..0e1ccb739168 --- /dev/null +++ b/docs/html/intl/zh-CN/training/monitoring-device-state/battery-monitoring.jd @@ -0,0 +1,120 @@ +page.title=监控电池电量和充电状态 +parent.title=优化电池使用时间 +parent.link=index.html + +trainingnavtop=true +next.title=确定和监控基座对接状态和类型 +next.link=docking-monitoring.html + +@jd:body + + + +

    如果您要更改后台更新频率,从而减少更新对电池使用时间的影响,最好先查看当前的电池电量和充电状态。

    + +

    对应用进行更新会影响电池使用时间,具体取决于设备的电池电量和充电状态。如果用户正在通过交流电源为设备充电,更新应用的影响就可以忽略不计。因此,在大多数情况下,只要设备连接了充电器,您就可以最大程度地提高刷新频率。相反,如果设备在消耗电池电量,那么降低更新频率就可以延长电池使用时间。

    + +

    同样,您也可以查看电池电量,如果电量即将耗尽,您就可以降低更新频率,甚至停止更新。

    + + +

    确定当前的充电状态

    + +

    请先确定当前的充电状态。{@link android.os.BatteryManager} 会通过一个包含充电状态的持续 {@link android.content.Intent} 广播所有的电池详情和充电详情。

    + +

    由于这是个持续 intent,因此您无需通过将传入 {@code null} 的 {@code registerReceiver} 作为接收器直接调用(如下一代码段所示)来注册 {@link android.content.BroadcastReceiver},系统会返回当前电池状态 intent。您可以在此处传入实际的 {@link android.content.BroadcastReceiver} 对象,不过我们会在下文中介绍如何处理更新,因此您不一定要执行此操作。

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    +Intent batteryStatus = context.registerReceiver(null, ifilter);
    + +

    如果设备正在充电,则您可以提取当前的充电状态和充电方式(无论是通过 USB 还是交流充电器),如下所示:

    + +

    // Are we charging / charged?
    +int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                     status == BatteryManager.BATTERY_STATUS_FULL;
    +
    +// How are we charging?
    +int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    + +

    通常,如果设备连接了交流充电器,您就应最大程度地提高后台更新频率;如果设备通过 USB 充电,请降低更新频率;如果电池在耗电,请进一步降低更新频率。

    + + +

    监控充电状态的变化

    + +

    充电状态的改变就像设备连接电源那样容易,因此监控充电状态的变化并相应地调整刷新频率就很重要了。

    + +

    只要设备连接或断开电源,{@link android.os.BatteryManager} 就会广播相应的操作。即使您的应用没有运行,也请务必接收这些事件,尤其是当这些事件会影响您启动应用以执行后台更新的频率时。因此,您应该通过在 intent 过滤器中定义 {@link android.content.Intent#ACTION_POWER_CONNECTED} 和 {@link android.content.Intent#ACTION_POWER_DISCONNECTED},在清单中注册 {@link android.content.BroadcastReceiver} 来侦听这两个事件。

    + +
    <receiver android:name=".PowerConnectionReceiver">
    +  <intent-filter>
    +    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    +    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    +  </intent-filter>
    +</receiver>
    + +

    在实施相关的 {@link android.content.BroadcastReceiver} 时,您可以按上一步骤所述提取当前的充电状态和充电方式。

    + +
    public class PowerConnectionReceiver extends BroadcastReceiver {
    +    @Override
    +    public void onReceive(Context context, Intent intent) { 
    +        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    +        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
    +                            status == BatteryManager.BATTERY_STATUS_FULL;
    +    
    +        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    +        boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
    +        boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;
    +    }
    +}
    + + +

    确定当前的电池电量

    + +

    在某些情况下,确定当前的电池电量会对您有所帮助。如果电池电量低于一定水平,您可以降低后台更新频率。

    + +

    您可以从电池状态 intent 中提取要了解的当前电池电量以及电池容量,具体如下所示:

    + +
    int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    +int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    +
    +float batteryPct = level / (float)scale;
    + + +

    监控电池电量的显著变化

    + +

    您无法轻松地对电池状态进行持续监控,不过也无需这么做。

    + +

    一般来说,与应用的正常行为相比,持续监控电池电量会消耗更多电量。因此,比较合适的做法是只监控电池电量的显著变化(尤其是在设备进入或结束低电量状态的情况下)。

    + +

    以下清单代码段提取自广播接收器中的 intent 过滤器元素。通过侦听 {@link android.content.Intent#ACTION_BATTERY_LOW} 和 {@link android.content.Intent#ACTION_BATTERY_OKAY},只要设备的电池进入或结束低电量状态,系统就会触发接收器。

    + +
    <receiver android:name=".BatteryLevelReceiver">
    +<intent-filter>
    +  <action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
    +  <action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
    +  </intent-filter>
    +</receiver>
    + +

    如果电池电量极低,通常比较合适的做法是停用所有后台更新。如果您还没用上更新的数据,手机就自动关机了,那这些数据再新也没有意义。

    + +

    在很多情况下,将设备插入基座就可以为其充电。下一教程将向您介绍如何确定当前基座状态及如何监控设备对接的变化。

    + diff --git a/docs/html/intl/zh-CN/training/monitoring-device-state/connectivity-monitoring.jd b/docs/html/intl/zh-CN/training/monitoring-device-state/connectivity-monitoring.jd new file mode 100644 index 000000000000..8313e089b908 --- /dev/null +++ b/docs/html/intl/zh-CN/training/monitoring-device-state/connectivity-monitoring.jd @@ -0,0 +1,70 @@ +page.title=确定和监控网络连接状态 +parent.title=优化电池使用时间 +parent.link=index.html + +trainingnavtop=true + +previous.title=确定和监控基座对接状态和类型 +previous.link=docking-monitoring.html +next.title=根据需要操作广播接收器 +next.link=manifest-receivers.html + +@jd:body + + + +

    重复提醒和后台服务最常见的用途之一,就是为来自互联网资源的应用数据、缓存数据安排定期更新或执行长时间运行的下载任务。但是,如果您没有连接互联网,或因连接过慢而无法完成下载,那就根本没必要唤醒设备并安排更新了。

    + +

    您可以使用 {@link android.net.ConnectivityManager} 查看是否确实已连接互联网,如果已连接,您还可以了解当前的连接类型。

    + + +

    确定是否已连接互联网

    + +

    如果设备未连接互联网,就没有必要根据互联网资源安排更新了。以下代码段说明如何使用 {@link android.net.ConnectivityManager} 查询有效网络并确定该网络是否已连接互联网。

    + +
    ConnectivityManager cm =
    +        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    + 
    +NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    +boolean isConnected = activeNetwork.isConnectedOrConnecting();
    + + +

    确定互联网连接的类型

    + +

    您也可以确定当前可用的互联网连接的类型。

    + +

    通过移动数据、WiMAX、Wi-Fi 和以太网连接可提供设备连接。您可以查询有效网络的类型(具体如下所示),以便根据可用带宽调整刷新频率。

    + +
    boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
    + +

    移动数据的费用往往比 Wi-Fi 高很多,因此在大多数情况下,如果您使用的是移动连接,就应降低应用更新频率。同样,在没有 Wi-Fi 连接的情况下,您就应暂停较大的下载任务。

    + +

    停用更新后,请务必侦听连接情况的变化,以便在建立互联网连接后恢复更新。

    + + +

    监控连接情况的变化

    + +

    只要连接的具体情况发生变化,{@link android.net.ConnectivityManager} 就会广播 {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION} ({@code "android.net.conn.CONNECTIVITY_CHANGE"}) 操作。您可以在清单中注册广播接收器,以便侦听这些变化并相应地恢复(或暂停)后台更新。

    + +
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    + +

    设备连接情况的变化可能会非常频繁,只要您在移动数据和 Wi-Fi 之间相互切换,系统就会触发此广播。因此比较合适的做法是,仅当之前暂停了更新或下载时才监控此广播,以便恢复更新或下载。通常,您只需在开始更新前检查互联网连接情况即可,如果未连接互联网,请暂停后续更新,直到连接恢复。

    + +

    此技巧需要切换您在清单中声明的广播接收器,具体说明请见下一教程。

    diff --git a/docs/html/intl/zh-CN/training/monitoring-device-state/docking-monitoring.jd b/docs/html/intl/zh-CN/training/monitoring-device-state/docking-monitoring.jd new file mode 100644 index 000000000000..53b951dd584e --- /dev/null +++ b/docs/html/intl/zh-CN/training/monitoring-device-state/docking-monitoring.jd @@ -0,0 +1,74 @@ +page.title=确定和监控基座对接状态和类型 +parent.title=优化电池使用时间 +parent.link=index.html + +trainingnavtop=true +previous.title= 监控电池电量和充电状态 +previous.link=battery-monitoring.html +next.title= 确定和监控网络连接状态 +next.link=connectivity-monitoring.html + +@jd:body + + + +

    Android 设备支持几种不同类型的基座。这些类型包括车载或家用基座以及数字和模拟基座。许多基座可用于为插入的设备充电,因此基座状态通常与充电状态紧密相关。

    + +

    您可以根据手机的基座状态调整更新频率,具体取决于相关应用。如果设备插入的是桌面基座,您就可以提高体育中心类应用的更新频率;如果设备插入的是车载基座,您就可以完全停用此类更新。相反,如果设备插入的是车载基座且后台服务正在更新路况,您就可以最大程度地提高更新频率。

    + +

    系统是以持续 {@link android.content.Intent} 的形式广播基座状态的,这样您就可以查询设备是否插入了基座,如果已插入,您还可以查询基座类型。

    + + +

    确定当前的基座状态

    + +

    基座状态详情是以附加信息的形式包含在 {@link android.content.Intent#ACTION_DOCK_EVENT} 操作的持续广播中的。由于这属于持续广播,因此您无需注册 {@link android.content.BroadcastReceiver}。您可以将传入 {@code null} 的 {@link android.content.Context#registerReceiver registerReceiver()} 作为广播接收器直接调用,具体如下一代码段所示。

    + +
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
    +Intent dockStatus = context.registerReceiver(null, ifilter);
    + +

    您可以从 {@code EXTRA_DOCK_STATE} 附加信息中提取当前的基座对接状态:

    + +

    int dockState = battery.getIntExtra(EXTRA_DOCK_STATE, -1);
    +boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
    + + +

    确定当前的基座类型

    + +

    用户可以将设备插入以下四种类型的基座: +

    • 车载基座
    • +
    • 桌面基座
    • +
    • 低端(模拟)桌面基座
    • +
    • 高端(数字)桌面基座

    + +

    请注意,后两种类型仅适用于 API 级别为 11 及以上的 Android,因此如果您只关注基座类型,而不在意基座究竟是数字的还是模拟的,那么比较合适的做法就是查看全部三种类型:

    + +
    boolean isCar = dockState == EXTRA_DOCK_STATE_CAR;
    +boolean isDesk = dockState == EXTRA_DOCK_STATE_DESK || 
    +                 dockState == EXTRA_DOCK_STATE_LE_DESK ||
    +                 dockState == EXTRA_DOCK_STATE_HE_DESK;
    + + +

    监控基座状态或类型的变化

    + +

    无论设备是否插入了基座,系统都会广播 {@link android.content.Intent#ACTION_DOCK_EVENT} 操作。要监控设备基座状态的变化,您只需在应用清单中注册广播接收器即可,具体如以下代码段所示:

    + +
    <action android:name="android.intent.action.ACTION_DOCK_EVENT"/>
    + +

    您可以使用上一步骤中所述的技术在接收器实施过程中提取基座的类型和状态。

    diff --git a/docs/html/intl/zh-CN/training/monitoring-device-state/index.jd b/docs/html/intl/zh-CN/training/monitoring-device-state/index.jd new file mode 100644 index 000000000000..aa107539eeca --- /dev/null +++ b/docs/html/intl/zh-CN/training/monitoring-device-state/index.jd @@ -0,0 +1,49 @@ +page.title=优化电池使用时间 + +trainingnavtop=true +startpage=true +next.title=监控电池电量和充电状态 +next.link=battery-monitoring.html + +@jd:body + +
    +
    + +

    依存关系和前提条件

    + + +

    您还应参阅

    + + +
    +
    + +

    为了打造一个优秀的应用,您应设法降低应用对电池使用时间的影响。阅读完本教程后,您就可以让自己构建的应用根据其所在设备的状态来监控和调整自身的功能和行为。

    + +

    要确保在不影响用户体验的情况下最大程度地降低应用对电池使用时间的影响,您可以采取一些措施,例如在网络连接断开时停用后台服务更新,或在电池电量较低时降低此类更新的频率。

    + +

    教程

    + + + +
    +
    监控电池电量和充电状态
    +
    了解如何通过确定和监控当前的电池电量和充电状态的变化来相应地调整应用的更新频率。
    + +
    确定和监控基座对接状态和类型
    +
    最佳刷新频率可能各有不同,具体取决于安装了相关应用的设备的使用方式。了解如何确定和监控所用基座的对接状态和类型,以便相应地调整应用的行为。
    + +
    确定和监控网络连接状态
    +
    如果没有互联网连接,您就无法通过在线来源更新应用。了解如何查看连接状态,以便相应地调整后台更新频率。您还可以了解如何在执行高带宽操作前查看 Wi-Fi 或移动连接的状态。
    + +
    根据需要操作广播接收器
    +
    您可以在运行时切换自己在清单中声明的广播接收器,以便根据当前设备状态停用不需要的接收器。了解如何在设备未处于特定状态的情况下切换和层叠状态变化接收器和延迟操作,以便提高效率。
    +
    \ No newline at end of file diff --git a/docs/html/intl/zh-CN/training/monitoring-device-state/manifest-receivers.jd b/docs/html/intl/zh-CN/training/monitoring-device-state/manifest-receivers.jd new file mode 100644 index 000000000000..07c014f10a31 --- /dev/null +++ b/docs/html/intl/zh-CN/training/monitoring-device-state/manifest-receivers.jd @@ -0,0 +1,50 @@ +page.title=根据需要操作广播接收器 +parent.title=优化电池使用时间 +parent.link=index.html + +trainingnavtop=true + +previous.title=确定和监控网络连接状态 +previous.link=connectivity-monitoring.html + +@jd:body + +
    +
    + +

    本教程将指导您

    +
      +
    1. 切换和层叠状态变化接收器以提高效率
    2. +
    + + +

    您还应参阅

    + + +
    +
    + +

    监控设备状态变化的最简单方法就是,为您监控的每种状态创建 {@link android.content.BroadcastReceiver} 并在应用清单中逐一进行注册。然后,您只需根据当前设备状态在每个接收器中重新安排重复提醒即可。

    + +

    此方法的负面影响在于,只要系统触发了这些接收器中的任何一个,相关应用就会唤醒设备,其频率可能会远远超过所需的水平。

    + +

    更好的方法是在运行时停用或启用广播接收器。这样的话,您就可以将自己在清单中声明的接收器用作被动提醒,只有在需要时才会由系统事件触发。

    + + +

    切换和层叠状态变化接收器以提高效率

    + +

    您可以使用 {@link android.content.pm.PackageManager} 切换清单中定义的任意组件的启用状态(包括您要启用或停用的任意广播接收器),具体如以下片段所示:

    + +
    ComponentName receiver = new ComponentName(context, myReceiver.class);
    +
    +PackageManager pm = context.getPackageManager();
    +
    +pm.setComponentEnabledSetting(receiver,
    +        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    +        PackageManager.DONT_KILL_APP)
    + +

    在使用此技巧时,如果您确定连接已断开,就可以停用除连接变化接收器外的所有接收器。相反,成功连接后,您就可以停止侦听连接变化,同时只需在执行更新和重新安排重复更新提醒前查看是否在线即可。

    + +

    您可以使用同样的方法来延迟需要较高带宽的下载任务。只有在连接 Wi-Fi 后,您才能直接启用用于侦听连接变化和启动下载任务的广播接收器。

    diff --git a/docs/html/intl/zh-CN/training/multiscreen/adaptui.jd b/docs/html/intl/zh-CN/training/multiscreen/adaptui.jd new file mode 100644 index 000000000000..89908fe46ef9 --- /dev/null +++ b/docs/html/intl/zh-CN/training/multiscreen/adaptui.jd @@ -0,0 +1,212 @@ +page.title=实施自适应用户界面流程 +parent.title=针对多种屏幕进行设计 +parent.link=index.html + +trainingnavtop=true +previous.title=支持各种屏幕密度 +previous.link=screendensities.html + +@jd:body + + + +
    +
    + +

    本教程将指导您

    + +
      +
    1. 确定当前布局
    2. +
    3. 根据当前布局做出响应
    4. +
    5. 重复使用其他活动中的片段
    6. +
    7. 处理屏幕配置变化
    8. +
    + +

    您还应参阅

    + + + +

    试试看

    + +
    +下载示例应用 +

    NewsReader.zip

    +
    + + +
    +
    + +

    根据您的应用当前显示的布局,用户界面流程可能会有所不同。例如,如果您的应用处于双面板模式下,点击左侧面板上的项即可直接在右侧面板上显示相关内容;如果该应用处于单面板模式下,相关内容就应以其他活动的形式在同一面板上显示。

    + + +

    确定当前布局

    + +

    由于每种布局的实施都会稍有不同,因此您可能需要先确定当前向用户显示的布局。例如,您可以了解用户所处的是“单面板”模式还是“双面板”模式。要做到这一点,您可以查询指定视图是否存在以及是否已显示出来。

    + +
    +public class NewsReaderActivity extends FragmentActivity {
    +    boolean mIsDualPane;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main_layout);
    +
    +        View articleView = findViewById(R.id.article);
    +        mIsDualPane = articleView != null && 
    +                        articleView.getVisibility() == View.VISIBLE;
    +    }
    +}
    +
    + +

    请注意,这段代码用于查询“报道”面板是否可用,与针对具体布局的硬编码查询相比,这段代码的灵活性要大得多。

    + +

    再举一个适应各种组件的存在情况的方法示例:在对这些组件执行操作前先查看它们是否可用。例如,新闻阅读器示例应用中有一个用于打开菜单的按钮,但只有在版本低于 3.0 的 Android 上运行该应用时,这个按钮才会存在,因为 API 级别 11 或更高级别中的 {@link android.app.ActionBar} 已取代了该按钮的功能。因此,您可以使用以下代码为此按钮添加事件侦听器:

    + +
    +Button catButton = (Button) findViewById(R.id.categorybutton);
    +OnClickListener listener = /* create your listener here */;
    +if (catButton != null) {
    +    catButton.setOnClickListener(listener);
    +}
    +
    + + +

    根据当前布局做出响应

    + +

    有些操作可能会因当前的具体布局而产生不同的结果。例如,在新闻阅读器示例中,如果用户界面处于双面板模式下,那么点击标题列表中的标题就会在右侧面板中打开相应报道;但如果用户界面处于单面板模式下,那么上述操作就会启动一个独立活动:

    + +
    +@Override
    +public void onHeadlineSelected(int index) {
    +    mArtIndex = index;
    +    if (mIsDualPane) {
    +        /* display article on the right pane */
    +        mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
    +    } else {
    +        /* start a separate activity */
    +        Intent intent = new Intent(this, ArticleActivity.class);
    +        intent.putExtra("catIndex", mCatIndex);
    +        intent.putExtra("artIndex", index);
    +        startActivity(intent);
    +    }
    +}
    +
    + +

    同样,如果该应用处于双面板模式下,就应设置带导航标签的操作栏;但如果该应用处于单面板模式下,就应使用旋转窗口小部件设置导航栏。因此您的代码还应确定哪种情况比较合适:

    + +
    +final String CATEGORIES[] = { "热门报道", "政治", "经济", "Technology" };
    +
    +public void onCreate(Bundle savedInstanceState) {
    +    ....
    +    if (mIsDualPane) {
    +        /* use tabs for navigation */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
    +        int i;
    +        for (i = 0; i < CATEGORIES.length; i++) {
    +            actionBar.addTab(actionBar.newTab().setText(
    +                CATEGORIES[i]).setTabListener(handler));
    +        }
    +        actionBar.setSelectedNavigationItem(selTab);
    +    }
    +    else {
    +        /* use list navigation (spinner) */
    +        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
    +        SpinnerAdapter adap = new ArrayAdapter(this, 
    +                R.layout.headline_item, CATEGORIES);
    +        actionBar.setListNavigationCallbacks(adap, handler);
    +    }
    +}
    +
    + + +

    重复使用其他活动中的片段

    + +

    多屏幕设计中的重复模式是指,对于某些屏幕配置,已实施界面的一部分会用作面板;但对于其他配置,这部分就会以独立活动的形式存在。例如,在新闻阅读器示例中,对于较大的屏幕,新闻报道文本会显示在右侧面板中;但对于较小的屏幕,这些文本就会以独立活动的形式存在。

    + +

    在类似情况下,您通常可以在多个活动中重复使用相同的 {@link android.app.Fragment} 子类以避免代码重复。例如,您在双面板布局中使用了 ArticleFragment

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    然后又在小屏幕的活动布局中重复使用(无布局)了它 (ArticleActivity):

    + +
    +ArticleFragment frag = new ArticleFragment();
    +getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
    +
    + +

    当然,这与在 XML 布局中声明片段的效果是一样的,但在这种情况下却没必要使用 XML 布局,因为报道片段是此活动中的唯一组件。

    + +

    请务必在设计片段时注意,不要针对具体活动创建强耦合。要做到这一点,您通常可以定义一个界面,该界面概括了相关片段与其主活动交互所需的全部方式,然后让主活动实施该界面:

    + +

    例如,新闻阅读器应用的 HeadlinesFragment 会精确执行以下代码:

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    OnHeadlineSelectedListener mHeadlineSelectedListener = null;
    +
    +    /* Must be implemented by host activity */
    +    public interface OnHeadlineSelectedListener {
    +        public void onHeadlineSelected(int index);
    +    }
    +    ...
    +
    +    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
    +        mHeadlineSelectedListener = listener;
    +    }
    +}
    +
    + +

    然后,如果用户选择某个标题,相关片段就会通知由主活动指定的侦听器(而不是通知某个硬编码的具体活动):

    + +
    +public class HeadlinesFragment extends ListFragment {
    +    ...
    +    @Override
    +    public void onItemClick(AdapterView<?> parent, 
    +                            View view, int position, long id) {
    +        if (null != mHeadlineSelectedListener) {
    +            mHeadlineSelectedListener.onHeadlineSelected(position);
    +        }
    +    }
    +    ...
    +}
    +
    + +

    支持平板电脑和手持设备的指南中进一步介绍了此技术。

    + + +

    处理屏幕配置变化

    + +

    如果您使用独立活动实施界面的独立部分,那么请注意,您可能需要对特定配置变化(例如屏幕方向的变化)做出响应,以便保持界面的一致性。

    + +

    例如,在运行 Android 3.0 或更高版本的标准 7 英寸平板电脑上,如果新闻阅读器示例应用运行在纵向模式下,就会在使用独立活动显示新闻报道;但如果该应用运行在横向模式下,就会使用双面板布局。

    + +

    也就是说,如果用户处于纵向模式下且屏幕上显示的是用于阅读报道的活动,那么您就需要在检测到屏幕方向变化(变成横向模式)后执行相应操作,即停止上述活动并返回主活动,以便在双面板布局中显示相关内容:

    + +
    +public class ArticleActivity extends FragmentActivity {
    +    int mCatIndex, mArtIndex;
    +
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
    +        mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
    +
    +        // If should be in two-pane mode, finish to return to main activity
    +        if (getResources().getBoolean(R.bool.has_two_panes)) {
    +            finish();
    +            return;
    +        }
    +        ...
    +}
    +
    + + diff --git a/docs/html/intl/zh-CN/training/multiscreen/index.jd b/docs/html/intl/zh-CN/training/multiscreen/index.jd new file mode 100644 index 000000000000..35c48e066c24 --- /dev/null +++ b/docs/html/intl/zh-CN/training/multiscreen/index.jd @@ -0,0 +1,64 @@ +page.title=针对多种屏幕进行设计 + +trainingnavtop=true +startpage=true +next.title=支持各种屏幕尺寸 +next.link=screensizes.html + +@jd:body + +
    +
    + +

    依存关系和前提条件

    + +
      +
    • Android 1.6 或更高版本(示例应用则需要 2.1 或更高版本)
    • +
    • 活动片段的基本知识
    • +
    • 构建 Android 用户界面的经验
    • +
    • 多个功能需要用到支持库
    • +
    + +

    您还应参阅

    + + + +

    试试看

    + +
    +下载示例应用 +

    NewsReader.zip

    +
    + +
    +
    + +

    Android 支持数百种屏幕尺寸不同的设备,包括小型手机和大型电视机。因此,请务必将您的应用设计为与所有的屏幕尺寸兼容,以便让尽可能多的用户使用该应用。

    + +

    不过,与各种类型的设备兼容还远远不够。由于各种屏幕尺寸对用户互动产生的利弊有所不同,因此要真正满足用户需求并广获好评,您的应用不仅需要支持多种屏幕,还应针对各类屏幕配置的用户体验进行优化。

    + +

    本教程将向您介绍如何针对多种屏幕配置优化和实施相应的用户界面。

    + +

    各教程中都提及了一种来自一个示例应用的代码,该应用展示了关于针对多种分辨率进行优化的最佳实践。您可以在右侧下载该示例,并在自己的应用内重复使用其中的代码。

    + +

    请注意:本教程和相关的示例使用了支持库,以便在 3.0 版以下的 Android 上使用 {@link android.app.Fragment} API。因此,您需要下载该库并将其添加到您的应用,才能使用本教程中涉及的所有 API。

    + + +

    教程

    + +
    +
    支持各种屏幕尺寸
    +
    本教程将向您介绍如何设计可适应多种屏幕尺寸的布局(使用灵活的视图尺寸、 {@link android.widget.RelativeLayout}、屏幕尺寸和屏幕方向限定符、别名过滤器以及自动拉伸位图)。
    + +
    支持各种屏幕密度
    +
    本教程将向您介绍如何支持具有不同像素密度的屏幕(使用非密度制约像素并提供各种密度的相应位图)。
    + +
    实施自适应用户界面流程
    +
    本教程将向您介绍如何以可适应多种屏幕尺寸/屏幕密度组合的方式实施用户界面流程(运行时对当前布局的检测,根据当前布局做出响应,处理屏幕配置变化)。
    +
    diff --git a/docs/html/intl/zh-CN/training/multiscreen/screendensities.jd b/docs/html/intl/zh-CN/training/multiscreen/screendensities.jd new file mode 100644 index 000000000000..cdb9b7fe54c6 --- /dev/null +++ b/docs/html/intl/zh-CN/training/multiscreen/screendensities.jd @@ -0,0 +1,100 @@ +page.title=支持各种屏幕密度 +parent.title=针对多种屏幕进行设计 +parent.link=index.html + +trainingnavtop=true +previous.title=支持各种屏幕尺寸 +previous.link=screensizes.html +next.title=实施自适应用户界面流程 +next.link=adaptui.html + +@jd:body + + + +
    +
    + +

    本教程将指导您

    +
      +
    1. 使用非密度制约像素
    2. +
    3. 提供备用位图
    4. +
    + +

    您还应参阅

    + + + +

    试试看

    + +
    +下载示例应用 +

    NewsReader.zip

    +
    + + +
    +
    + +

    本教程将向您介绍如何通过提供不同资源和使用独立于分辨率的测量单位来支持不同屏幕密度。

    + +

    使用非密度制约像素

    + +

    在设计布局时,大家经常会误使用绝对像素来定义距离或尺寸,您一定要避免犯这种错误。由于各种屏幕的像素密度都有所不同,因此相同数量的像素在不同设备上的实际大小也有所差异,这样使用像素定义布局尺寸就会产生问题。因此,请务必使用 dpsp 单位指定尺寸。dp 是一种非密度制约像素,其尺寸与 160 dpi 像素的实际尺寸相同。sp 也是一种基本单位,但它可根据用户的偏好文字大小进行调整(即尺度独立性像素),因此您应将该测量单位用于定义文字大小(请勿用其定义布局尺寸)。

    + +

    例如,请使用 dp(而非 px)指定两个视图间的间距:

    + +
    +<Button android:layout_width="wrap_content" 
    +    android:layout_height="wrap_content" 
    +    android:text="@string/clickme"
    +    android:layout_marginTop="20dp" />
    +
    + +

    请务必使用 sp 指定文字大小:

    + +
    +<TextView android:layout_width="match_parent" 
    +    android:layout_height="wrap_content" 
    +    android:textSize="20sp" />
    +
    + + +

    提供备用位图

    + +

    由于 Android 可在具有各种屏幕密度的设备上运行,因此您提供的位图资源应始终可以满足各类普遍密度范围的要求:低密度、中等密度、高密度以及超高密度。这将有助于您的图形在所有屏幕密度上都能得到出色的质量和效果。

    + +

    要生成这些图片,您应先提取矢量格式的原始资源,然后根据以下尺寸范围针对各密度生成相应的图片。

    + +

      +
    • xhdpi:2.0 +
    • hdpi:1.5 +
    • mdpi:1.0(最低要求) +
    • ldpi:0.75 +

    + +

    也就是说,如果您为 xhdpi 设备生成了 200x200 尺寸的图片,就应该使用同一资源为 hdpimdpildpi 设备分别生成 150x150、100x100 和 75x75 尺寸的图片。

    + +

    然后,将生成的图片文件放在 res/ 下的相应子目录中(如下所示),系统就会根据运行您应用的设备的屏幕密度自动选择合适的图片:

    + +
    +MyProject/
    +  res/
    +    drawable-xhdpi/
    +        awesomeimage.png
    +    drawable-hdpi/
    +        awesomeimage.png
    +    drawable-mdpi/
    +        awesomeimage.png
    +    drawable-ldpi/
    +        awesomeimage.png
    +
    + +

    这样一来,无论您何时引用 @drawable/awesomeimage,系统都能根据相应屏幕的 dpi 选取合适的位图。

    + +

    有关为您的应用创建图标资产的更多提示和指南,请参阅图标设计指南

    + diff --git a/docs/html/intl/zh-CN/training/multiscreen/screensizes.jd b/docs/html/intl/zh-CN/training/multiscreen/screensizes.jd new file mode 100644 index 000000000000..904d09790a21 --- /dev/null +++ b/docs/html/intl/zh-CN/training/multiscreen/screensizes.jd @@ -0,0 +1,279 @@ +page.title=支持各种屏幕尺寸 +parent.title=针对多种屏幕进行设计 +parent.link=index.html + +trainingnavtop=true +next.title=支持各种屏幕密度 +next.link=screendensities.html + +@jd:body + + + + + +

    此教程将向您介绍如何通过以下方法支持各种尺寸的屏幕:

    +
      +
    • 确保系统可以适当地调整您布局的尺寸以便适应屏幕
    • +
    • 根据屏幕配置提供合适的用户界面布局
    • +
    • 确保正确的布局应用到了正确的屏幕上
    • +
    • 提供可正确缩放的位图
    • +
    + + +

    使用“wrap_content”和“match_parent”

    + +

    要确保布局的灵活性并适应各种尺寸的屏幕,您应使用 "wrap_content""match_parent" 控制某些视图组件的宽度和高度。如果您使用 "wrap_content",系统就会将视图的宽度或高度设置成所需的最小尺寸以适应视图中的内容,而 "match_parent"(在低于 API 级别 8 的级别中称为 "fill_parent")则会展开组件以匹配其父视图的尺寸。

    + +

    如果使用 "wrap_content""match_parent" 尺寸值而不是硬编码的尺寸,您的视图就会相应地仅使用自身所需的空间或展开以填满可用空间。例如:

    + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    请注意示例中使用 "wrap_content""match_parent" 控制组件尺寸的方法,而不是关注具体的尺寸。此方法可让布局正确适应各种屏幕尺寸和屏幕方向。

    + +

    此视图在纵向模式和横向模式下的显示效果如下所示。请注意,组件的尺寸会自动适应屏幕的高度和宽度:

    + + +

    图 1。纵向模式(左)和横向模式(右)下的新闻阅读器示例应用。

    + + +

    使用相对布局

    + +

    您可以使用 {@link android.widget.LinearLayout} 的嵌套实例并结合 "wrap_content""match_parent" 尺寸,以便构建相当复杂的布局。不过,您无法通过 {@link android.widget.LinearLayout} 精确控制子视图的特殊关系;系统会将 {@link android.widget.LinearLayout} 中的视图直接并排列出。如果您需要将子视图排列出各种效果而不是一条直线,通常更合适的解决方法是使用 {@link android.widget.RelativeLayout},这样您就可以根据各组件之间的特殊关系指定布局了。例如,您可以将某个子视图对齐到屏幕左侧,同时将另一个视图对齐到屏幕右侧。

    + +

    例如:

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="match_parent"
    +    android:layout_height="match_parent">
    +    <TextView
    +        android:id="@+id/label"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:text="Type here:"/>
    +    <EditText
    +        android:id="@+id/entry"
    +        android:layout_width="match_parent"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/label"/>
    +    <Button
    +        android:id="@+id/ok"
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_below="@id/entry"
    +        android:layout_alignParentRight="true"
    +        android:layout_marginLeft="10dp"
    +        android:text="OK" />
    +    <Button
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:layout_toLeftOf="@id/ok"
    +        android:layout_alignTop="@id/ok"
    +        android:text="Cancel" />
    +</RelativeLayout>
    +
    + +

    图 2 展示的是此布局在 QVGA 屏幕上的显示效果。

    + + +

    图 2。QVGA 屏幕(小屏幕)上的截图。

    + +

    图 3 展示的是此布局在较大屏幕上的显示效果。

    + + +

    图 3。WSVGA 屏幕(大屏幕)上的截图。

    + +

    请注意,虽然组件的尺寸有所变化,但它们的空间关系仍会保留,具体由 {@link android.widget.RelativeLayout.LayoutParams} 指定。

    + + +

    使用尺寸限定符

    + +

    上文所述的灵活布局或相对布局可以为您带来的优势就只有这么多了。虽然这些布局可以拉伸组件内外的空间以适应各种屏幕,但它们不一定能为每种屏幕都提供最佳的用户体验。因此,您的应用不仅应实施灵活布局,还应针对各种屏幕配置提供一些备用布局。要做到这一点,您可以使用配置限定符,这样就可以在运行时根据当前的设备配置自动选择合适的资源了(例如根据各种屏幕尺寸选择不同的布局)。

    + +

    例如,很多应用会在较大的屏幕上实施“双面板”模式(相关应用可能会在一个面板上显示项目列表,并在另一面板上显示对应内容)。平板电脑和电视的屏幕已经大到可以同时容纳这两个面板了,但手机屏幕就需要分别显示。因此,您可以使用以下文件以便实施这些布局:

    + +
      +
    • res/layout/main.xml,单面板(默认)布局: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-large/main.xml,双面板布局: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    请注意第二种布局名称目录中的 large 限定符。系统会在属于较大屏幕(例如 7 英寸或更大的平板电脑)的设备上选择此布局。系统会在较小的屏幕上选择其他布局(无限定符)。

    + + +

    使用最小宽度限定符

    + +

    在版本低于 3.2 的 Android 设备上,开发人员遇到的问题之一是“较大”屏幕的尺寸范围,该问题会影响戴尔 Streak、早期的 Galaxy Tab 以及大部分 7 英寸平板电脑。即使这些设备的屏幕属于“较大”的尺寸,但很多应用可能会针对此类别中的各种设备(例如 5 英寸和 7 英寸的设备)显示不同的布局。这就是 Android 3.2 版在引入其他限定符的同时引入“最小宽度”限定符的原因。

    + +

    最小宽度限定符可让您通过指定某个最小宽度(以 dp 为单位)来定位屏幕。例如,标准 7 英寸平板电脑的最小宽度为 600 dp,因此如果您要在此类屏幕上的用户界面中使用双面板(但在较小的屏幕上只显示列表),您可以使用上文中所述的单面板和双面板这两种布局,但您应使用 sw600dp 指明双面板布局仅适用于最小宽度为 600 dp 的屏幕,而不是使用 large 尺寸限定符:

    + +
      +
    • res/layout/main.xml,单面板(默认)布局: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} +
    • +
    • res/layout-sw600dp/main.xml,双面板布局: + +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} +
    • +
    + +

    也就是说,对于最小宽度大于等于 600 dp 的设备,系统会选择 layout-sw600dp/main.xml(双面板)布局,否则系统就会选择 layout/main.xml(单面板)布局。

    + +

    但 Android 版本低于 3.2 的设备不支持此技术,原因是这些设备无法将 sw600dp 识别为尺寸限定符,因此您仍需使用 large 限定符。这样一来,就会有一个名称为 res/layout-large/main.xml 的文件(与 res/layout-sw600dp/main.xml 一样)。您将在下一教程中了解到避免此类布局文件出现重复的技术。

    + + +

    使用布局别名

    + +

    最小宽度限定符仅适用于 Android 3.2 及更高版本。因此,您仍需使用与较低版本兼容的概括尺寸范围(小、正常、大和特大)。例如,如果您要将用户界面设计成在手机上显示单面板,但在 7 英寸平板电脑、电视和其他较大的设备上显示多面板,请提供以下文件:

    + +

      +
    • res/layout/main.xml: 单面板布局
    • +
    • res/layout-large: 多面板布局
    • +
    • res/layout-sw600dp: 多面板布局
    • +

    + +

    后两个文件是相同的,因为其中一个用于和 Android 3.2 设备匹配,而另一个则是为使用较低版本 Android 的平板电脑和电视准备的。

    + +

    要避免平板电脑和电视的文件出现重复(以及由此带来的维护问题),您可以使用别名文件。例如,您可以定义以下布局:

    + +
      +
    • res/layout/main.xml,单面板布局
    • +
    • res/layout/main_twopanes.xml,双面板布局
    • +
    + +

    然后添加这两个文件:

    + +

      +
    • res/values-large/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      +
    • + +
    • res/values-sw600dp/layout.xml: +
      +<resources>
      +    <item name="main" type="layout">@layout/main_twopanes</item>
      +</resources>
      +
      + +
    • +

    + +

    后两个文件的内容相同,但它们并未实际定义布局。它们只是将 {@code main} 设置成了 {@code main_twopanes} 的别名。由于这些文件包含 largesw600dp 选择器,因此无论 Android 版本如何,系统都会将这些文件应用到平板电脑和电视上(版本低于 3.2 的平板电脑和电视会匹配 +{@code large},版本低于 3.2 的平板电脑和电视则会匹配 sw600dp)。

    + + +

    使用屏幕方向限定符

    + +

    某些布局会同时支持横向模式和纵向模式,但您可以通过调整优化其中大部分布局的效果。在新闻阅读器示例应用中,每种屏幕尺寸和屏幕方向下的布局行为方式如下所示:

    + +

      +
    • 小屏幕,纵向:单面板,带徽标
    • +
    • 小屏幕,横向:单面板,带徽标
    • +
    • 7 英寸平板电脑,纵向:单面板,带操作栏
    • +
    • 7 英寸平板电脑,横向:双面板,宽,带操作栏
    • +
    • 10 英寸平板电脑,纵向:双面板,窄,带操作栏
    • +
    • 10 英寸平板电脑,横向:双面板,宽,带操作栏
    • +
    • 电视,横向:双面板,宽,带操作栏
    • +

    + +

    因此,这些布局中的每一种都定义在了 res/layout/ 目录下的某个 XML 文件中。为了继续将每个布局分配给各种屏幕配置,该应用会使用布局别名将两者相匹配:

    + +

    res/layout/onepane.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane.xml all} + +

    res/layout/onepane_with_bar.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/onepane_with_bar.xml all} + +

    res/layout/twopanes.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes.xml all} + +

    res/layout/twopanes_narrow.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/layout/twopanes_narrow.xml all} + +

    既然您已定义了所有可能的布局,那就只需使用配置限定符将正确的布局映射到各种配置即可。您现在只需使用布局别名技术即可做到这一点:

    + +

    res/values/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values/layouts.xml all} + +

    res/values-sw600dp-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-land/layouts.xml +all} + +

    res/values-sw600dp-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-sw600dp-port/layouts.xml +all} + +

    res/values-large-land/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-land/layouts.xml all} + +

    res/values-large-port/layouts.xml:

    +{@sample development/samples/training/multiscreen/newsreader/res/values-large-port/layouts.xml all} + + + +

    使用自动拉伸位图

    + +

    支持各种屏幕尺寸通常意味着您的图片资源还必须能适应各种尺寸。例如,无论要应用到什么形状的按钮上,按钮背景都必须能适应。

    + +

    如果在可以更改尺寸的组件上使用了简单的图片,您很快就会发现显示效果多少有些不太理想,因为系统会在运行时平均地拉伸或收缩您的图片。解决方法为使用自动拉伸位图,这是一种格式特殊的 PNG 文件,其中会指明可以拉伸以及不可以拉伸的区域。

    + +

    因此,如果设计的是用于尺寸可变的组件上的位图,请务必使用自动拉伸技术。要将某个位图转换成自动拉伸位图,您可以先准备好普通图片(图 4,放大了 4 倍以便清楚显示)。

    + + +

    图 4button.png

    + +

    然后通过 SDK 的 draw9patch 实用工具(位于 tools/ 目录中)运行该图片,您可以在该工具中绘制像素以标出要拉伸的区域以及左侧和顶部的边界。您还可以沿右侧和底部边界绘制像素以标出用于放置内容的区域,具体如图 5 所示。

    + + +

    图 5button.9.png

    + +

    请注意沿边界显示的黑色像素。顶部和左侧边界上的像素用于指定可以拉伸的图片区域,右侧和底部边界上的像素则用于指定放置内容的区域。

    + +

    另请注意 .9.png 的扩展名。您必须使用此扩展名,因为系统框架需要通过此扩展名确定相关图片是自动拉伸位图,而不是普通 PNG 图片。

    + +

    如果您将此背景应用到某个组件(通过设置 android:background="@drawable/button"),系统框架就会正确拉伸图片以适应按钮的尺寸,具体如图 6 中的各种尺寸所示。

    + + +

    图 6。在各种尺寸下使用 button.9.png 自动拉伸位图的按钮。

    + diff --git a/docs/html/legal.jd b/docs/html/legal.jd new file mode 100644 index 000000000000..575f01640eb4 --- /dev/null +++ b/docs/html/legal.jd @@ -0,0 +1,129 @@ +page.title=Legal Notice +fullpage=1 +@jd:body + +
    + +

    Legal Notice

    + +

    Android is an open platform that's freely available to you as an app developer. You can +immediately download the Android SDK, develop apps, and distribute them to the world without any +registration or fees.

    + +

    Android is developed by Google Inc. and the Open Handset Alliance. We've made it available to you +as a development platform pursuant to our commitment to openness, freedom, and innovation in +mobile.

    + +

    To start developing apps for Android, download the free Android SDK.

    + + + +

    Android Brands

    + +

    The "Android" name and Android logo are trademarks of Google Inc. +You may not use the logo or the logo's custom typeface.

    + +

    You may use the word "Android" in a product name only as a descriptor, such as "for Android" +and the first instance should be followed by a TM symbol, "for Android™." In other +messaging, the word "Android" may be used in text as a descriptor, as long as it is followed by a +proper generic term (for example, "Android™ application"). Any use of the Android name +must include footer attribution in your communications: "Android is a trademark of Google Inc."

    + +

    The Android Robot logo can be used, reproduced, and modified freely +in marketing communications. Our standard color value for print is PMS 376C. Our online hex color is +#A4C639. The Android Robot logo is licensed under the terms of the Creative Commons Attribution license and any +use of it must be attributed as such.

    + +

    For more information about Android brands, see the Android Branding Guidelines.

    + + + +

    Web Site Content

    + +

    We are pleased to license the Android documentation and sample code on this web site under terms +that encourage you to take, modify, reuse, re-purpose, and remix the content as you see fit. The +documentation content on this web site is made available to you as part of the Android Open Source Project. This documentation, including any +code shown in it, is licensed under the Apache +2.0 license. All other content on this site, except the license documents themselves and as +otherwise noted, is licensed under the Creative Commons Attribution 2.5 license. +

    + +

    For more information about licenses provided for the content of this web site and the +restrictions for re-use, read the complete Content License.

    + +

    Your use of this site is subject to Google's Privacy +Policy & Terms of Service.

    + + + +

    Other Android Services

    + +

    Google provides other optional services for your Android apps that have their own legal terms and +restrictions. Such services include:

    + +
    +
    Eclipse Android Developer Tools Plugin
    +
    If you're developing apps with the Eclipse IDE, we offer a free plugin called the +Android Developer Tools (ADT) to speed up your +development and debugging. Certain code within the ADT plugin and other packages available +from the SDK Manager require that you agree to terms and conditions for use, reproduction and +distribution upon installation.
    + +
    Google Play
    +
    Google Play is a publicly available service through which you can distribute your apps for +Android-powered devices. Google Play not only makes your app available to millions of devices, but +also offers your app powerful services such as in-app billing and license verification. In order to +distribute your apps on Google Play and use the associated services, you must agree to the Developer +Distribution Agreement and acquire a valid Developer Account. +

    Developer Distribution +Agreement, Developer Program +Policies

    + +
    Google Maps API
    +
    The Android Maps APIs are a collection of services (including, but not limited to, the +MapView and MapActivity classes) that allow you to include +maps, geocoding, geolocation, and other content from Google and its content providers in your +Android +apps. If you want to develop an Android app that displays Google Maps data, you must agree +to the terms of service, register, and get an API Key. Registration is free. +

    Google Maps Android API Key Signup, Mobile Legal +Notices

    +
    + +
    Android Cloud to Device Messaging
    +
    Android Cloud to Device Messaging (C2DM) is a service that helps you send data from +your servers to your users' Android devices. The service provides a simple, lightweight +mechanism that your servers can use to tell your Android app to contact your server directly to +fetch updated app or user data. Before you can sign up for Android Cloud to Device Messaging, you +must agree to the terms of a legal agreement between you and Google. Registration is free. +

    Android Cloud to Device +Messaging Terms of Service

    +
    + +
    Android Backup Service
    +
    Android Backup Service is integrated with Android's data backup framework to perform data +backup and restore for most devices running Android 2.2 or greater, using Google servers and a +backup transport on the device. Before you can sign up for Android Backup Service, you +must agree to the terms of a legal agreement between you and Google. Registration is free. +

    Android Backup Service +Terms of Service

    +
    +
    + +

    Any and all other services available for Android but not documented on developer.android.com are subject to their own terms, as +documented on their respective web sites.

    + +
    \ No newline at end of file diff --git a/docs/html/license.jd b/docs/html/license.jd index 83cd4709102a..a9af038bd696 100644 --- a/docs/html/license.jd +++ b/docs/html/license.jd @@ -1,15 +1,13 @@ page.title=Content License -hide_license_footer=true +fullpage=1 @jd:body -
    -

    Content License

    - -

    For the purposes of licensing, the content of this site is divided +

    +

    Content License

    +

    For the purposes of licensing, the content of this web site is divided into two categories:

      -
    • Documentation content, found under the "Dev Guide" and "Reference" - tabs, including both static content and content extracted from source +
    • Documentation content, including both static documentation and content extracted from source code modules, as well as sample code, and
    • All other site content
    @@ -31,6 +29,10 @@ is licensed under GPLv2 or other license. In those cases, the license covering the source code module will apply to the documentation extracted from it.

    +

    Third-party components of this site such as JavaScript libraries are included in the Android +Open Source Project under the licenses specified by their authors. For information about these +licenses, refer to the source files in the Android Open Source Project.

    +

    All other content on this site, except the license documents themselves and as otherwise noted, is licensed under the Creative Commons @@ -42,17 +44,18 @@ above. For content licensed under Creative Commons Attribution 2.5, we ask that you give proper attribution.

    -

    Terms of Use

    +

    Terms of Use

    We are pleased to license the Android documentation and sample code under terms that encourage you to take, modify, reuse, re-purpose, and remix the -content as you see fit. Except as noted in the Restrictions section below, you +content as you see fit. Except as noted in the Restrictions section +below, you are free to use the documentation content in your own creations. For example, you could quote the text in a book, cut-and-paste sections to your blog, record it as an audiobook for the visually impaired, or even translate it.

    -

    Restrictions

    +

    Restrictions

    • While the documentation itself is available to you under the Apache 2.0 @@ -60,9 +63,11 @@ license, note that proprietary trademarks and brand features are not included in that license.
    • Google's trademarks and other brand features (including the -ANDROID stylized typeface logo) are not included in the license. -Please see -Guidelines for Third Party Use of Google Brand Features for +Android stylized typeface logo) are not included +in the license. +Please see Android Branding Guidelines for information about this usage.
    • In some cases, a page may include content, such as an image, that is not @@ -76,9 +81,8 @@ slide decks that are not covered.
    • documentation is subject to the conditions detailed in the Apache 2.0 license.
    - -

    Attribution

    +

    Attribution

    Proper attribution is required when you reuse or create modified versions of content that appears on a page made available under the @@ -95,49 +99,47 @@ Creative Commons legal code. are producing the work. There are several typical ways in which this might apply:

    -

    Exact Reproductions

    +

    Exact Reproductions

    If your online work exactly reproduces text or images from this site, in whole or in part, please include a paragraph at the bottom of your page that reads:

    -
    +

    Portions of this page are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. -

    +

    Also, please link back to the original source page so that readers can refer there for more information.

    -

    Modified Versions

    +

    Modified Versions

    If your online work shows modified text or images based on the content from this site, please include a paragraph at the bottom of your page that reads:

    -
    +

    Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. -

    +

    Again, please link back to the original source page so that readers can refer there for more information. This is even more important when the content has been modified.

    -

    Other Media

    +

    Other Media

    If you produce non-hypertext works, such as books, audio, or video, we ask that you make a best effort to include a spoken or written attribution in the spirit of the messages above.

    -
    - - +
    diff --git a/docs/html/live/index.jd b/docs/html/live/index.jd index 3885725eb5c2..972972713400 100644 --- a/docs/html/live/index.jd +++ b/docs/html/live/index.jd @@ -1,7 +1,8 @@ page.title=Live +fullpage=1 @jd:body -
    +

    Android Developers Live

    @@ -61,4 +62,4 @@ livecasts on YouTube and videos of past sessions or follow us on
    -
    +
    diff --git a/docs/html/mwc2010/index.html b/docs/html/mwc2010/index.html deleted file mode 100644 index c91386f91070..000000000000 --- a/docs/html/mwc2010/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - -Redirecting... - - - - - diff --git a/docs/html/offline.jd b/docs/html/offline.jd index edd8eb09dd2d..73da7799fdcc 100644 --- a/docs/html/offline.jd +++ b/docs/html/offline.jd @@ -23,13 +23,13 @@ page.title=Welcome

    Get Started

    @@ -37,7 +37,7 @@ tools

    If you've downloaded the Android SDK for the first time

    -

    Follow the guide to Installing the Android SDK, which +

    Follow the guide to Installing the Android SDK, which will help you setup your development environment.

    If you've installed new SDK components using the Android SDK Manager

    diff --git a/docs/html/resources/articles/avoiding-memory-leaks.jd b/docs/html/resources/articles/avoiding-memory-leaks.jd deleted file mode 100644 index 395f5900979c..000000000000 --- a/docs/html/resources/articles/avoiding-memory-leaks.jd +++ /dev/null @@ -1,111 +0,0 @@ -page.title=Avoiding Memory Leaks -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -

    Android applications are, at least on the T-Mobile G1, limited -to 16 MB of heap. It's both a lot of memory for a phone and yet very -little for what some developers want to achieve. Even if you do not -plan on using all of this memory, you should use as little as possible -to let other applications run without getting them killed. The more -applications Android can keep in memory, the faster it will be for the -user to switch between his apps. As part of my job, I ran into memory -leaks issues in Android applications and they are most of the time due -to the same mistake: keeping a long-lived reference to a -{@link android.content.Context Context}.

    - -

    On Android, a Context is used for many operations - but mostly to load and access resources. This is why all the widgets -receive a Context parameter in their constructor. In a -regular Android application, you usually have two kinds of -Context, {@link android.app.Activity} and -{@link android.app.Application}. It's usually the first one that -the developer passes to classes and methods that need a Context:

    - -
    @Override
    -protected void onCreate(Bundle state) {
    -  super.onCreate(state);
    -  
    -  TextView label = new TextView(this);
    -  label.setText("Leaks are bad");
    -  
    -  setContentView(label);
    -}
    -
    - -

    This means that views have a reference to the entire activity and -therefore to anything your activity is holding onto; usually the entire -View hierarchy and all its resources. Therefore, if you leak the Context -("leak" meaning you keep a reference to it thus preventing the GC from -collecting it), you leak a lot of memory. Leaking an entire activity -can be really easy if you're not careful.

    - -

    When the screen orientation changes the system will, by default, -destroy the current activity and create a new one while preserving its -state. In doing so, Android will reload the application's UI from the -resources. Now imagine you wrote an application with a large bitmap -that you don't want to load on every rotation. The easiest way to keep -it around and not having to reload it on every rotation is to keep in a -static field:

    - -
    private static Drawable sBackground;
    -  
    -@Override
    -protected void onCreate(Bundle state) {
    -  super.onCreate(state);
    -  
    -  TextView label = new TextView(this);
    -  label.setText("Leaks are bad");
    -  
    -  if (sBackground == null) {
    -    sBackground = getDrawable(R.drawable.large_bitmap);
    -  }
    -  label.setBackgroundDrawable(sBackground);
    -  
    -  setContentView(label);
    -}
    -
    - -

    This code is very fast and also very wrong; it leaks the first activity -created upon the first screen orientation change. When a -{@link android.graphics.drawable.Drawable Drawable} is attached to a view, the view is set as a -{@link android.graphics.drawable.Drawable#setCallback(android.graphics.drawable.Drawable.Callback) callback} -on the drawable. In the code snippet above, this means the drawable has a -reference to the TextView which itself has a reference to the -activity (the Context) which in turns has references to -pretty much anything (depending on your code.)

    - -

    This example is one of the simplest cases of leaking the -Context and you can see how we worked around it in the -Home screen's source code -(look for the unbindDrawables() method) by setting the stored -drawables' callbacks to null when the activity is destroyed. Interestingly -enough, there are cases where you can create a chain of leaked contexts, -and they are bad. They make you run out of memory rather quickly.

    - -

    There are two easy ways to avoid context-related memory leaks. The most -obvious one is to avoid escaping the context outside of its own scope. The -example above showed the case of a static reference but inner classes and -their implicit reference to the outer class can be equally dangerous. The -second solution is to use the Application context. This -context will live as long as your application is alive and does not depend -on the activities life cycle. If you plan on keeping long-lived objects -that need a context, remember the application object. You can obtain it -easily by calling -{@link android.content.Context#getApplicationContext() Context.getApplicationContext()} -or {@link android.app.Activity#getApplication() Activity.getApplication()}.

    - -

    In summary, to avoid context-related memory leaks, remember the following:

    -
      -
    • Do not keep long-lived references to a context-activity (a reference -to an activity should have the same life cycle as the activity itself)
    • -
    • Try using the context-application instead of a context-activity
    • -
    • Avoid non-static inner classes in an activity if you don't control -their life cycle, use a static inner class and make a weak reference to -the activity inside. The solution to this issue is to use a static inner -class with a {@link java.lang.ref.WeakReference WeakReference} to the -outer class, as done in ViewRoot -and its W inner class for instance
    • -
    • A garbage collector is not an insurance against memory leaks
    • -
    diff --git a/docs/html/resources/articles/backward-compatibility.jd b/docs/html/resources/articles/backward-compatibility.jd deleted file mode 100644 index f96d587c0067..000000000000 --- a/docs/html/resources/articles/backward-compatibility.jd +++ /dev/null @@ -1,252 +0,0 @@ -page.title=Backward Compatibility for Applications -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -
    -
    - -

    See also

    -
      -
    1. Android API Levels
    2. -
    - -
    -
    - -

    A variety of Android-powered devices are now available to consumers from carriers -in geographies around the world. Across those devices, a range of Android -platform versions are in use, some running the latest version of the platform, -others running older versions. As a developer, you need to consider the approach -to backward compatibility that you will take in your application — do you -want to allow your application to run on all devices, or just those running the -latest software? In some cases it will be useful to employ the newer APIs on -devices that support them, while continuing to support older devices.

    - -

    Setting the minSdkVersion

    -

    If the use of a new API is integral to the application — perhaps you -need to record video using an API introduced in Android 1.5 (API Level 3) -— you should add a <android:minSdkVersion> - to the application's manifest, to ensure your app won't -be installed on older devices. For example, if your application depends on an -API introduced in API Level 3, you would specify "3" as the value of the minimum -SDK version:

    - -
      <manifest>
    -   ...
    -   <uses-sdk android:minSdkVersion="3" />
    -   ...
    -  </manifest>
    - -

    However, if you want to add a useful but non-essential feature, such as -popping up an on-screen keyboard even when a hardware keyboard is available, you -can write your program in a way that allows it to use the newer features without -failing on older devices.

    - -

    Using reflection

    - -

    Suppose there's a simple new call you want to use, like {@link -android.os.Debug#dumpHprofData(java.lang.String) -android.os.Debug.dumpHprofData(String filename)}. The {@link android.os.Debug} -class has existed since Android 1.0, but the method is new in Anroid 1.5 (API -Level 3). If you try to call it directly, your app will fail to run on devices -running Android 1.1 or earlier.

    - -

    The simplest way to call the method is through reflection. This requires -doing a one-time lookup and caching the result in a Method object. -Using the method is a matter of calling Method.invoke and un-boxing -the result. Consider the following:

    - -
    public class Reflect {
    -   private static Method mDebug_dumpHprofData;
    -
    -   static {
    -       initCompatibility();
    -   };
    -
    -   private static void initCompatibility() {
    -       try {
    -           mDebug_dumpHprofData = Debug.class.getMethod(
    -                   "dumpHprofData", new Class[] { String.class } );
    -           /* success, this is a newer device */
    -       } catch (NoSuchMethodException nsme) {
    -           /* failure, must be older device */
    -       }
    -   }
    -
    -   private static void dumpHprofData(String fileName) throws IOException {
    -       try {
    -           mDebug_dumpHprofData.invoke(null, fileName);
    -       } catch (InvocationTargetException ite) {
    -           /* unpack original exception when possible */
    -           Throwable cause = ite.getCause();
    -           if (cause instanceof IOException) {
    -               throw (IOException) cause;
    -           } else if (cause instanceof RuntimeException) {
    -               throw (RuntimeException) cause;
    -           } else if (cause instanceof Error) {
    -               throw (Error) cause;
    -           } else {
    -               /* unexpected checked exception; wrap and re-throw */
    -               throw new RuntimeException(ite);
    -           }
    -       } catch (IllegalAccessException ie) {
    -           System.err.println("unexpected " + ie);
    -       }
    -   }
    -
    -   public void fiddle() {
    -       if (mDebug_dumpHprofData != null) {
    -           /* feature is supported */
    -           try {
    -               dumpHprofData("/sdcard/dump.hprof");
    -           } catch (IOException ie) {
    -               System.err.println("dump failed!");
    -           }
    -       } else {
    -           /* feature not supported, do something else */
    -           System.out.println("dump not supported");
    -       }
    -   }
    -}
    - -

    This uses a static initializer to call initCompatibility, -which does the method lookup. If that succeeds, it uses a private -method with the same semantics as the original (arguments, return -value, checked exceptions) to do the call. The return value (if it had -one) and exception are unpacked and returned in a way that mimics the -original. The fiddle method demonstrates how the -application logic would choose to call the new API or do something -different based on the presence of the new method.

    - -

    For each additional method you want to call, you would add an additional -private Method field, field initializer, and call wrapper to the -class.

    - -

    This approach becomes a bit more complex when the method is declared in a -previously undefined class. It's also much slower to call -Method.invoke() than it is to call the method directly. These -issues can be mitigated by using a wrapper class.

    - -

    Using a wrapper class

    - -

    The idea is to create a class that wraps all of the new APIs exposed by a new -or existing class. Each method in the wrapper class just calls through to the -corresponding real method and returns the same result.

    - -

    If the target class and method exist, you get the same behavior you would get -by calling the class directly, with a small amount of overhead from the -additional method call. If the target class or method doesn't exist, the -initialization of the wrapper class fails, and your application knows that it -should avoid using the newer calls.

    - -

    Suppose this new class were added:

    public class NewClass {
    -   private static int mDiv = 1;
    -
    -   private int mMult;
    -
    -   public static void setGlobalDiv(int div) {
    -       mDiv = div;
    -   }
    -
    -   public NewClass(int mult) {
    -       mMult = mult;
    -   }
    -
    -   public int doStuff(int val) {
    -       return (val * mMult) / mDiv;
    -   }
    -}
    - -

    We would create a wrapper class for it:

    - -
    class WrapNewClass {
    -   private NewClass mInstance;
    -
    -   /* class initialization fails when this throws an exception */
    -   static {
    -       try {
    -           Class.forName("NewClass");
    -       } catch (Exception ex) {
    -           throw new RuntimeException(ex);
    -       }
    -   }
    -
    -   /* calling here forces class initialization */
    -   public static void checkAvailable() {}
    -
    -   public static void setGlobalDiv(int div) {
    -       NewClass.setGlobalDiv(div);
    -   }
    -
    -   public WrapNewClass(int mult) {
    -       mInstance = new NewClass(mult);
    -   }
    -
    -   public int doStuff(int val) {
    -       return mInstance.doStuff(val);
    -   }
    -}
    - -

    This has one method for each constructor and method in the original, plus a -static initializer that tests for the presence of the new class. If the new -class isn't available, initialization of WrapNewClass fails, -ensuring that the wrapper class can't be used inadvertently. The -checkAvailable method is used as a simple way to force class -initialization. We use it like this:

    - -
    public class MyApp {
    -   private static boolean mNewClassAvailable;
    -
    -   /* establish whether the "new" class is available to us */
    -   static {
    -       try {
    -           WrapNewClass.checkAvailable();
    -           mNewClassAvailable = true;
    -       } catch (Throwable t) {
    -           mNewClassAvailable = false;
    -       }
    -   }
    -
    -   public void diddle() {
    -       if (mNewClassAvailable) {
    -           WrapNewClass.setGlobalDiv(4);
    -           WrapNewClass wnc = new WrapNewClass(40);
    -           System.out.println("newer API is available - " + wnc.doStuff(10));
    -       } else {
    -           System.out.println("newer API not available");
    -       }
    -   }
    -}
    - -

    If the call to checkAvailable succeeds, we know the new class is -part of the system. If it fails, we know the class isn't there, and adjust our -expectations accordingly. It should be noted that the call to -checkAvailable will fail before it even starts if the bytecode -verifier decides that it doesn't want to accept a class that has references to a -nonexistent class. The way this code is structured, the end result is the same -whether the exception comes from the verifier or from the call to -Class.forName.

    - -

    When wrapping an existing class that now has new methods, you only need to -put the new methods in the wrapper class. Invoke the old methods directly. The -static initializer in WrapNewClass would be augmented to do a -one-time check with reflection.

    - -

    Testing is key

    - -

    You must test your application on every version of the Android framework that -is expected to support it. By definition, the behavior of your application will -be different on each. Remember the mantra: if you haven't tried it, it doesn't -work.

    - -

    You can test for backward compatibility by running your application in an -emulator that uses an older version of the platform. The Android SDK allows you -to do this easily by creating "Android Virtual Devices" with different API -levels. Once you create the AVDs, you can test your application with old and new -versions of the system, perhaps running them side-by-side to see the -differences. More information about emulator AVDs can be found in Creating and Managing Virtual Devices and -from emulator -help-virtual-device.

    \ No newline at end of file diff --git a/docs/html/resources/articles/can-i-use-this-intent.jd b/docs/html/resources/articles/can-i-use-this-intent.jd deleted file mode 100644 index 7787d31e39ca..000000000000 --- a/docs/html/resources/articles/can-i-use-this-intent.jd +++ /dev/null @@ -1,71 +0,0 @@ -page.title=Can I Use this Intent? -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Android offers a very powerful and yet easy-to-use message type called -an intents. -You can use intents to turn applications into high-level libraries and -make code modular and reusable. The Android Home screen and AnyCut -applications, for instance, use intents extensively to create shortcuts.

    - -

    While it is nice to be able to make use of a loosely coupled -API, there is no guarantee that the intent you send will be received by -another application. This happens in particular with third-party apps, like -Panoramio -and its RADAR intent.

    - -

    This article describes a technique you can use to find out whether the system -contains any application capable of responding to the intent you want to use. -The example below shows a helper method that queries the system package manager -to determine whether there's an app that can respond to a specified intent. Your -application can pass an intent to the method and then, for example, show or hide -user options that the user would normally use to trigger the intent.

    - -
    /**
    - * Indicates whether the specified action can be used as an intent. This
    - * method queries the package manager for installed packages that can
    - * respond to an intent with the specified action. If no suitable package is
    - * found, this method returns false.
    - *
    - * @param context The application's environment.
    - * @param action The Intent action to check for availability.
    - *
    - * @return True if an Intent with the specified action can be sent and
    - *         responded to, false otherwise.
    - */
    -public static boolean isIntentAvailable(Context context, String action) {
    -    final PackageManager packageManager = context.getPackageManager();
    -    final Intent intent = new Intent(action);
    -    List<ResolveInfo> list =
    -            packageManager.queryIntentActivities(intent,
    -                    PackageManager.MATCH_DEFAULT_ONLY);
    -    return list.size() > 0;
    -}
    -
    - -

    Here is how you could use the helper method:

    - -
    @Override
    -public boolean onPrepareOptionsMenu(Menu menu) {
    -    final boolean scanAvailable = isIntentAvailable(this,
    -        "com.google.zxing.client.android.SCAN");
    -
    -    MenuItem item;
    -    item = menu.findItem(R.id.menu_item_add);
    -    item.setEnabled(scanAvailable);
    -
    -    return super.onPrepareOptionsMenu(menu);
    -}
    -
    - -

    In this example, the menu is grayed out if the Barcode Scanner -application is not installed.

    - -

    Another, simpler, way to do this is to catch the -ActivityNotFoundException when calling startActivity() -but it only lets you react to the problem, you cannot predict it and update the -UI accordingly to prevent the user from doing something that won't work. The -technique described here can also be used at startup time to ask the user -whether he'd like to install the missing package, you can then simply redirect -him to Google Play by using the appropriate URI.

    \ No newline at end of file diff --git a/docs/html/resources/articles/contacts.jd b/docs/html/resources/articles/contacts.jd deleted file mode 100644 index 374587b284a5..000000000000 --- a/docs/html/resources/articles/contacts.jd +++ /dev/null @@ -1,424 +0,0 @@ -page.title=Using the Contacts API -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Starting from Android 2.0 (API Level 5), the Android platform provides an -improved Contacts API for managing and integrating contacts from multiple -accounts and from other data sources. To handle overlapping data from multiple -sources, the contacts content provider aggregates similar contacts and presents -them to users as a single entity. This article describes how to use the new API -to manage contacts.

    - -

    The new Contacts API is defined in the -{@link android.provider.ContactsContract android.provider.ContactsContract} -and related classes. The older API is still supported, although deprecated. -If you have an existing application that uses the older API, -see Considerations for legacy apps, below, for ideas -on how to support the Contacts API in your app.

    - -

    If you'd like to look at an applied example of how to use the new Contacts -API, including how to support both the new and older API in a single app, -please see the Business Card -sample application.

    - -

    Data structure of Contacts

    - -

    In the new Contacts API, data is laid out in three primary tables: -contacts, raw contacts, and data, a structure that -is slightly different from that used in the older API. The new structure -allows the system to more easily store and manage information for a -specific contact from multiple contacts sources.

    - - - -
      -
    • Data is a generic table that stores all of the data points -associated with a raw contact. Each row stores data of a specific kind — -for example name, photo, email addresses, phone numbers, and group memberships. -Each row is tagged with a MIME type to identify what type of data it can -contain, across the entire column. Columns are generic and the type of data they -contain is determined by the kind of data stored in each row. For example, if a -row's data kind is Phone.CONTENT_ITEM_TYPE, then the first column -stores the phone number, but if the data kind is -Email.CONTENT_ITEM_TYPE, then the column stores the email address. - -

      The {@link android.provider.ContactsContract.CommonDataKinds ContactsContract.CommonDataKinds} -class provides subclasses corresponding to common MIME types for contacts data. -If needed, your application or other contacts sources can define additional MIME -types for data rows. For more information about the Data table and examples of -how to use it, see {@link android.provider.ContactsContract.Data android.provider.ContactsContract.Data}.

    • - -
    • A row in the RawContacts table represents the set of -Data and other information describing a person and associated with -a single contacts source. For example, a row might define the data associated -with a person's Google or Exchange account or Facebook friend. For more -information, see -{@link android.provider.ContactsContract.RawContacts ContactsContract.RawContacts}.

      - -
    • A row in the Contacts table represents an aggregate of one or -more RawContacts describing the same person (or entity). - -

      As mentioned above, the Contacts content provider automatically aggregates -Raw Contacts into a single Contact entry, where possible, since common data -fields (such as name or email address) are likely to be stored in each raw -contact. Since the aggregation logic maintains the entries in the Contact rows, -the entries can be read but should not be modified. See the section Aggregation of contacts, below, for more details, -including and information on how to -control aggregation.

    • - -
    - -

    When displaying contacts to users, applications should typically operate on -the Contacts level, since it provides a unified, aggregated view of contacts -from various underlying sources.

    - -

    Example: Inserting a Phone Number

    - -

    To insert a phone number using the new APIs you'll need the ID of the Raw -Contact to attach the phone number to, then you'll need to create a Data -row:

    - -
    import android.provider.ContactsContract.CommonDataKinds.Phone;
    -...
    -ContentValues values = new ContentValues();
    -values.put(Phone.RAW_CONTACT_ID, rawContactId);
    -values.put(Phone.NUMBER, phoneNumber);
    -values.put(Phone.TYPE, Phone.TYPE_MOBILE);
    -Uri uri = getContentResolver().insert(Phone.CONTENT_URI, values);
    - - -

    Aggregation of contacts

    - -

    When users sync contacts from multiple sources, several contacts might refer -to the same person or entity, but with slightly different (or overlapping) data. - For example, "Bob Parr" might be a user's co-worker and also his personal -friend, so the user might have his contact information stored in both a -corporate email account and a personal account. To provide a simplified view for -the user, the system locates such overlapping contacts and combines them into a -single, aggregate contact.

    - -

    The system automatically aggregates contacts by default. However, if needed, -your application can control how the system handles aggregation or it can -disable aggregation altogether, as described in the sections below.

    - -

    Automatic aggregation

    - -

    When a raw contact is added or modified, the system looks for matching -(overlapping) raw contacts with which to aggregate it. It may not find any -matching raw contacts, in which case it will create an aggregate contact that -contains just the original raw contact. If it finds a single match, it creates a -new contact that contains the two raw contacts. And it may even find multiple -similar raw contacts, in which case it chooses the closest match.

    - -

    Two raw contacts are considered to be a match if at least one of these -conditions is met:

    - -
      -
    • They have matching names.
    • -
    • Their names consist of the same words but in different order -(for example, "Bob Parr" and "Parr, Bob")
    • -
    • One of them has a common short name for the other (for example, -"Bob Parr" and "Robert Parr")
    • -
    • One of them has just a first or last name and it matches the other -raw contact. This rule is less reliable, so it only applies if the two -raw contacts are also sharing some other data like a phone number, an -email address or a nickname (for example, Helen ["elastigirl"] = Helen -Parr ["elastigirl"])
    • -
    • At least one of the two raw contacts is missing the name altogether -and they are sharing a phone number, an email address or a nickname (for -example, Bob Parr [incredible@android.com] = incredible@android.com).
    • -
    - -

    When comparing names, the system ignores upper/lower case differences -(Bob=BOB=bob) and diacritical marks (Hélène=Helene). When comparing two -phone numbers the system ignores special characters such as "*", "#", -"(", ")", and whitespace. Also if the only difference between two numbers -is that one has a country code and the other does not, then the system -considers those to be a match (except for numbers in the Japan country code).

    - -

    Automatic aggregation is not permanent; any change of a constituent raw -contact may create a new aggregate or break up an existing one.

    - -

    Explicit aggregation

    - -

    In some cases, the system's automatic aggregation may not meet the -requirements of your application or sync adapter. There are two sets of APIs you -can use to control aggregation explicitly: aggregation modes allow you -to control automatic aggregation behaviors and aggregation exceptions -allow you to override automated aggregation entirely. - -

    Aggregation modes

    - -

    You can set an aggregation mode for each raw contact individually. To do so, -add a mode constant as the value of the AGGREGATION_MODE column in -the RawContact row. The mode constants available include:

    - -
      -
    • AGGREGATION_MODE_DEFAULT — normal mode, automatic -aggregation is allowed.
    • -
    • AGGREGATION_MODE_DISABLED — automatic aggregation is not -allowed. The raw contact will not be aggregated.
    • -
    • AGGREGATION_MODE_SUSPENDED — automatic aggregation is -deactivated. If the raw contact is already a part of an aggregated contact when -aggregation mode changes to suspended, it will remain in the aggregate, even if -it changes in such a way that it no longer matches the other raw contacts in the -aggregate.
    • -
    - -

    Aggregation exceptions

    - -

    To keep two raw contacts unconditionally together or unconditionally apart, -you can add a row to the -{@link android.provider.ContactsContract.AggregationExceptions} table. Exceptions -defined in the table override all automatic aggregation rules.

    - - -

    Loookup URI

    - -

    The new Contacts API introduces the notion of a lookup key for a contact. If -your application needs to maintain references to contacts, you should use lookup -keys instead of the traditional row ids. You can acquire a lookup key from the -contact itself, it is a column on the -{@link android.provider.ContactsContract.Contacts} table. Once you have a lookup key, -you can construct a URI in this way:

    - -
    Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey)
    - -

    and use it like you would use a traditional content URI, for example:

    - -
    Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME}, ...);
    -try {
    -    c.moveToFirst();
    -    String displayName = c.getString(0);
    -} finally {
    -    c.close();
    -}
    - -

    The reason for this complication is that regular contact row IDs are -inherently volatile. Let's say your app stored a long ID of a contact. Then the -user goes and manually joins the contact with some other contact. Now there is a -single contact where there used to be two, and the stored long contact ID points -nowhere. - -

    The lookup key helps resolve the contact in this case. The key is a string -that concatenates the server-side identities of the raw contacts. Your -application can use that string to find a contact, regardless whether the raw -contact is aggregated with others or not.

    - -

    If performance is a concern for your application, you might want to store -both the lookup and the long ID of a contact and construct a lookup URI out of -both IDs, as shown here:

    - -
    Uri lookupUri = getLookupUri(contactId, lookupKey)
    - -

    When both IDs are present in the URI, the system will try to use the long ID -first. That is a very quick query. If the contact is not found, or if the one -that is found has the wrong lookup key, the content provider will parse the -lookup key and track down the constituent raw contacts. If your app -bulk-processes contacts, you should maintain both IDs. If your app works with a -single contact per user action, you probably don't need to bother with storing -the long ID.

    - -Android itself uses lookup URIs whenever there is a need to reference a contact, -such as with shortcuts or Quick Contact, and also during editing or even viewing -a contact. The latter case is less obvious — why would a contact ID change -while we are simply viewing the contact? It could change because there might be -a sync going in the background, and the contact might get automatically -aggregated with another while being viewed.

    - -

    In summary: whenever you need to reference a contact, we recommend that you -do so by its lookup URI.

    - - -

    Considerations for legacy applications

    - -

    If you have an existing application that uses the older Contacts API, -you should consider upgrading it to use the new API. You have four options:

    - -
      -
    • Leave it as-is and rely on the Contacts compatibility mode.
    • -
    • Upgrade the app and discontinue support of pre-Android 2.0 platforms.
    • -
    • Build a new version of the app for the new API, while keeping the old version available.
    • -
    • Make the app use the right set of APIs depending on the platform where it is deployed.
    • -
    - -

    Let's consider these options one by one.

    - -

    Using compatibility mode

    - -

    Compatibility mode is the easiest option because you just leave the -application as is, and it should run on Android 2.0 as long as it only uses -public APIs. A couple examples of the use of non-public API include the use of -explicit table names in nested queries and the use of columns that were not -declared as public constants in the {@link android.provider.Contacts} class. -

    - -

    Even if the application currently runs, you don't want to leave it like this -for long. The main reason is that it will only have access to contacts from one -account, namely the first Google account on the device. If the user opens other -accounts in addition to or instead of a Google account, your application will -not be able to access those contacts.

    - - -

    Upgrading to the new API and dropping support for older platforms

    - -

    If your application will no longer target platforms older than -Android 2.0, you can upgrade to the new API in this way:

    - -
      -
    • Replace all usages of {@link android.provider.Contacts} with calls to new -API. After you are done, you should not see any deprecation warnings during -application build. The new application will be able to take full advantage of -multiple accounts and other new features of Android 2.0.

      - -
    • In the application's manifest, update (or add) the -android:minSdkVersion attribute to the -<uses-sdk> element. To use the new Contacts API, you should -set the value of the attribute to "5" (or higher, as appropriate). For more -information about android:minSdkVersion, see the documentation for -the <uses-sdk> -element. For more information about the value of the -minSdkVersion, see API Levels.
    • -
    - -

    Maintaining two applications

    - -

    You may decide to have two different applications: one for pre-Android 2.0 -platforms and one for Android 2.0 and beyond. If so, here's what you'll need to do:

    - -
      -
    • Clone your existing app.
    • -
    • Change the old application:
    • -
        -
      • At launch time, check the version of the SDK. The version of the SDK -is available as {@link android.os.Build.VERSION#SDK android.os.Build.VERSION.SDK}.
      • -
      • If the SDK version is greater or equal to 5 (Android 2.0), show a dialog -suggesting to the user that it's time to go to Google Play and find a new version of -the app. You can even provide a link to the new app on Google Play (see Using Intents -to Launch Google Play).
      • -
      -
    • Change the new application:
    • -
        -
      • Replace all usages of the older Contacts API with calls to new API. -The new application will be able to take full advantage of multiple accounts -and other new features of Android 2.0.
      • -
      • Modify that application's AndroidManifest.xml file:
      • -
          -
        • Give the application a new name and a new package name. Currently -Google Play does not allow you to have two applications with the same -name/package.
        • -
        • Update (or add) the android:minSdkVersion attribute -to the <uses-sdk> element. To use the new Contacts API, -you should set the value of the attribute to "5" (or higher, as appropriate).
        • -
        -
      -
    • Publish both apps on Google Play, the old app one as an upgrade and the -other as new. Make sure to explain the difference between the apps in their -descriptions.
    • -
    - -

    This plan has its disadvantages:

    - -
      -
    • The new application will not be able to read the old application's data. -Application data can only be accessed by code living in the same package. So -databases, shared preferences, and so on, will need to be populated from -scratch.
    • -
    • The upgrade process is too clunky for the user. Some users may choose -to either stay with the crippled old version or uninstall altogether.
    • -
    - -

    Supporting the old and new APIs in the same application

    - -

    This is a bit tricky, but the result is worth the effort. You can -build a single package that will work on any platform:

    - -

    Go through the existing application and factor out all access to -{@link android.provider.Contacts} into one class, such as ContactAccessorOldApi. -For example, if you have code like this: - -

        protected void pickContact() {
    -        startActivityForResult(new Intent(Intent.ACTION_PICK, People.CONTENT_URI), 0);
    -    }
    - -

    it will change to:

    - - -
        private final ContactAccessorOldApi mContactAccessor = new ContactAccessorOldApi();
    -
    -    void pickContact() {
    -        startActivityForResult(mContactAccessor.getContactPickerIntent(), 0);
    -    }
    - -

    The corresponding method on ContactAccessorOldApi will look like this:

    - -
        public Intent getContactPickerIntent() {
    -        return new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
    -    }
    - -

    Once you are done, you should see deprecation warnings coming only -from ContactAccessorOldApi.

    - -

    Create a new abstract class ContactAccessor, make sure the abstract -class has all method signatures from ContactAccessorOldApi. Make -ContactAccessorOldApi extend ContactAccessor:

    - -
        public abstract class ContactAccessor {
    -        public abstract Intent getContactPickerIntent();
    -        ...
    -    }
    - -

    Create a new subclass of ContactAccessor, ContactAccessorNewApi and -implement all methods using the new API:

    - -
        public class ContactAccessorNewApi extends ContactAccessor {    
    -        @Override
    -        public Intent getContactPickerIntent() {
    -            return new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
    -        }
    -        ...
    -    }
    - -

    At this point, you have two implementations of the same API, one using the -old API and another using the new API. Let's plug them in. Add this code to -the ContactAccessor class:

    - -
        private static ContactAccessor sInstance;
    -
    -    public static ContactAccessor getInstance() {
    -        if (sInstance == null) {
    -            String className;
    -            int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
    -            if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
    -                className = "ContactAccessorOldApi";
    -            } else {
    -                className = "ContactAccessorNewApi";
    -            }
    -            try {
    -                Class<? extends ContactAccessor> clazz =
    -                        Class.forName(ContactAccessor.class.getPackage() + "." + className)
    -                                .asSubclass(ContactAccessor.class);
    -                sInstance = clazz.newInstance();
    -            } catch (Exception e) {
    -                throw new IllegalStateException(e);
    -            }
    -        }
    -        return sInstance;
    -    }
    - -

    Now replace references to ContactsAccessorOldApi with references to -ContactsAccessor:

    - -
        private final ContactAccessor mContactAccessor = ContactAccessor.getInstance();
    - -

    You are done! Now you will want to test on Android 2.0, 1.6 and 1.5.

    - -

    We hope you like the new features and APIs we've added to Contacts in -Android 2.0, and we can't wait to see what cool things developers do with -the new APIs.

    diff --git a/docs/html/resources/articles/creating-input-method.jd b/docs/html/resources/articles/creating-input-method.jd deleted file mode 100644 index 84c2704f5568..000000000000 --- a/docs/html/resources/articles/creating-input-method.jd +++ /dev/null @@ -1,528 +0,0 @@ -page.title=Creating an Input Method -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -
    -
    -

    See also

    -
      -
    1. - Onscreen Input Methods -
    2. -
    3. - Soft Keyboard sample -
    4. -
    -
    -
    -

    - An input method editor (IME) is a user control that enables users to enter text. Android - provides an extensible input method framework that allows applications to provide users - alternative input methods, such as on-screen keyboards or even speech input. Once installed, - users can select which IME they want to use from the system settings and use it across the - entire system; only one IME may be enabled at a time. -

    -

    - To add an IME to the Android system, you create an Android application - containing a class that extends {@link android.inputmethodservice.InputMethodService}. In - addition, you usually create a "settings" activity that passes options to the IME - service. You can also define a settings UI that's displayed as part of the system settings. -

    -

    This article covers the following:

    -
      -
    • The IME lifecycle.
    • -
    • Declaring IME components in the application manifest.
    • -
    • The IME API.
    • -
    • Designing an IME UI.
    • -
    • Sending text from an IME to an application.
    • -
    • Working with IME subtypes.
    • -
    -

    - If you haven't worked with IMEs before, you should read the introductory article - Onscreen Input Methods first. - Also, the Soft Keyboard sample app included in the SDK contains sample code that you can modify - to start building your own IME. -

    -

    The IME Lifecycle

    -

    - The following diagram describes the life cycle of an IME: -

    - -

    - Figure 1. The life cycle of an IME. -

    -

    - The following sections describe how to implement the UI and code associated with an IME that - follows this lifecycle. -

    -

    Declaring IME Components in the Manifest

    -

    - In the Android system, an IME is an Android application that contains a special IME service. - The application's manifest file must declare the service, request the necessary permissions, - provide an intent filter that matches the action action.view.InputMethod, and - provide metadata that defines characteristics of the IME. In addition, to provide a settings - interface that allows the user to modify the behavior of the IME, you can define a "settings" - activity that can be launched from System Settings. -

    -

    - The following snippet declares IME service. It requests the permission {@link - android.Manifest.permission#BIND_INPUT_METHOD} to allow the service to connect the IME to - the system, sets up an intent filter that matches the action - android.view.InputMethod, and defines metadata for the IME: -

    -
    -<!-- Declares the input method service -->
    -    <service android:name="FastInputIME"
    -        android:label="@string/fast_input_label"
    -        android:permission="android.permission.BIND_INPUT_METHOD">
    -        <intent-filter>
    -            <action android:name="android.view.InputMethod" />
    -        </intent-filter>
    -        <meta-data android:name="android.view.im" android:resource="@xml/method" />
    -    </service>
    -
    -

    - This next snippet declares the settings activity for the IME. It has an intent filter for - {@link android.content.Intent#ACTION_MAIN} that indicates this activity is the main entry point - for the IME application:

    -
    -    <!-- Optional: an activity for controlling the IME settings -->
    -    <activity android:name="FastInputIMESettings" 
    -        android:label="@string/fast_input_settings">
    -        <intent-filter>
    -            <action android:name="android.intent.action.MAIN"/>
    -        </intent-filter>
    -    </activity>
    -
    -

    - You can also provide access to the IME's settings directly from its UI. -

    -

    The Input Method API

    -

    - Classes specific to IMEs are found in the {@link android.inputmethodservice} and {@link - android.view.inputmethod} packages. The {@link android.view.KeyEvent} class is important for - handling keyboard characters. -

    -

    - The central part of an IME is a service component, a class that extends - {@link android.inputmethodservice.InputMethodService}. In addition to implementing the - normal service lifecycle, this class has callbacks for providing your IME's UI, handling user - input, and delivering text to the field that currently has focus. By default, the - {@link android.inputmethodservice.InputMethodService} class provides most of the implementation - for managing the state and visibility of the IME and communicating with the current - input field. -

    -

    - The following classes are also important: -

    -
    -
    {@link android.view.inputmethod.BaseInputConnection}
    -
    - Defines the communication channel from an {@link android.view.inputmethod.InputMethod} - back to the application that is receiving its input. You use it to read text around the - cursor, commit text to the text box, and send raw key events to the application. - Applications should extend this class rather than implementing the base interface - {@link android.view.inputmethod.InputConnection}. -
    -
    {@link android.inputmethodservice.KeyboardView}
    -
    - An extension of {@link android.view.View} that renders a keyboard and responds to user - input events. The keyboard layout is specified by an instance of - {@link android.inputmethodservice.Keyboard}, which you can define in an XML file. -
    -
    -

    Designing the Input Method UI

    -

    - There are two main visual elements for an IME: the input view and the - candidates view. You only have to implement the elements that are relevant to - the input method you're designing. -

    -

    Input view

    -

    - The input view is the UI where the user inputs text, in the form of keyclicks, handwriting or - gestures. When the iIME is displayed for the first time, the system calls the - {@link android.inputmethodservice.InputMethodService#onCreateInputView()} callback. In your - implementation of this method, you create the layout you want to display in the IME - window and return the layout to the system. This snippet is an example of implementing the - {@link android.inputmethodservice.InputMethodService#onCreateInputView()} method: -

    -    @Override 
    -    public View onCreateInputView() { 
    -        MyKeyboardView inputView = 
    -            (MyKeyboardView) getLayoutInflater().inflate( R.layout.input, null);
    -    
    -        inputView.setOnKeyboardActionListener(this); inputView.setKeyboard(mLatinKeyboard); 
    -        
    -        return mInputView; 
    -    } 
    -
    -

    - In this example, {@code MyKeyboardView} is an instance of a custom implementation of - {@link android.inputmethodservice.KeyboardView} that renders a - {@link android.inputmethodservice.Keyboard}. If you’re building a traditional QWERTY keyboard, - see the Soft Keyboard sample - app for an example of how to extend the {@link android.inputmethodservice.KeyboardView} class. -

    -

    Candidates view

    -

    - The candidates view is the UI where the IME displays potential word corrections or - suggestions for the user to select. In the IME lifecycle, the system calls - {@link android.inputmethodservice.InputMethodService#onCreateCandidatesView()} when it's ready - to display the candidate view. In your implementation of this method, return a layout that shows - word suggestions, or return null if you don’t want to show anything (a null response is the - default behavior, so you don’t have to implement this if you don’t provide suggestions).

    -

    - For an example implementation that provides user suggestions, see the - Soft Keyboard sample app. -

    -

    UI design considerations

    -

    - This section describes some specific UI design considerations for IMEs. -

    -

    Handling multiple screen sizes

    -

    - The UI for your IME must be able to scale for different screen sizes, and it also - must handle both landscape and portrait orientations. In non-fullscreen IME mode, leave - sufficient space for the application to show the text field and any associated context, so that - no more than half the screen is occupied by the IME. In fullscreen IME mode this is not an - issue. -

    -

    Handling different input types

    -

    - Android text fields allow you to set a specific input type, such as free form text, numbers, - URLs, email addresses, and search strings. When you implement a new IME, you need to - detect the input type of each field and provide the appropriate interface for it. However, you - don't have to set up your IME to check that the user entered text that's valid for the - input type; that's the responsibility of the application that owns the text field. -

    -

    - For example, here are screenshots of the interfaces that the Latin IME provided with the - Android platform provides for text and phone number inputs: -

    - - -

    - Figure 2. Latin IME input types. -

    -

    - When an input field receives focus and your IME starts, the system calls - {@link android.inputmethodservice.InputMethodService#onStartInputView(EditorInfo, boolean) - onStartInputView()}, passing in an {@link android.view.inputmethod.EditorInfo} object that - contains details about the input type and other attributes of the text field. In this object, - the {@link android.view.inputmethod.EditorInfo#inputType} field contains the text field's input - type. -

    -

    - The {@link android.view.inputmethod.EditorInfo#inputType} field is an int - that contains bit patterns for various input type settings. To test it for the text field's - input type, mask it with the constant {@link android.text.InputType#TYPE_MASK_CLASS}, like - this: -

    -
    -inputType & InputType.TYPE_MASK_CLASS 
    -
    -

    -The input type bit pattern can have one of several values, including: -

    -
    -
    {@link android.text.InputType#TYPE_CLASS_NUMBER}
    -
    - A text field for entering numbers. As illustrated in the previous screen shot, the - Latin IME displays a number pad for fields of this type. -
    -
    {@link android.text.InputType#TYPE_CLASS_DATETIME}
    -
    - A text field for entering a date and time. -
    -
    {@link android.text.InputType#TYPE_CLASS_PHONE}
    -
    - A text field for entering telephone numbers. -
    -
    {@link android.text.InputType#TYPE_CLASS_TEXT}
    -
    - A text field for entering all supported characters. -
    -
    -

    - These constants are described in more detail in the reference documentation for - {@link android.text.InputType}. -

    -

    - The {@link android.view.inputmethod.EditorInfo#inputType} field can contain other bits that - indicate a variant of the text field type, such as: -

    -
    -
    {@link android.text.InputType#TYPE_TEXT_VARIATION_PASSWORD}
    -
    - A variant of {@link android.text.InputType#TYPE_CLASS_TEXT} for entering passwords. The - input method will display dingbats instead of the actual text. -
    -
    {@link android.text.InputType#TYPE_TEXT_VARIATION_URI}
    -
    - A variant of {@link android.text.InputType#TYPE_CLASS_TEXT} for entering web URLs and - other Uniform Resource Identifiers (URIs). -
    -
    {@link android.text.InputType#TYPE_TEXT_FLAG_AUTO_COMPLETE}
    -
    - A variant of {@link android.text.InputType#TYPE_CLASS_TEXT} for entering text that the - application "auto-completes" from a dictionary, search, or other facility. -
    -
    -

    - Remember to mask {@link android.view.inputmethod.EditorInfo#inputType} with the appropriate - constant when you test for these variants. The available mask constants are listed in the - reference documentation for {@link android.text.InputType}. -

    -

    - Caution: In your own IME, make sure you handle text correctly when you send it - to a password field. Hide the password in your UI both in the input view and in the candidates - view. Also remember that you shouldn't store passwords on a device. To learn more, see the Designing for Security guide. -

    -

    Sending Text to the Application

    -

    - As the user inputs text with your IME, you can send text to the application by - sending individual key events or by editing the text around the cursor in the application's text - field. In either case, you use an instance of {@link android.view.inputmethod.InputConnection} - to deliver the text. To get this instance, call - {@link android.inputmethodservice.InputMethodService#getCurrentInputConnection - InputMethodService.getCurrentInputConnection()}. -

    -

    Editing the text around the cursor

    -

    - When you're handling the editing of existing text in a text field, some of the more useful - methods in {@link android.view.inputmethod.BaseInputConnection} are: -

    -
    -
    - {@link android.view.inputmethod.BaseInputConnection#getTextBeforeCursor(int, int) - getTextBeforeCursor()}
    -
    - Returns a {@link java.lang.CharSequence} containing the number of requested characters - before the current cursor position. -
    -
    - {@link android.view.inputmethod.BaseInputConnection#getTextAfterCursor(int, int) - getTextAfterCursor()} -
    -
    - Returns a {@link java.lang.CharSequence} containing the number of requested characters - following the current cursor position. -
    -
    - {@link android.view.inputmethod.BaseInputConnection#deleteSurroundingText(int, int) - deleteSurroundingText()} -
    -
    - Deletes the specified number of characters before and following the current cursor - position. -
    -
    - {@link android.view.inputmethod.BaseInputConnection#commitText(CharSequence, int) - commitText()} -
    -
    - Commit a {@link java.lang.CharSequence} to the text field and set a new cursor - position. -
    -
    -

    - For example, the following snippet shows how to replace the text "Fell" to the left of the - with the text "Hello!": -

    -
    -    InputConnection ic = getCurrentInputConnection();
    -    
    -    ic.deleteSurroundingText(4, 0);
    -    
    -    ic.commitText("Hello", 1);
    -    
    -    ic.commitText("!", 1);
    -
    -

    Composing text before committing

    -

    - If your IME does text prediction or requires multiple steps to compose a glyph or - word, you can show the progress in the text field until the user commits the word, and then you - can replace the partial composition with the completed text. You may give special treatment to - the text by adding a "span" to it when you pass it to InputConnection#setComposingText(). -

    -

    - The following snippet shows how to show progress in a text field: -

    -
    -    InputConnection ic = getCurrentInputConnection();
    -
    -    ic.setComposingText("Composi", 1);
    -...
    -
    -    ic.setComposingText("Composin", 1);
    -
    -...
    -
    -    ic.commitText("Composing ", 1);
    -
    -

    - The following screenshots show how this appears to the user: -

    - - - -

    - Figure 3. Composing text before committing. -

    -

    Intercepting hardware key events

    -

    - Even though the input method window doesn't have explicit focus, it receives hardware key - events first and can choose to consume them or forward them along to the application. For - example, you may want to consume the directional keys to navigate within your UI for candidate - selection during composition. You may also want to trap the back key to dismiss any popups - originating from the input method window.

    -

    - To intercept hardware keys, override - {@link android.inputmethodservice.InputMethodService#onKeyDown(int, KeyEvent) onKeyDown()} - and {@link android.inputmethodservice.InputMethodService#onKeyUp(int, KeyEvent) onKeyUp()}. - See the Soft Keyboard sample - app for an example. -

    -

    - Remember to call the super() method for keys you don't want to handle yourself. -

    -

    Creating an IME Subtype

    -

    - Subtypes allow the IME to expose multiple input modes and languages supported by an IME. A - subtype can represent: -

    -
      -
    • A locale such as en_US or fr_FR
    • -
    • An input mode such as voice, keyboard, or handwriting
    • -
    • - Other input styles, forms, or properties specific to the IME, such as 10-key or qwerty - keyboard layouts. -
    • -
    -

    - Basically, the mode can be any text such as "keyboard", "voice", and so forth. -

    -

    A subtype can also expose a combination of these.

    -

    - Subtype information is used for an IME switcher dialog that's available from the notification - bar and also for IME settings. The information also allows the framework to bring up a - specific subtype of an IME directly. When you build an IME, use the subtype facility, because - it helps the user identify and switch between different IME languages and modes. -

    -

    - You define subtypes in one of the input method's XML resource files, using the - <subtype> element. The following snippet defines an IME with two - subtypes: a keyboard subtype for the US English locale, and another keyboard subtype for the - French language locale for France: -

    -
    -<input-method xmlns:android="http://schemas.android.com/apk/res/android"
    -        android:settingsActivity="com.example.softkeyboard.Settings"
    -        android:icon="@drawable/ime_icon"
    -    <subtype android:name="@string/display_name_english_keyboard_ime"
    -            android:icon="@drawable/subtype_icon_english_keyboard_ime"
    -            android:imeSubtypeLanguage="en_US"
    -            android:imeSubtypeMode="keyboard"
    -            android:imeSubtypeExtraValue="somePrivateOption=true"
    -    />
    -    <subtype android:name="@string/display_name_french_keyboard_ime"
    -            android:icon="@drawable/subtype_icon_french_keyboard_ime"
    -            android:imeSubtypeLanguage="fr_FR"
    -            android:imeSubtypeMode="keyboard"
    -            android:imeSubtypeExtraValue="foobar=30,someInternalOption=false"
    -    />
    -    <subtype android:name="@string/display_name_german_keyboard_ime"
    -            ...
    -    />
    -/>
    -
    -

    - To ensure that your subtypes are labeled correctly in the UI, use %s to get a subtype label - that is the same as the subtype’s locale label. This is demonstrated in the next two snippets. - The first snippet shows part of the input method's XML file: -

    -
    -    <subtype
    -        android:label="@string/label_subtype_generic"
    -        android:imeSubtypeLocale="en_US"
    -        android:icon="@drawable/icon_en_us"
    -        android:imeSubtypeMode="keyboard" />
    -
    -

    - The next snippet is part of the IME's strings.xml file. The string - resource label_subtype_generic, which is used by the input method UI definition to - set the subtype's label, is defined as: -

    -
    -<string name="label_subtype_generic">%s</string>
    -
    -

    - This sets the subtype’s display name to “English (United States)” in any English language - locale, or to the appropriate localization in other locales. -

    -

    Choosing IME subtypes from the notification bar

    -

    - The Android system manages all subtypes exposed by all IMEs. IME subtypes are - treated as modes of the IME they belong to. In the notification bar, a user can select an - available subtype for the currently-set IME, as shown in the following screenshot: -

    - -

    - Figure 4. Choosing an IME subtype from the notification bar. -

    - -

    - Figure 5. Setting subtype preferences in System Settings. -

    -

    Choosing IME subtypes from System Settings

    -

    - A user can control how subtypes are used in the “Language & input” settings panel in the - System Settings area. In the Soft Keyboard sample, the file - InputMethodSettingsFragment.java contains an implementation that - facilitates a subtype enabler in the IME settings. Please refer to the SoftKeyboard sample in - the Android SDK for more information about how to support Input Method Subtypes in your IME. -

    - -

    - Figure 6. Choosing a language for the IME. -

    -

    General IME Considerations

    -

    - Here are some other things to consider as you're implementing your IME: -

    -
      -
    • - Provide a way for users to set options directly from the IME's UI. -
    • -
    • - Because multiple IMEs may be installed on the device, provide a way for the user to switch to a - different IME directly from the input method UI. -
    • -
    • - Bring up the IME's UI quickly. Preload or load on demand any large resources so that users - see the IME as soon as they tap on a text field. Cache resources and views for subsequent - invocations of the input method. -
    • -
    • - Conversely, you should release large memory allocations soon after the input method window is - hidden, so that applications can have sufficient memory to run. Consider using a delayed message - to release resources if the IME is in a hidden state for a few seconds. -
    • -
    • - Make sure that users can enter as many characters as possible for the language or locale - associated with the IME. Remember that users may use punctuation in passwords or user - names, so your IME has to provide many different characters to allow users to enter a - password and get access to the device. -
    • -
    diff --git a/docs/html/resources/articles/drawable-mutations.jd b/docs/html/resources/articles/drawable-mutations.jd deleted file mode 100644 index c5818fcbafb9..000000000000 --- a/docs/html/resources/articles/drawable-mutations.jd +++ /dev/null @@ -1,93 +0,0 @@ -page.title=Drawable Mutations -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Android's drawables are extremely useful to easily build applications. A -{@link android.graphics.drawable.Drawable Drawable} is a pluggable drawing -container that is usually associated with a View. For instance, a -{@link android.graphics.drawable.BitmapDrawable BitmapDrawable} is used to display -images, a {@link android.graphics.drawable.ShapeDrawable ShapeDrawable} to draw -shapes and gradients, and so on. You can even combine them to create complex -renderings.

    - -

    Drawables allow you to easily customize the rendering of the widgets without -subclassing them. As a matter of fact, they are so convenient that most of the -default Android apps and widgets are built using drawables; there are about 700 -drawables used in the core Android framework. Because drawables are used so -extensively throughout the system, Android optimizes them when they are loaded -from resources. For instance, every time you create a -{@link android.widget.Button Button}, a new drawable is loaded from the framework -resources (android.R.drawable.btn_default). This means all buttons -across all the apps use a different drawable instance as their background. -However, all these drawables share a common state, called the "constant state." -The content of this state varies according to the type of drawable you are -using, but it usually contains all the properties that can be defined by a -resource. In the case of a button, the constant state contains a bitmap image. -This way, all buttons across all applications share the same bitmap, which saves -a lot of memory.

    - -

    The following diagram shows what entities are -created when you assign the same image resource as the background of -two different views. As you can see, two drawables are created but they -both share the same constant state, hence the same bitmap:

    - - - -

    This state sharing feature is great to avoid wasting memory but it can cause -problems when you try to modify the properties of a drawable. Imagine an -application with a list of books. Each book has a star next to its name, totally -opaque when the user marks the book as a favorite, and translucent when the book -is not a favorite. To achieve this effect, you would probably write the -following code in your list adapter's getView() method:

    - -
    Book book = ...;
    -TextView listItem = ...;
    -
    -listItem.setText(book.getTitle());
    -
    -Drawable star = context.getResources().getDrawable(R.drawable.star);
    -if (book.isFavorite()) {
    -  star.setAlpha(255); // opaque
    -} else {
    -  star.setAlpha(70); // translucent
    -}
    - -

    Unfortunately, this piece of code yields a rather strange result: -all of the drawables have the same opacity:

    - - - -

    This -result is explained by the constant state. Even though we are getting a -new drawable instance for each list item, the constant state remains -the same and, in the case of BitmapDrawable, the opacity is part of the -constant state. Thus, changing the opacity of one drawable instance -changes the opacity of all the other instances. Even worse, working -around this issue was not easy with Android 1.0 and 1.1.

    - -

    Android 1.5 and higher offers a very easy way to solve this issue -with the new {@link android.graphics.drawable.Drawable#mutate()} method. -When you invoke this method on a drawable, the constant state of the -drawable is duplicated to allow you to change any property without -affecting other drawables. Note that bitmaps are still shared, even -after mutating a drawable. The diagram below shows what happens when -you invoke mutate() on a drawable:

    - - - -

    Let's update our previous piece of code to make use of mutate():

    - -
    Drawable star = context.getResources().getDrawable(R.drawable.star);
    -if (book.isFavorite()) {
    -  star.mutate().setAlpha(255); // opaque
    -} else {
    -  star. mutate().setAlpha(70); // translucent
    -}
    - -

    For convenience, mutate() -returns the drawable itself, which allows to chain method calls. It -does not however create a new drawable instance. With this new piece of -code, our application now behaves correctly:

    - - diff --git a/docs/html/resources/articles/faster-screen-orientation-change.jd b/docs/html/resources/articles/faster-screen-orientation-change.jd deleted file mode 100644 index e7b73bf2d6ae..000000000000 --- a/docs/html/resources/articles/faster-screen-orientation-change.jd +++ /dev/null @@ -1,133 +0,0 @@ -page.title=Faster Screen Orientation Change -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -
    -
    - -

    See also

    -
      -
    1. Handling Runtime -Changes
    2. -
    - -
    -
    - -

    Android is designed to run efficiently on a wide -array of devices, with very different hardware configurations. Some -devices, like the T-Mobile G1, can change their hardware configuration -at runtime. For instance, when you open the keyboard, the screen change -from the portrait orientation to the landscape orientation. - -

    - -

    To make -Android app development easier, the Android system automatically handles -configuration change events and restarts the current activity with the new -configuration. This is the default behavior that lets you declare -resources like layouts and drawables based on the orientation, screen -size, locale, etc.

    - -

    While this behavior is really powerful, since your application adapts -automatically to the device's configuration at runtime, it is sometimes -confusing for new Android developers, who wonder why their activity is -destroyed and recreated.

    - -

    Facing this "issue," some developers choose to handle configuration changes -themselves which is, in general, a short-term solution that will only complicate -their lives later. On the other hand, the system's automatic resource handling -is a very efficient and easy way to adapt an application's user interface to -various devices and devices configurations. It sometimes comes at a price, -though.

    - -

    When your application displays a lot of data, or data that is expensive to fetch, -the automatic destruction/creation of the activities can be lead to a -painful user experience. Take the example of Photostream, -a simple Flickr browsing application. After you launch the application and choose a Flickr account, the -application downloads a set of 6 photos (on a T-Mobile G1) from the -Flickr servers and displays them on screen. To improve the user -experience, the application uses slightly different layouts and drawables in -portrait and landscape modes and this is what the result looks like:

    - -

    - -

    - -

    Photostream lets Android take care of the configuration change when the -screen is rotated. However, can you imagine how painful it would be for the user -to see all the images being downloaded again? The obvious solution to this -problem is to temporarily cache the images. They could be cached on the SD card -(if there's one), in the Application object, in a static field, etc. None of -these techniques is adapted to the current situation: why should we bother -caching the images when the screen is not rotated? Fortunately for us, Android -offers a great API exactly for that purpose.

    - -

    The Activity class has a special method called -{@link android.app.Activity#onRetainNonConfigurationInstance()}. This method -can be used to pass an arbitrary object to your future self and Android -is smart enough to call this method only when needed. In the case of Photostream, -the application used this method -to pass the downloaded images to the future activity on orientation change. -The implementation can be summarized like so:

    - -
    @Override
    -public Object onRetainNonConfigurationInstance() {
    -    final LoadedPhoto[] list = new LoadedPhoto[numberOfPhotos];
    -    keepPhotos(list);
    -    return list;
    -}
    -
    - -

    In the new activity, in onCreate(), all you have to do to -get your object back is to call {@link android.app.Activity#getLastNonConfigurationInstance()}. -In Photostream, this method is invoked -and if the returned value is not null, the grid is loaded with the list of -photos from the previous activity:

    - -
    private void loadPhotos() {
    -    final Object data = getLastNonConfigurationInstance();
    -    
    -    // The activity is starting for the first time, load the photos from Flickr
    -    if (data == null) {
    -        mTask = new GetPhotoListTask().execute(mCurrentPage);
    -    } else {
    -        // The activity was destroyed/created automatically, populate the grid
    -        // of photos with the images loaded by the previous activity
    -        final LoadedPhoto[] photos = (LoadedPhoto[]) data;
    -        for (LoadedPhoto photo : photos) {
    -            addPhoto(photo);
    -        }
    -    }
    -}
    -
    - -

    Be very careful with the object you pass through -onRetainNonConfigurationChange(), though. If the object you -pass is for some reason tied to the Activity/Context, you will leak -all the views and resources of the activity. This means you should -never pass a View, a Drawable, an Adapter, etc. Photostream for -instance extracts the bitmaps from the drawables and pass the bitmaps -only, not the drawables. Finally, remember that -onRetainNonConfigurationChange() should be used only to retain -data that is expensive to load. Otherwise, keep it simple and let Android -do everything.

    - -

    Also read the guide to Handling Runtime -Changes.

    diff --git a/docs/html/resources/articles/future-proofing.jd b/docs/html/resources/articles/future-proofing.jd deleted file mode 100644 index b8aeedf1794a..000000000000 --- a/docs/html/resources/articles/future-proofing.jd +++ /dev/null @@ -1,91 +0,0 @@ -page.title=Future-Proofing Your Apps -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    It's important to implement your application so that it will not break as new -versions of the Android platform are loaded onto the users device. The list -below is based on our observations of five ways that we've seen bad apps fail. -You can think of these as "anti-patterns" (that is, techniques to avoid) for -Android development.

    - -

    If your application uses any of the dubious techniques below, break out -your IDE and duct tape, spackle, and patch up the app.

    - -

    Technique to Avoid, #1: Using Internal APIs

    - -

    Even -though we've always strongly advised against doing so, some developers -have chosen to use unsupported or internal APIs. For instance, many -developers are using the internal brightness control and bluetooth -toggle APIs that were present in 1.0 and 1.1. A bug -- which was -fixed in Android 1.5 -- allowed apps to use those APIs without -requesting permission. As a result, apps that used those APIs broke -on 1.5. If you've used internal APIs in your apps, you need to update -your apps to stop doing so.

    - -

    Technique to Avoid, #2: Directly Manipulating Settings

    - -

    Strictly speaking this one isn't evil, since this is a change in -behavior that we made to Android itself. But we made it because some -developers were doing naughty things: a number of apps were changing -system settings silently without even notifying the user. For instance, -some apps turn on GPS without asking the user, and others might turn on -data roaming.

    - -

    As a result, applications can no longer directly -manipulate the values of certain system Settings, even if they -previously had permission to do so. For instance, apps can no longer -directly turn on or off GPS. These apps won't crash, but the APIs in -question now have no effect, and do nothing. Instead, apps will need to -issue an Intent to launch the appropriate Settings configuration -screen, so that the user can change these settings manually. For -details, see the android.provider.Settings.Secure class, which you can -find in the 1.5_pre SDK documentation (and later). Note that only -Settings that were moved to the Settings.Secure class are affected. -Other, less sensitive, settings will continue to have the same behavior -as in Android 1.1.

    - -

    Technique to Avoid, #3: Going Overboard with Layouts

    - -

    Due to changes in the View rendering infrastructure, unreasonably deep -(more than 10 or so) or broad (more than 30 total) View hierarchies in -layouts are now likely to cause crashes. This was always a risk for -excessively complex layouts, but you can think of Android 1.5 as being -better than 1.1 at exposing this problem. Most developers won't need to -worry about this, but if your app has very complicated layouts, you'll -need to put it on a diet. You can simplify your layouts using the more -advanced layout classes like FrameLayout and TableLayout.

    - -

    Technique to Avoid, #4: Bad Hardware Assumptions

    - -

    Android 1.5 includes support for soft keyboards, and there will soon be many -devices that run Android but do not have physical keyboards. If your -application assumes the presence of a physical keyboard (such as if you -have created a custom View that sinks keypress events) you should make -sure it degrades gracefully on devices that only have soft keyboards. -For more information on this, keep on eye on this blog as we'll be -posting more detailed information about handling the new soft keyboards.

    - -

    Technique to Avoid, #5: Incautious Rotations

    - -

    Devices running Android 1.5 and later can automatically rotate the screen, -depending on how the user orients the device. Some 1.5 devices will do -this by default, and on all others it can be turned on by the user. -This can sometimes result in unpredictable behavior from applications -that do their own reorientations (whether using the accelerometer, or -something else.) This often happens when applications assume that the -screen can only rotate if the physical keyboard is exposed; if the -device lacks a physical keyboard, these apps do not expect to be -reoriented, which is a coding error. Developers should be sure that -their applications can gracefully handle being reoriented at any time.

    - -

    Also, apps that use the accelerometer directly to reorient themselves -sometimes compete with the system doing the same thing, with odd -results. And finally, some apps that use the accelerometer to detect -things like shaking motions and that don't lock their orientation to -portrait or landscape, often end up flipping back and forth between -orientations. This can be irritating to the user. (You can lock your -app's orientation to portrait or landscape using the -android:screenOrientation attribute in the manifest file.)

    - diff --git a/docs/html/resources/articles/gestures.jd b/docs/html/resources/articles/gestures.jd deleted file mode 100644 index 5b8d76068842..000000000000 --- a/docs/html/resources/articles/gestures.jd +++ /dev/null @@ -1,213 +0,0 @@ -page.title=Gestures -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Touch screens are a great way to interact with applications on -mobile devices. With a touch screen, users can easily tap, drag, fling, -or slide to quickly perform actions in their favorite applications. -For app developers. the Android framework makes it's easy to -recognize simple actions, like a swipe, but it has been more -difficult to handle complicated gestures, sometimes requiring -developers to write a lot of code.

    - -

    That's why we introduced a new gestures API in Android 1.6. This API, located -in the new package {@link android.gesture}, lets you store, load, draw, and -recognize gestures. This article will show you how you can use the -android.gesture API in your applications. Before going any further, -you should download the source code -of the examples.

    - -

    Creating a gestures library

    - -

    Android 1.6 and higher SDK platforms include a new application pre-installed -on the emulator, called Gestures Builder. You can use this application to create -a set of pre-defined gestures for your own application. It also serves as an -example of how to let the user define his own gestures in your applications. You -can find the source code of Gestures Builders in the samples directory of each -SDK platform. In our example we will use Gestures Builder to generate a set of -gestures for us (make sure to create an AVD with an SD card image to use -Gestures Builder.) The screenshot below shows what the application looks like -after adding a few gestures:

    - - - -

    As you can see, a gesture is always associated with a name. That name is very -important because it identifies each gesture within your application. The names -do not have to be unique. Actually it can be very useful to have several -gestures with the same name to increase the precision of the recognition. Every -time you add or edit a gesture in the Gestures Builder, a file is generated on -the emulator's SD card, /sdcard/gestures. This file contains the -description of all the gestures, and you will need to package it inside your -application inside the resources directory, in -/res/raw.

    - -

    Loading the gestures library

    - -

    Now that you have a set of pre-defined gestures, you must load it inside your -application. This can be achieved in several ways but the easiest is to use the -GestureLibraries class:

    - -
    mLibrary = GestureLibraries.fromRawResource(this, R.raw.spells);
    -if (!mLibrary.load()) {
    -    finish();
    -}
    - -

    In this example, the gesture library is loaded from the file -/res/raw/spells. You can easily load libraries from other sources, -like the SD card, which is very important if you want your application to be -able to save the library; a library loaded from a raw resource is read-only and -cannot be modified. The following diagram shows the structure of a library:

    - - - -

    Recognizing gestures

    - -

    To start recognizing gestures in your application, all you have to do -is add a GestureOverlayView to your XML layout:

    - -
    <android.gesture.GestureOverlayView
    -    android:id="@+id/gestures"
    -    android:layout_width="fill_parent" 
    -    android:layout_height="0dip"
    -    android:layout_weight="1.0" />
    - -

    Notice that the GestureOverlayView -is not part of the usual android.widget package. Therefore, you must -use its fully qualified name. A gesture overlay acts as a simple -drawing board on which the user can draw his gestures. You can tweak -several visual properties, like the color and the width of the stroke -used to draw gestures, and register various listeners to follow what -the user is doing. The most commonly used listener is -GestureOverlayView.OnGesturePerformedListener, -which fires whenever a user is done drawing a gesture:

    - -
    GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
    -gestures.addOnGesturePerformedListener(this);
    - -

    When the listener fires, you can ask the GestureLibrary -to try to recognize the gesture. In return, you will get a list of -Prediction instances, each with a name - the same name you entered in -the Gestures Builder - and a score. The list is sorted by descending -scores; the higher the score, the more likely the associated gesture is -the one the user intended to draw. The following code snippet -demonstrates how to retrieve the name of the first prediction:

    - -
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
    -    ArrayList<prediction> predictions = mLibrary.recognize(gesture);
    -
    -    // We want at least one prediction
    -    if (predictions.size() > 0) {
    -        Prediction prediction = predictions.get(0);
    -        // We want at least some confidence in the result
    -        if (prediction.score > 1.0) {
    -            // Show the spell
    -            Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show();
    -        }
    -    }
    -}
    - -

    In this example, the first prediction is taken into account only if it's -score is greater than 1.0. The threshold you use is entirely up to you -but know that scores lower than 1.0 are typically poor matches. And -this is all the code you need to create a simple application that can -recognize pre-defined gestures (see the source code of the project -GesturesDemo):

    - - - -

    Gestures overlay

    - -

    In the example above, the GestureOverlayView was used -as a normal view, embedded inside a LinearLayout. -However, as its name suggests, it can also be used as an overlay on top -of other views. This can be useful to recognize gestures in a game or -just anywhere in the UI of an application. In the second example, -called GesturesListDemo, we'll create an overlay on top of a list of -contacts. We start again in Gestures Builder to create a new set of -pre-defined gestures:

    - -

    - -

    And here is what the XML layout looks like:

    - -
    <android.gesture.GestureOverlayView
    -    xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:id="@+id/gestures"
    -    android:layout_width="fill_parent"
    -    android:layout_height="fill_parent"
    -    
    -    android:gestureStrokeType="multiple"
    -    android:eventsInterceptionEnabled="true"
    -    android:orientation="vertical">
    -
    -    <ListView
    -        android:id="@android:id/list"  
    -        android:layout_width="fill_parent" 
    -        android:layout_height="fill_parent"  />
    -
    -</android.gesture.GestureOverlayView>
    - -

    In this application, the gestures view is an overlay on top of a regular -ListView. The overlay also specifies a few properties that we did not -need before:

    - -
      -
    • gestureStrokeType: indicates -whether we want to recognize gestures made of a single stroke or -multiple strokes. Since one of our gestures is the "+" symbol, we need -multiple strokes
    • -
    • eventsInterceptionEnabled: when -set to true, this property tells the overlay to steal the events from -its children as soon as it knows the user is really drawing a gesture. -This is useful when there's a scrollable view under the overlay, to -avoid scrolling the underlying child as the user draws his gesture
    • -
    • orientation: -indicates the scroll orientation of the views underneath. In this case -the list scrolls vertically, which means that any horizontal gestures -(like action_delete) can immediately be recognized as a -gesture. Gestures that start with a vertical stroke must contain at -least one horizontal component to be recognized. In other words, a -simple vertical line cannot be recognized as a gesture since it would -conflict with the list's scrolling.
    • -
    - -

    The code used to load and set up the gestures library and overlay is exactly -the same as before. The only difference is that we now check the name of the -predictions to know what the user intended to do:

    - -
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
    -    ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
    -    if (predictions.size() > 0 && predictions.get(0).score > 1.0) {
    -        String action = predictions.get(0).name;
    -        if ("action_add".equals(action)) {
    -            Toast.makeText(this, "Adding a contact", Toast.LENGTH_SHORT).show();
    -        } else if ("action_delete".equals(action)) {
    -            Toast.makeText(this, "Removing a contact", Toast.LENGTH_SHORT).show();
    -        } else if ("action_refresh".equals(action)) {
    -            Toast.makeText(this, "Reloading contacts", Toast.LENGTH_SHORT).show();
    -        }
    -    }
    -}
    - -

    The user is now able to draw his gestures on top of the list without -interfering with the scrolling:

    - - - -

    The overlay even gives visual clues as to whether the gesture is considered -valid for recognition. In the case of a vertical overlay, for instance, -a single vertical stroke cannot be recognized as a gesture and is -therefore drawn with a translucent color:

    - - - -

    It's your turn

    - -

    Adding support for gestures in your application is easy and can be a valuable -addition. The gestures API does not even have to be used to recognize complex -shapes; it will work equally well to recognize simple swipes. We are very -excited by the possibilities the gestures API offers, and we're eager to see -what cool applications the community will create with it.

    diff --git a/docs/html/resources/articles/glsurfaceview.jd b/docs/html/resources/articles/glsurfaceview.jd deleted file mode 100644 index 45407a96dbe1..000000000000 --- a/docs/html/resources/articles/glsurfaceview.jd +++ /dev/null @@ -1,270 +0,0 @@ -page.title=Introducing GLSurfaceView -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -

    The {@link android android.opengl.GLSurfaceView} class makes it -easier for you to use OpenGL ES rendering in your applications by:

    - -
      -
    • Providing the glue code to connect OpenGL ES to the {@link -android.view.View} system.
    • -
    • Providing the glue code to make OpenGL ES work with the {@link -android.app.Activity} life-cycle.
    • -
    • Making it easy to choose an appropriate frame buffer pixel format.
    • -
    • Creating and managing a separate rendering thread, to enable smooth -animation.
    • -
    • Providing easy-to-use debugging tools for tracing OpenGL ES API calls and -checking for errors.
    • -
    - -

    GLSurfaceView is a good base for building an application that uses OpenGL ES -for part or all of its rendering. A 2D or 3D action game would be a good -candidate, as would a 2D or 3D data visualization application such as Google Maps StreetView.

    - -

    A simple GLSurfaceView application

    - -

    Here's the source code to the simplest possible OpenGL ES application:

    - -
    package com.example.android.apis.graphics;
    -
    -import javax.microedition.khronos.egl.EGLConfig;
    -import javax.microedition.khronos.opengles.GL10;
    -
    -import android.app.Activity;
    -import android.opengl.GLSurfaceView;
    -import android.os.Bundle;
    -
    -public class ClearActivity extends Activity {
    -    @Override
    -    protected void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        mGLView = new GLSurfaceView(this);
    -        mGLView.setRenderer(new ClearRenderer());
    -        setContentView(mGLView);
    -    }
    -
    -    @Override
    -    protected void onPause() {
    -        super.onPause();
    -        mGLView.onPause();
    -    }
    -
    -    @Override
    -    protected void onResume() {
    -        super.onResume();
    -        mGLView.onResume();
    -    }
    -
    -    private GLSurfaceView mGLView;
    -}
    -
    -class ClearRenderer implements GLSurfaceView.Renderer {
    -    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    -        // Do nothing special.
    -    }
    -
    -    public void onSurfaceChanged(GL10 gl, int w, int h) {
    -        gl.glViewport(0, 0, w, h);
    -    }
    -
    -    public void onDrawFrame(GL10 gl) {
    -        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    -    }
    -}
    - -

    This program doesn't do much: it clears the screen to black on every frame. -But it is a complete OpenGL application that correctly implements the -Android activity life-cycle. It pauses rendering when the activity is -paused, and resumes it when the activity is resumed. You could use this -application as the basis for non-interactive demonstration programs. -Just add more OpenGL calls to the ClearRenderer.onDrawFrame() method. -Notice that you don't even need to subclass the GLSurfaceView view.

    - -

    The {@link android.opengl.GLSurfaceView.Renderer} interface has three methods:

    - -
      -
    • The -onSurfaceCreated() method is called at the start of rendering, and -whenever the OpenGL ES drawing context has to be recreated. (The -drawing context is typically lost and recreated when the activity is -paused and resumed.) OnSurfaceCreated() is a good place to create -long-lived OpenGL resources such as textures.
    • -
    • The onSurfaceChanged() -method is called when the surface changes size. It's a good place to -set your OpenGL viewport. You may also want to set your camera here, if -it's a fixed camera that doesn't move around the scene.
    • -
    • The onDrawFrame() method is called every frame, and is -responsible for drawing the scene. You would typically start by calling -glClear to clear the framebuffer, followed by other OpenGL ES calls -to draw the current scene.
    • -
    - -

    How about user input?

    - -

    If you want an interactive application (such as a game), you will typically -subclass GLSurfaceView, because that's an easy way of obtaining -input events. Here's a slightly longer example showing how to do that:

    - -
    package com.google.android.ClearTest;
    -
    -import javax.microedition.khronos.egl.EGLConfig;
    -import javax.microedition.khronos.opengles.GL10;
    -
    -import android.app.Activity;
    -import android.content.Context;
    -import android.opengl.GLSurfaceView;
    -import android.os.Bundle;
    -import android.view.MotionEvent;
    -
    -public class ClearActivity extends Activity {
    -    @Override
    -    protected void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        mGLView = new ClearGLSurfaceView(this);
    -        setContentView(mGLView);
    -    }
    -
    -    @Override
    -    protected void onPause() {
    -        super.onPause();
    -        mGLView.onPause();
    -    }
    -
    -    @Override
    -    protected void onResume() {
    -        super.onResume();
    -        mGLView.onResume();
    -    }
    -
    -    private GLSurfaceView mGLView;
    -}
    -
    -class ClearGLSurfaceView extends GLSurfaceView {
    -    public ClearGLSurfaceView(Context context) {
    -        super(context);
    -        mRenderer = new ClearRenderer();
    -        setRenderer(mRenderer);
    -    }
    -
    -    public boolean onTouchEvent(final MotionEvent event) {
    -        queueEvent(new Runnable(){
    -            public void run() {
    -                mRenderer.setColor(event.getX() / getWidth(),
    -                        event.getY() / getHeight(), 1.0f);
    -            }});
    -            return true;
    -        }
    -
    -        ClearRenderer mRenderer;
    -}
    -
    -class ClearRenderer implements GLSurfaceView.Renderer {
    -    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    -        // Do nothing special.
    -    }
    -
    -    public void onSurfaceChanged(GL10 gl, int w, int h) {
    -        gl.glViewport(0, 0, w, h);
    -    }
    -
    -    public void onDrawFrame(GL10 gl) {
    -        gl.glClearColor(mRed, mGreen, mBlue, 1.0f);
    -        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    -    }
    -
    -    public void setColor(float r, float g, float b) {
    -        mRed = r;
    -        mGreen = g;
    -        mBlue = b;
    -    }
    -
    -    private float mRed;
    -    private float mGreen;
    -    private float mBlue;
    -}
    - -

    This application clears the screen for every frame. When you tap on the -screen, it sets the clear color based on the (x,y) coordinates of your touch -event. Note the use of queueEvent() in -ClearGLSurfaceView.onTouchEvent(). The queueEvent() -method is used to safely communicate between the UI thread and the rendering -thread. If you prefer, you can use some other Java cross-thread communication -technique, such as synchronized methods on the Renderer class -itself. However, queueing events is often the simplest way of dealing with -cross-thread communication.

    - -

    Other GLSurfaceView samples

    - -

    Tired -of just clearing the screen? You can find more interesting samples in -the API Demos sample included in the Android SDK. All the OpenGL ES samples have been -converted to use the GLSurfaceView view:

    - -
      -
    • GLSurfaceView - a spinning triangle
    • -
    • Kube - a cube puzzle demo
    • -
    • Translucent GLSurfaceView - shows how to display 3D graphics on a translucent background
    • -
    • Textured Triangle - shows how to draw a textured 3D triangle
    • -
    • Sprite Text - shows how to draw text into a texture and then composite it into a 3D scene
    • -
    • Touch Rotate - shows how to rotate a 3D object in response to user input.
    • -
    - -

    Choosing a surface

    - -

    GLSurfaceView -helps you choose the type of surface to render to. Different Android -devices support different types of surfaces, with no common subset. -This makes it tricky problem to choose the best available surface on -each device.

    - -

    By default, GLSurfaceView tries to find a surface that's as -close as possible to a 16-bit RGB frame buffer with a 16-bit depth -buffer. Depending upon your application's needs you may want to change -this behavior. For example, the Translucent GLSurfaceView sample needs -an Alpha channel in order to render translucent data. GLSurfaceView -provides an overloaded setEGLSurfaceChooser() method to give -you control over which surface type is chosen:

    - -
    -
    setEGLConfigChooser(boolean needDepth)
    -
    Choose a config that's closest to R5G6B5 with or without a 16-bit framebuffer
    -
    setEGLConfigChooser(int redSize, int greenSize,int blueSize, -int alphaSize,int depthSize, int stencilSize)
    -
    Choose the config with the fewest number of bits per pixel that has at least -as many bits-per-channel as specified in the constructor.
    -
    setEGLConfigChooser(EGLConfigChooser configChooser)
    -
    Allow total control over choosing a configuration. You pass in your own -implementation of EGLConfigChooser, which gets to inspect the -device's capabilities and choose a configuration.
    -
    - -

    Continuous rendering versus render-when-dirty

    - -

    Most 3D applications, such as games or simulations, are continuously -animated. But some 3D applications are more reactive: they wait passively until -the user does something, and then react to it. For those types of applications, -the default GLSurfaceView behavior of continuously redrawing the -screen is a waste of time. If you are developing a reactive application, you can -call GLSurfaceView.setRenderMode(RENDERMODE_WHEN_DIRTY), which -turns off the continuous animation. Then you call -GLSurfaceView.requestRender() whenever you want to re-render.

    - -

    Help With debugging

    - -

    GLSurfaceView has a handy built-in feature for debugging OpenGL ES -applications: the GLSurfaceView.setDebugFlags() method can be used -to enable logging and/or error checking your OpenGL ES calls. Call this method -in your GLSurfaceView's constructor, before calling -setRenderer():

    - -
    public ClearGLSurfaceView(Context context) {
    -    super(context);
    -    // Turn on error-checking and logging
    -    setDebugFlags(DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS);
    -    mRenderer = new ClearRenderer();
    -    setRenderer(mRenderer);
    -}
    \ No newline at end of file diff --git a/docs/html/resources/articles/images/File.png b/docs/html/resources/articles/images/File.png deleted file mode 100644 index bc5a2b827329..000000000000 Binary files a/docs/html/resources/articles/images/File.png and /dev/null differ diff --git a/docs/html/resources/articles/images/File_002.png b/docs/html/resources/articles/images/File_002.png deleted file mode 100644 index 39254b30a4d8..000000000000 Binary files a/docs/html/resources/articles/images/File_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/JFlubber.png b/docs/html/resources/articles/images/JFlubber.png deleted file mode 100644 index d95e32b8fbf2..000000000000 Binary files a/docs/html/resources/articles/images/JFlubber.png and /dev/null differ diff --git a/docs/html/resources/articles/images/WikiNotes.png b/docs/html/resources/articles/images/WikiNotes.png deleted file mode 100644 index d52c4fca7bd3..000000000000 Binary files a/docs/html/resources/articles/images/WikiNotes.png and /dev/null differ diff --git a/docs/html/resources/articles/images/all_drawables_changed.png b/docs/html/resources/articles/images/all_drawables_changed.png deleted file mode 100644 index 04ec4a2d7aa3..000000000000 Binary files a/docs/html/resources/articles/images/all_drawables_changed.png and /dev/null differ diff --git a/docs/html/resources/articles/images/android.png b/docs/html/resources/articles/images/android.png deleted file mode 100644 index 6dc88ccbd170..000000000000 Binary files a/docs/html/resources/articles/images/android.png and /dev/null differ diff --git a/docs/html/resources/articles/images/buttons.png b/docs/html/resources/articles/images/buttons.png deleted file mode 100644 index 8c220b9523cc..000000000000 Binary files a/docs/html/resources/articles/images/buttons.png and /dev/null differ diff --git a/docs/html/resources/articles/images/contacts-2.png b/docs/html/resources/articles/images/contacts-2.png deleted file mode 100644 index 02f28aaad211..000000000000 Binary files a/docs/html/resources/articles/images/contacts-2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/contacts.png b/docs/html/resources/articles/images/contacts.png deleted file mode 100644 index d8b067df99b1..000000000000 Binary files a/docs/html/resources/articles/images/contacts.png and /dev/null differ diff --git a/docs/html/resources/articles/images/correct_drawables.png b/docs/html/resources/articles/images/correct_drawables.png deleted file mode 100644 index 516309b683e8..000000000000 Binary files a/docs/html/resources/articles/images/correct_drawables.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ddms_allocation_tracker.png b/docs/html/resources/articles/images/ddms_allocation_tracker.png deleted file mode 100644 index b9fa0a1db807..000000000000 Binary files a/docs/html/resources/articles/images/ddms_allocation_tracker.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ddms_allocation_trackerl.png b/docs/html/resources/articles/images/ddms_allocation_trackerl.png deleted file mode 100644 index 5ac8d2a0eddc..000000000000 Binary files a/docs/html/resources/articles/images/ddms_allocation_trackerl.png and /dev/null differ diff --git a/docs/html/resources/articles/images/device.png b/docs/html/resources/articles/images/device.png deleted file mode 100644 index 186b960bd908..000000000000 Binary files a/docs/html/resources/articles/images/device.png and /dev/null differ diff --git a/docs/html/resources/articles/images/device_002.png b/docs/html/resources/articles/images/device_002.png deleted file mode 100644 index 4bc3b0c4f14b..000000000000 Binary files a/docs/html/resources/articles/images/device_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/gestures.png b/docs/html/resources/articles/images/gestures.png deleted file mode 100644 index fe8f7cdfe2f2..000000000000 Binary files a/docs/html/resources/articles/images/gestures.png and /dev/null differ diff --git a/docs/html/resources/articles/images/gestures_002.png b/docs/html/resources/articles/images/gestures_002.png deleted file mode 100644 index b20da98fcd22..000000000000 Binary files a/docs/html/resources/articles/images/gestures_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/gestures_003.png b/docs/html/resources/articles/images/gestures_003.png deleted file mode 100644 index a29593905f37..000000000000 Binary files a/docs/html/resources/articles/images/gestures_003.png and /dev/null differ diff --git a/docs/html/resources/articles/images/gestures_004.png b/docs/html/resources/articles/images/gestures_004.png deleted file mode 100644 index 3fe5fb179357..000000000000 Binary files a/docs/html/resources/articles/images/gestures_004.png and /dev/null differ diff --git a/docs/html/resources/articles/images/gestures_005.png b/docs/html/resources/articles/images/gestures_005.png deleted file mode 100644 index 3efc519d0326..000000000000 Binary files a/docs/html/resources/articles/images/gestures_005.png and /dev/null differ diff --git a/docs/html/resources/articles/images/gestures_006.png b/docs/html/resources/articles/images/gestures_006.png deleted file mode 100644 index 399c31d6b51f..000000000000 Binary files a/docs/html/resources/articles/images/gestures_006.png and /dev/null differ diff --git a/docs/html/resources/articles/images/grid.png b/docs/html/resources/articles/images/grid.png deleted file mode 100644 index 4713de5f564a..000000000000 Binary files a/docs/html/resources/articles/images/grid.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ime.png b/docs/html/resources/articles/images/ime.png deleted file mode 100644 index 57f6df1c3a97..000000000000 Binary files a/docs/html/resources/articles/images/ime.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ime_002.png b/docs/html/resources/articles/images/ime_002.png deleted file mode 100644 index 3ec00b2f66d6..000000000000 Binary files a/docs/html/resources/articles/images/ime_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ime_003.png b/docs/html/resources/articles/images/ime_003.png deleted file mode 100644 index a3f57bb701f3..000000000000 Binary files a/docs/html/resources/articles/images/ime_003.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ime_004.png b/docs/html/resources/articles/images/ime_004.png deleted file mode 100644 index efeddf05b0fa..000000000000 Binary files a/docs/html/resources/articles/images/ime_004.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ime_005.png b/docs/html/resources/articles/images/ime_005.png deleted file mode 100644 index a7394e067cf9..000000000000 Binary files a/docs/html/resources/articles/images/ime_005.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ime_006.png b/docs/html/resources/articles/images/ime_006.png deleted file mode 100644 index 0b55c7962dbf..000000000000 Binary files a/docs/html/resources/articles/images/ime_006.png and /dev/null differ diff --git a/docs/html/resources/articles/images/layouts_comparison_small.png b/docs/html/resources/articles/images/layouts_comparison_small.png deleted file mode 100644 index 0ba4cb8cf9cd..000000000000 Binary files a/docs/html/resources/articles/images/layouts_comparison_small.png and /dev/null differ diff --git a/docs/html/resources/articles/images/list01.png b/docs/html/resources/articles/images/list01.png deleted file mode 100644 index e1b7fa8255ef..000000000000 Binary files a/docs/html/resources/articles/images/list01.png and /dev/null differ diff --git a/docs/html/resources/articles/images/list02.png b/docs/html/resources/articles/images/list02.png deleted file mode 100644 index 7f72a3f28994..000000000000 Binary files a/docs/html/resources/articles/images/list02.png and /dev/null differ diff --git a/docs/html/resources/articles/images/list_fade_1.png b/docs/html/resources/articles/images/list_fade_1.png deleted file mode 100644 index 43013d6b3997..000000000000 Binary files a/docs/html/resources/articles/images/list_fade_1.png and /dev/null differ diff --git a/docs/html/resources/articles/images/list_fade_2.png b/docs/html/resources/articles/images/list_fade_2.png deleted file mode 100644 index 160d3ffe5b3e..000000000000 Binary files a/docs/html/resources/articles/images/list_fade_2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/list_fade_3.png b/docs/html/resources/articles/images/list_fade_3.png deleted file mode 100644 index 70dca6439c97..000000000000 Binary files a/docs/html/resources/articles/images/list_fade_3.png and /dev/null differ diff --git a/docs/html/resources/articles/images/list_fade_4.png b/docs/html/resources/articles/images/list_fade_4.png deleted file mode 100644 index 7619fcaeb403..000000000000 Binary files a/docs/html/resources/articles/images/list_fade_4.png and /dev/null differ diff --git a/docs/html/resources/articles/images/live_wallpapers_small.png b/docs/html/resources/articles/images/live_wallpapers_small.png deleted file mode 100644 index 3b49b2427005..000000000000 Binary files a/docs/html/resources/articles/images/live_wallpapers_small.png and /dev/null differ diff --git a/docs/html/resources/articles/images/merge1.jpg b/docs/html/resources/articles/images/merge1.jpg deleted file mode 100644 index 114eed697bf5..000000000000 Binary files a/docs/html/resources/articles/images/merge1.jpg and /dev/null differ diff --git a/docs/html/resources/articles/images/merge2.png b/docs/html/resources/articles/images/merge2.png deleted file mode 100644 index b4a8d4c26639..000000000000 Binary files a/docs/html/resources/articles/images/merge2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/merge3.png b/docs/html/resources/articles/images/merge3.png deleted file mode 100644 index 61ed983dd506..000000000000 Binary files a/docs/html/resources/articles/images/merge3.png and /dev/null differ diff --git a/docs/html/resources/articles/images/merge4.jpg b/docs/html/resources/articles/images/merge4.jpg deleted file mode 100644 index 17b6c20a2032..000000000000 Binary files a/docs/html/resources/articles/images/merge4.jpg and /dev/null differ diff --git a/docs/html/resources/articles/images/merge5.png b/docs/html/resources/articles/images/merge5.png deleted file mode 100644 index 289f47e0f3eb..000000000000 Binary files a/docs/html/resources/articles/images/merge5.png and /dev/null differ diff --git a/docs/html/resources/articles/images/mutated_states.png b/docs/html/resources/articles/images/mutated_states.png deleted file mode 100644 index 50518b639136..000000000000 Binary files a/docs/html/resources/articles/images/mutated_states.png and /dev/null differ diff --git a/docs/html/resources/articles/images/on-screen-inputs.png b/docs/html/resources/articles/images/on-screen-inputs.png deleted file mode 100644 index b8b3cf794f36..000000000000 Binary files a/docs/html/resources/articles/images/on-screen-inputs.png and /dev/null differ diff --git a/docs/html/resources/articles/images/on-screen-inputs_002.png b/docs/html/resources/articles/images/on-screen-inputs_002.png deleted file mode 100644 index a5d21c75f634..000000000000 Binary files a/docs/html/resources/articles/images/on-screen-inputs_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/on-screen-inputs_003.png b/docs/html/resources/articles/images/on-screen-inputs_003.png deleted file mode 100644 index 81ee257b6c10..000000000000 Binary files a/docs/html/resources/articles/images/on-screen-inputs_003.png and /dev/null differ diff --git a/docs/html/resources/articles/images/on-screen-inputs_004.png b/docs/html/resources/articles/images/on-screen-inputs_004.png deleted file mode 100644 index 651b72a10ba2..000000000000 Binary files a/docs/html/resources/articles/images/on-screen-inputs_004.png and /dev/null differ diff --git a/docs/html/resources/articles/images/on-screen-inputs_005.png b/docs/html/resources/articles/images/on-screen-inputs_005.png deleted file mode 100644 index 75185ff1bbf0..000000000000 Binary files a/docs/html/resources/articles/images/on-screen-inputs_005.png and /dev/null differ diff --git a/docs/html/resources/articles/images/on-screen-inputs_006.png b/docs/html/resources/articles/images/on-screen-inputs_006.png deleted file mode 100644 index b653d753dc26..000000000000 Binary files a/docs/html/resources/articles/images/on-screen-inputs_006.png and /dev/null differ diff --git a/docs/html/resources/articles/images/photostream_landscape.png b/docs/html/resources/articles/images/photostream_landscape.png deleted file mode 100644 index ad4a0c5a0fda..000000000000 Binary files a/docs/html/resources/articles/images/photostream_landscape.png and /dev/null differ diff --git a/docs/html/resources/articles/images/photostream_portrait.png b/docs/html/resources/articles/images/photostream_portrait.png deleted file mode 100644 index 3794f6374439..000000000000 Binary files a/docs/html/resources/articles/images/photostream_portrait.png and /dev/null differ diff --git a/docs/html/resources/articles/images/qsb.png b/docs/html/resources/articles/images/qsb.png deleted file mode 100644 index 4e40af14a53b..000000000000 Binary files a/docs/html/resources/articles/images/qsb.png and /dev/null differ diff --git a/docs/html/resources/articles/images/qsb_002.png b/docs/html/resources/articles/images/qsb_002.png deleted file mode 100644 index 8c2f77232270..000000000000 Binary files a/docs/html/resources/articles/images/qsb_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/qsb_003.png b/docs/html/resources/articles/images/qsb_003.png deleted file mode 100644 index 069b6cd31d1e..000000000000 Binary files a/docs/html/resources/articles/images/qsb_003.png and /dev/null differ diff --git a/docs/html/resources/articles/images/relativelayout_1.png b/docs/html/resources/articles/images/relativelayout_1.png deleted file mode 100644 index 3360ad85366d..000000000000 Binary files a/docs/html/resources/articles/images/relativelayout_1.png and /dev/null differ diff --git a/docs/html/resources/articles/images/relativelayout_2.png b/docs/html/resources/articles/images/relativelayout_2.png deleted file mode 100644 index 8e71bb27f202..000000000000 Binary files a/docs/html/resources/articles/images/relativelayout_2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/relativelayout_3.png b/docs/html/resources/articles/images/relativelayout_3.png deleted file mode 100644 index 16a9767890d1..000000000000 Binary files a/docs/html/resources/articles/images/relativelayout_3.png and /dev/null differ diff --git a/docs/html/resources/articles/images/relativelayout_wire_1.png b/docs/html/resources/articles/images/relativelayout_wire_1.png deleted file mode 100644 index 9cb241df6d45..000000000000 Binary files a/docs/html/resources/articles/images/relativelayout_wire_1.png and /dev/null differ diff --git a/docs/html/resources/articles/images/relativelayout_wire_2.png b/docs/html/resources/articles/images/relativelayout_wire_2.png deleted file mode 100644 index 4243812e366d..000000000000 Binary files a/docs/html/resources/articles/images/relativelayout_wire_2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/relativelayout_wire_3.png b/docs/html/resources/articles/images/relativelayout_wire_3.png deleted file mode 100644 index 04ce1cefb2bd..000000000000 Binary files a/docs/html/resources/articles/images/relativelayout_wire_3.png and /dev/null differ diff --git a/docs/html/resources/articles/images/search01.png b/docs/html/resources/articles/images/search01.png deleted file mode 100644 index 4160a76528d2..000000000000 Binary files a/docs/html/resources/articles/images/search01.png and /dev/null differ diff --git a/docs/html/resources/articles/images/search02.png b/docs/html/resources/articles/images/search02.png deleted file mode 100644 index 63000186b730..000000000000 Binary files a/docs/html/resources/articles/images/search02.png and /dev/null differ diff --git a/docs/html/resources/articles/images/service-api-changes-starting-with_runningservices.png b/docs/html/resources/articles/images/service-api-changes-starting-with_runningservices.png deleted file mode 100644 index e159fff70efb..000000000000 Binary files a/docs/html/resources/articles/images/service-api-changes-starting-with_runningservices.png and /dev/null differ diff --git a/docs/html/resources/articles/images/service-api-changes-starting-with_stopservice.png b/docs/html/resources/articles/images/service-api-changes-starting-with_stopservice.png deleted file mode 100644 index cc8f0a2a5fd6..000000000000 Binary files a/docs/html/resources/articles/images/service-api-changes-starting-with_stopservice.png and /dev/null differ diff --git a/docs/html/resources/articles/images/shared_states.png b/docs/html/resources/articles/images/shared_states.png deleted file mode 100644 index 81bec0958f81..000000000000 Binary files a/docs/html/resources/articles/images/shared_states.png and /dev/null differ diff --git a/docs/html/resources/articles/images/shelves2.png b/docs/html/resources/articles/images/shelves2.png deleted file mode 100644 index 2de239fb413b..000000000000 Binary files a/docs/html/resources/articles/images/shelves2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/speech-input.png b/docs/html/resources/articles/images/speech-input.png deleted file mode 100644 index 78fbc98c4603..000000000000 Binary files a/docs/html/resources/articles/images/speech-input.png and /dev/null differ diff --git a/docs/html/resources/articles/images/text_field.png b/docs/html/resources/articles/images/text_field.png deleted file mode 100644 index b9dedecd342a..000000000000 Binary files a/docs/html/resources/articles/images/text_field.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ui-1.6.png b/docs/html/resources/articles/images/ui-1.6.png deleted file mode 100644 index bc5a2b827329..000000000000 Binary files a/docs/html/resources/articles/images/ui-1.6.png and /dev/null differ diff --git a/docs/html/resources/articles/images/ui-1.6_002.png b/docs/html/resources/articles/images/ui-1.6_002.png deleted file mode 100644 index 39254b30a4d8..000000000000 Binary files a/docs/html/resources/articles/images/ui-1.6_002.png and /dev/null differ diff --git a/docs/html/resources/articles/images/viewstub1.png b/docs/html/resources/articles/images/viewstub1.png deleted file mode 100644 index 2de239fb413b..000000000000 Binary files a/docs/html/resources/articles/images/viewstub1.png and /dev/null differ diff --git a/docs/html/resources/articles/images/viewstub2.png b/docs/html/resources/articles/images/viewstub2.png deleted file mode 100644 index 6e6feb978d87..000000000000 Binary files a/docs/html/resources/articles/images/viewstub2.png and /dev/null differ diff --git a/docs/html/resources/articles/images/viewstub3.png b/docs/html/resources/articles/images/viewstub3.png deleted file mode 100644 index 5e793e664e62..000000000000 Binary files a/docs/html/resources/articles/images/viewstub3.png and /dev/null differ diff --git a/docs/html/resources/articles/images/viewstub4.png b/docs/html/resources/articles/images/viewstub4.png deleted file mode 100644 index cffb9c63761a..000000000000 Binary files a/docs/html/resources/articles/images/viewstub4.png and /dev/null differ diff --git a/docs/html/resources/articles/images/webview.png b/docs/html/resources/articles/images/webview.png deleted file mode 100644 index 92472af527d4..000000000000 Binary files a/docs/html/resources/articles/images/webview.png and /dev/null differ diff --git a/docs/html/resources/articles/images/window_background.png b/docs/html/resources/articles/images/window_background.png deleted file mode 100644 index 58f4f7edd148..000000000000 Binary files a/docs/html/resources/articles/images/window_background.png and /dev/null differ diff --git a/docs/html/resources/articles/images/window_background_null.png b/docs/html/resources/articles/images/window_background_null.png deleted file mode 100644 index 83f7b45d0053..000000000000 Binary files a/docs/html/resources/articles/images/window_background_null.png and /dev/null differ diff --git a/docs/html/resources/articles/images/window_background_root.png b/docs/html/resources/articles/images/window_background_root.png deleted file mode 100644 index 95a47c0b60af..000000000000 Binary files a/docs/html/resources/articles/images/window_background_root.png and /dev/null differ diff --git a/docs/html/resources/articles/index.jd b/docs/html/resources/articles/index.jd deleted file mode 100644 index 2947e4a2649a..000000000000 --- a/docs/html/resources/articles/index.jd +++ /dev/null @@ -1,168 +0,0 @@ -page.title=Technical Articles -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -
    -
    Avoiding Memory Leaks
    -
    Mobile devices often have limited memory, and memory leaks can cause your application to waste this valuable resource without your knowledge. This article provides tips to help you avoid common causes of memory leaks on the Android platform.
    -
    - -
    -
    Backward Compatibility
    -
    The Android platform strives to ensure backwards compatibility. However, sometimes you want to use new features which aren't supported on older platforms. This article discusses strategies for selectively using these features based on availability, allowing you to keep your applications portable across a wide range of devices.
    -
    - -
    -
    Can I Use this Intent?
    -
    Android offers a very powerful and yet easy-to-use message type called an intent. You can use intents to turn applications into high-level libraries and make code modular and reusable. While it is nice to be able to make use of a loosely coupled API, there is no guarantee that the intent you send will be received by another application. This article describes a technique you can use to find out whether the system contains any application capable of responding to the intent you want to use.
    -
    - -
    -
    Creating an Input Method
    -
    Input Method Editors (IMEs) provide the mechanism for entering text into text fields and other Views. Android devices come bundled with at least one IME, but users can install additional IMEs. This article covers the basics of developing an IME for the Android platform.
    -
    - -
    -
    Drawable Mutations
    -
    Drawables are pluggable drawing containers that allow applications to display graphics. This article explains some common pitfalls when trying to modify the properties of multiple Drawables.
    -
    - -
    -
    Faster Screen Orientation Change
    -
    When an Android device changes its orientation, the default behavior is to automatically restart the current activity with a new configuration. However, this can become a bottleneck in applications that access a large amount of external data. This article discusses how to gracefully handle this situation without resorting to manually processing configuration changes.
    -
    - -
    -
    Future-Proofing Your Apps
    -
    A collection of common sense advice to help you ensure that your applications don't break when new versions of the Android platform are released.
    -
    - -
    -
    Gestures
    -
    Touch screens allow users to perform gestures, such as tapping, dragging, flinging, or sliding, to perform various actions. The gestures API enables your application to recognize even complicated gestures with ease. This article explains how to integrate this API into an application.
    -
    - -
    -
    Introducing GLSurfaceView
    -
    This article provides an overview of GLSurfaceView, a class that makes it easy to implement 2D or 3D OpenGL rendering inside of an Android application.
    -
    -
    -
    - - Using the Spell Checker Framework -
    -
    - This article describes how to use the Spell Checker Framework to check spelling in - various ways in your application. -
    -
    -
    -
    Layout Tricks: Creating Reusable UI Components
    -
    Learn how to combine multiple standard UI widgets into a single high-level component, which can be reused throughout your application.
    -
    - -
    -
    Layout Tricks: Creating Efficient Layouts
    -
    Learn how to optimize application layouts as this article walks you through converting a LinearLayout into a RelativeLayout, and analyzes the resulting implications on performance.
    -
    - -
    -
    Layout Tricks: Using ViewStubs
    -
    Learn about using ViewStubs inside an application's layout in order to inflate rarely used UI elements, without the performance implications which would otherwise be caused by using the <include> tag.
    -
    - -
    -
    Layout Tricks: Merging Layouts
    -
    Learn how to use the <merge> tag in your XML layouts in order to avoid unnecessary levels of hierarchy within an application's view tree.
    -
    - -
    -
    ListView Backgrounds: An Optimization
    -
    ListViews are very popular widgets within the Android framework. This article describes some of the optimizations used by the ListView widget, and how to avoid some common issues that this causes when trying to use a custom background.
    -
    - -
    -
    Live Folders
    -
    Live Folders allow users to display any source of data on their home screen without launching an application. This article discusses how to export an application's data in a format suitable for display inside of a live folder.
    -
    - -
    -
    Live Wallpapers
    -
    Live wallpapers are richer, animated, interactive backgrounds that users can display in their home screens. Learn how to create a live wallpaper and bundle it in an application that users can install on their devices.
    -
    - -
    -
    Onscreen Input Methods
    -
    The Input Method Framework (IMF) allows users to take advantage of on-screen input methods, such as software keyboards. This article provides an overview of Input Method Editors (IMEs) and how applications interact with them.
    -
    - -
    -
    Painless Threading
    -
    This article discusses the threading model used by Android applications and how applications can ensure best UI performance by spawning worker threads to handle long-running operations, rather than handling them in the main thread. The article also explains the API that your application can use to interact with Android UI toolkit components running on the main thread and spawn managed worker threads.
    -
    - -
    -
    Quick Search Box
    -
    Quick Search Box (QSB) is a powerful, system-wide search framework. QSB makes it possible for users to quickly and easily find what they're looking for, both on their devices and on the web. This article discusses how to work with the QSB framework to add new search results for an installed application.
    -
    - -
    -
    Touch Mode
    -
    This article explains the touch mode, one of the most important principles of Android's UI toolkit. Whenever a user interacts with a device's touch screen, the system enters touch mode. While simple in concept, there are important implications touch mode that are often overlooked.
    -
    - -
    -
    Tracking Memory Allocations
    -
    This article discusses how to use the Allocation Tracker tool to observe memory allocations and avoid performance problems that would otherwise be caused by ignoring the effect of Dalvik's garbage collector.
    -
    - -
    -
    UI Framework Changes in Android 1.5
    -
    Explore the UI changes that were introduced in Android 1.5, compared with the UI provided in Android 1.0 and 1.1.
    -
    - -
    -
    UI Framework Changes in Android 1.6
    -
    Explore the UI changes that were introduced in Android 1.6, compared with the UI provided in Android 1.5. In particular, this article discusses changes to RelativeLayouts and click listeners.
    -
    - -
    -
    Updating the UI from a Timer
    -
    Learn about how to use Handlers as a more efficient replacement for java.util.Timer on the Android platform.
    -
    - -
    -
    Using Text-to-Speech
    -
    The text-to-speech API lets your application "speak" to users, in any of several languages. This article provides an overview of the TTS API and how you use to add speech capabilities to your application.
    -
    - -
    -
    Using the Contacts API
    -
    This article discusses the improved Contacts API introduced in Android 2.0 and how to use it to manage and integrate contacts from multiple accounts and data sources. The article also discusses techniques for using the new API on devices that support it, while maintaining backward compatibility with the old API on other devices.
    -
    - -
    -
    Using WebViews
    -
    WebViews allow an application to dynamically display HTML and execute JavaScript, without relinquishing control to a separate browser application. This article introduces the WebView classes and provides a sample application that demonstrates its use.
    -
    - -
    -
    WikiNotes: Linkify your Text!
    -
    This article introduces WikiNotes for Android, part of the Apps for Android project. It covers the use of Linkify to turn ordinary text views into richer, link-oriented content that causes Android intents to fire when a link is selected.
    -
    - -
    -
    WikiNotes: Routing Intents
    -
    This article illustrates how an application, in this case the WikiNotes sample app, can use intents to route various types of linked text to the application that handles that type of data. For example, an app can use intents to route a linked telephone number to a dialer app and a web URL to a browser.
    -
    - -
    -
    Window Backgrounds & UI Speed
    -
    Some Android applications need to squeeze every bit of performance out of the UI toolkit and there are many ways to do so. In this article, you will discover how to speed up the drawing and the perceived startup time of your activities. Both of these techniques rely on a single feature, the window's background drawable.
    -
    - -
    -
    Zipalign: an Easy Optimization
    -
    The Android SDK includes a tool called zipalign that optimizes the way an application is packaged. Running zipalign against your application enables Android to interact with it more efficiently at run time and thus has the potential to make it and the overall system run faster. This article provides a high-level overview of the zipalign tool and its use.
    -
    diff --git a/docs/html/resources/articles/layout-tricks-efficiency.jd b/docs/html/resources/articles/layout-tricks-efficiency.jd deleted file mode 100644 index 00b4147e84cb..000000000000 --- a/docs/html/resources/articles/layout-tricks-efficiency.jd +++ /dev/null @@ -1,179 +0,0 @@ -page.title=Layout Tricks: Creating Efficient Layouts -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    The Android UI toolkit offers several layout managers that are -rather easy to use and, most of the time, you only need the basic -features of these layout managers to implement a user interface.

    - -

    Sticking to the basic features is unfortunately not the most efficient -way to create user interfaces. A common example is the abuse of -{@link android.widget.LinearLayout}, which leads to a proliferation of -views in the view hierarchy. Every view — or worse, every layout -manager — that you add to your application comes at a cost: -initialization, layout and drawing become slower. The layout pass can be -especially expensive when you nest several LinearLayout -that use the {@link android.R.attr#layout_weight weight} -parameter, which requires the child to be measured twice.

    - -

    Let's consider a very simple and common example of a layout: a list item -with an icon on the left, a title at the top and an optional description -underneath the title. Here is what such an item looks like:

    - -
    Simple list item
    - -

    To clearly understand how the views, one {@link android.widget.ImageView} and -two {@link android.widget.TextView}, are positioned with respect to each other, -here is the wireframe of the layout as captured by HierarchyViewer:

    - -
    Wireframe of the simple list item
    - -

    Implementing this layout is straightforward with LinearLayout. -The item itself is a horizontal LinearLayout with an -ImageView and a vertical LinearLayout, which contains -the two TextView. Here's the source code of this layout:

    - -
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:layout_width="fill_parent"
    -    android:layout_height="?android:attr/listPreferredItemHeight"
    -    
    -    android:padding="6dip">
    -    
    -    <ImageView
    -        android:id="@+id/icon"
    -        
    -        android:layout_width="wrap_content"
    -        android:layout_height="fill_parent"
    -        android:layout_marginRight="6dip"
    -        
    -        android:src="@drawable/icon" />
    -
    -    <LinearLayout
    -        android:orientation="vertical"
    -    
    -        android:layout_width="0dip"
    -        android:layout_weight="1"
    -        android:layout_height="fill_parent">
    -
    -        <TextView
    -            android:layout_width="fill_parent"
    -            android:layout_height="0dip"
    -            android:layout_weight="1"
    -                    
    -            android:gravity="center_vertical"
    -            android:text="My Application" />
    -            
    -        <TextView  
    -            android:layout_width="fill_parent"
    -            android:layout_height="0dip"
    -            android:layout_weight="1" 
    -            
    -            android:singleLine="true"
    -            android:ellipsize="marquee"
    -            android:text="Simple application that shows how to use RelativeLayout" />
    -            
    -    </LinearLayout>
    -
    -</LinearLayout>
    - -

    This layout works but can be wasteful if you instantiate it for every list -item of a {@link android.widget.ListView}. The same layout can be rewritten -using a single {@link android.widget.RelativeLayout}, thus saving one view, and -even better one level in view hierarchy, per list item. The implementation of -the layout with a RelativeLayout remains simple:

    - -
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:layout_width="fill_parent"
    -    android:layout_height="?android:attr/listPreferredItemHeight"
    -    
    -    android:padding="6dip">
    -    
    -    <ImageView
    -        android:id="@+id/icon"
    -        
    -        android:layout_width="wrap_content"
    -        android:layout_height="fill_parent"
    -        
    -        android:layout_alignParentTop="true"
    -        android:layout_alignParentBottom="true"
    -        android:layout_marginRight="6dip"
    -        
    -        android:src="@drawable/icon" />
    -
    -    <TextView  
    -        android:id="@+id/secondLine"
    -
    -        android:layout_width="fill_parent"
    -        android:layout_height="26dip" 
    -        
    -        android:layout_toRightOf="@id/icon"
    -        android:layout_alignParentBottom="true"
    -        android:layout_alignParentRight="true"
    -        
    -        android:singleLine="true"
    -        android:ellipsize="marquee"
    -        android:text="Simple application that shows how to use RelativeLayout" />
    -
    -    <TextView
    -        android:layout_width="fill_parent"
    -        android:layout_height="wrap_content"
    -        
    -        android:layout_toRightOf="@id/icon"
    -        android:layout_alignParentRight="true"
    -        android:layout_alignParentTop="true"
    -        android:layout_above="@id/secondLine"
    -        android:layout_alignWithParentIfMissing="true"
    -                
    -        android:gravity="center_vertical"
    -        android:text="My Application" />
    -
    -</RelativeLayout>
    - -

    This new implementation behaves exactly the same way as the previous -implementation, except in one case. The list item we want to display has two -lines of text: the title and an optional description. When a -description is not available for a given list item, the application would simply -set the visibility of the second TextView to -{@link android.view.View#GONE}. This works perfectly with the LinearLayout -implementation but not with the RelativeLayout version:

    - -
    RelativeLayout and description GONE
    -
    RelativeLayout and description GONE
    - -

    In a RelativeLayout, views are aligned with their parent, with the -RelativeLayout itself, or with other views. For instance, we declared that -the description is aligned with the bottom of the RelativeLayout and -that the title is positioned above the description and anchored to the -parent's top. With the description GONE, RelativeLayout doesn't know -where to position the title's bottom edge. To solve this problem, you -can use a very special layout parameter called -{@link android.R.attr#layout_alignWithParentIfMissing}. -

    - -

    This boolean parameter simply tells RelativeLayout to use its own edges as -anchors when a constraint target is missing. For instance, if you position a -view to the right of a GONE view and set alignWithParentIfMissing -to true, RelativeLayout will instead anchor the view -to its left edge. In our case, using alignWithParentIfMissing will -cause RelativeLayout to align the title's bottom with its own -bottom. The result is the following:

    - -
    RelativeLayout, description GONE and alignWithParentIfMissing
    -
    RelativeLayout, description GONE and alignWithParentIfMissing
    - -

    The -behavior of our layout is now perfect, even when the description is -GONE. Even better, the hierarchy is simpler and because we are not -using LinearLayout's weights it's also more efficient. The difference -between the two implementations becomes obvious when comparing the view -hierarchies in HierarchyViewer:

    - -
    LinearLayout vs RelativeLayout
    - -

    Again, the difference will be much more important when you use such a layout -for every item in a ListView for instance. Hopefully this simple -example showed you that getting to know your layouts is the best way to -learn how to optimize your UI.

    diff --git a/docs/html/resources/articles/layout-tricks-merge.jd b/docs/html/resources/articles/layout-tricks-merge.jd deleted file mode 100644 index 0ca0317d99f4..000000000000 --- a/docs/html/resources/articles/layout-tricks-merge.jd +++ /dev/null @@ -1,202 +0,0 @@ -page.title=Layout Tricks: Merging Layouts -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    The articles showed you how to use the <include /> tag in XML layouts, to -reuse and share your layout code. This article explains the <merge /> tag and how -it complements the <include /> tag.

    - -

    The <merge /> tag was created for the purpose of -optimizing Android layouts by reducing the number of levels in view trees. It's -easier to understand the problem this tag solves by looking at an example. The -following XML layout declares a layout that shows an image with its title on top -of it. The structure is fairly simple; a {@link android.widget.FrameLayout} is -used to stack a {@link android.widget.TextView} on top of an -{@link android.widget.ImageView}:

    - -
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:layout_width="fill_parent"
    -    android:layout_height="fill_parent">
    -
    -    <ImageView  
    -        android:layout_width="fill_parent" 
    -        android:layout_height="fill_parent" 
    -    
    -        android:scaleType="center"
    -        android:src="@drawable/golden_gate" />
    -    
    -    <TextView
    -        android:layout_width="wrap_content" 
    -        android:layout_height="wrap_content" 
    -        android:layout_marginBottom="20dip"
    -        android:layout_gravity="center_horizontal|bottom"
    -
    -        android:padding="12dip"
    -        
    -        android:background="#AA000000"
    -        android:textColor="#ffffffff"
    -        
    -        android:text="Golden Gate" />
    -
    -</FrameLayout>
    - -

    This layout renders nicely and nothing seems wrong with it:

    - -
    A FrameLayout is used to overlay a title on top of an image
    - -

    Things get more interesting when you inspect the result with HierarchyViewer. -If you look closely at the resulting tree, you will notice that the -FrameLayout defined in our XML file (highlighted in blue below) is -the sole child of another FrameLayout:

    - -
    A layout with only one child of same dimensions can be removed
    - -

    Since our FrameLayout has the same dimension as its parent, by -the virtue of using the fill_parent constraints, and does not -define any background, extra padding or a gravity, it is totally -useless. We only made the UI more complex for no good reason. But how could -we get rid of this FrameLayout? After all, XML documents require a -root tag and tags in XML layouts always represent view instances.

    - -

    That's where the <merge /> tag comes in handy. When the -{@link android.view.LayoutInflater} encounters this tag, it skips it and adds -the <merge /> children to the <merge /> -parent. Confused? Let's rewrite our previous XML layout by replacing the -FrameLayout with <merge />:

    - -
    <merge xmlns:android="http://schemas.android.com/apk/res/android">
    -
    -    <ImageView  
    -        android:layout_width="fill_parent" 
    -        android:layout_height="fill_parent" 
    -    
    -        android:scaleType="center"
    -        android:src="@drawable/golden_gate" />
    -    
    -    <TextView
    -        android:layout_width="wrap_content" 
    -        android:layout_height="wrap_content" 
    -        android:layout_marginBottom="20dip"
    -        android:layout_gravity="center_horizontal|bottom"
    -
    -        android:padding="12dip"
    -        
    -        android:background="#AA000000"
    -        android:textColor="#ffffffff"
    -        
    -        android:text="Golden Gate" />
    -
    -</merge>
    - -

    With this new version, both the TextView and the -ImageView will be added directly to the top-level -FrameLayout. The result will be visually the same but the view -hierarchy is simpler:

    - -
    Optimized view hierarchy using the merge tag
    - -

    Obviously, using <merge /> works in this case because the -parent of an activity's content view is always a FrameLayout. You -could not apply this trick if your layout was using a LinearLayout -as its root tag for instance. The <merge /> can be useful in -other situations though. For instance, it works perfectly when combined with the -<include /> tag. You can also use <merge -/> when you create a custom composite view. Let's see how we can use -this tag to create a new view called OkCancelBar which simply shows -two buttons with customizable labels. You can also download the complete -source code of this example. Here is the XML used to display this custom -view on top of an image:

    - -
    <merge
    -    xmlns:android="http://schemas.android.com/apk/res/android"
    -    xmlns:okCancelBar="http://schemas.android.com/apk/res/com.example.android.merge">
    -
    -    <ImageView  
    -        android:layout_width="fill_parent" 
    -        android:layout_height="fill_parent" 
    -    
    -        android:scaleType="center"
    -        android:src="@drawable/golden_gate" />
    -    
    -    <com.example.android.merge.OkCancelBar
    -        android:layout_width="fill_parent" 
    -        android:layout_height="wrap_content" 
    -        android:layout_gravity="bottom"
    -
    -        android:paddingTop="8dip"
    -        android:gravity="center_horizontal"
    -        
    -        android:background="#AA000000"
    -        
    -        okCancelBar:okLabel="Save"
    -        okCancelBar:cancelLabel="Don't save" />
    -
    -</merge>
    - -

    This new layout produces the following result on a device:

    - -
    Creating a custom view with the merge tag
    - -

    The source code of OkCancelBar is very simple because the two -buttons are defined in an external XML file, loaded using a -LayoutInflate. As you can see in the following snippet, the XML -layout R.layout.okcancelbar is inflated with the -OkCancelBar as the parent:

    - -
    public class OkCancelBar extends LinearLayout {
    -    public OkCancelBar(Context context, AttributeSet attrs) {
    -        super(context, attrs);
    -        setOrientation(HORIZONTAL);
    -        setGravity(Gravity.CENTER);
    -        setWeightSum(1.0f);
    -        
    -        LayoutInflater.from(context).inflate(R.layout.okcancelbar, this, true);
    -        
    -        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.OkCancelBar, 0, 0);
    -        
    -        String text = array.getString(R.styleable.OkCancelBar_okLabel);
    -        if (text == null) text = "Ok";
    -        ((Button) findViewById(R.id.okcancelbar_ok)).setText(text);
    -        
    -        text = array.getString(R.styleable.OkCancelBar_cancelLabel);
    -        if (text == null) text = "Cancel";
    -        ((Button) findViewById(R.id.okcancelbar_cancel)).setText(text);
    -        
    -        array.recycle();
    -    }
    -}
    - -

    The two buttons are defined in the following XML layout. As you can see, we -use the <merge /> tag to add the two buttons directly to the -OkCancelBar. Each button is included from the same external XML -layout file to make them easier to maintain; we simply override their id:

    - -
    <merge xmlns:android="http://schemas.android.com/apk/res/android">
    -    <include
    -        layout="@layout/okcancelbar_button"
    -        android:id="@+id/okcancelbar_ok" />
    -        
    -    <include
    -        layout="@layout/okcancelbar_button"
    -        android:id="@+id/okcancelbar_cancel" />
    -</merge>
    - -

    We have created a flexible and easy to maintain custom view that generates -an efficient view hierarchy:

    - -
    The resulting hierarchy is simple and efficient
    - -

    The <merge /> tag is extremely useful and can do wonders -in your code. However, it suffers from a couple of limitations:

    - -
      -
    • <merge /> can only be used as the root tag of an XML layout
    • -
    • When inflating a layout starting with a <merge />, you must -specify a parent ViewGroup and you must set attachToRoot to -true (see the documentation for -{@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)} method)
    • -
    - diff --git a/docs/html/resources/articles/layout-tricks-reuse.jd b/docs/html/resources/articles/layout-tricks-reuse.jd deleted file mode 100644 index 179c1d8e0e3e..000000000000 --- a/docs/html/resources/articles/layout-tricks-reuse.jd +++ /dev/null @@ -1,81 +0,0 @@ -page.title=Layout Tricks: Creating Reusable UI Components -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    The Android platform offers a wide variety of UI widgets, small -visual construction blocks that you can glue together to present users with -complex and useful interfaces. However applications often need higher-level -visual components. To meet that need, and to do so efficiently, you can -combine multiple standard widgets into a single, reusable component.

    - -

    For example, you could create a reusable component that contains a progress -bar and a cancel button, a panel containing two buttons (positive and negative -actions), a panel with an icon, a title and a description, and so on. You can -create UI components easily by writing a custom View, but you can -do it even more easily using only XML.

    - -

    In Android XML layout files, each tag is mapped to an actual class instance -(the class is always a subclass of {@link android.view.View} The UI toolkit lets -you also use three special tags that are not mapped to a View -instance: <requestFocus />, <merge /> and -<include />. This article shows how to use <include -/> to create pure XML visual components. For information about how to -use <merge />, which can be particularly powerful when -combined with <include />see the Merging Layouts -article.

    - -

    The <include /> element does exactly what its name -suggests; it includes another XML layout. Using this tag is straightforward as -shown in the following example, taken straight from the source code of the Home application -that ships with Android:

    - -
    <com.android.launcher.Workspace
    -    android:id="@+id/workspace"
    -    android:layout_width="fill_parent"
    -    android:layout_height="fill_parent"
    -
    -    launcher:defaultScreen="1">
    -
    -    <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
    -    <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
    -    <include android:id="@+id/cell3" layout="@layout/workspace_screen" />
    -
    -</com.android.launcher.Workspace>
    - -

    In the <include /> only the layout attribute -is required. This attribute, without the android namespace prefix, -is a reference to the layout file you wish to include. In this example, the same -layout is included three times in a row. This tag also lets you override a few -attributes of the included layout. The above example shows that you can use -android:id to specify the id of the root view of the included -layout; it will also override the id of the included layout if one is defined. -Similarly, you can override all the layout parameters. This means that any -android:layout_* attribute can be used with the <include -/> tag. Here is an example in -which the same layout is included twice, but only the first one overrides the layout properties:

    - -
    -<!-- override the layout height and width -->
    -<include layout="@layout/image_holder"
    -    android:layout_height="fill_parent"
    -    android:layout_width="fill_parent" />
    -<!-- do not override layout dimensions; inherit them from image_holder -->
    -<include layout="@layout/image_holder" />
    -
    - -

    Caution: If you want to override the layout dimensions, -you must override both android:layout_height and -android:layout_width—you cannot override only the height or only the width. -If you override only one, it will not take effect. (Other layout properties, such as weight, -are still inherited from the source layout.)

    - -

    This tag is particularly useful when you need to customize only part of your -UI depending on the device's configuration. For instance, the main layout of -your activity can be placed in the layout/ directory and can -include another layout which exists in two flavors, in layout-land/ -and layout-port/. This allows you to share most of the UI in -portrait and landscape.

    \ No newline at end of file diff --git a/docs/html/resources/articles/layout-tricks-stubs.jd b/docs/html/resources/articles/layout-tricks-stubs.jd deleted file mode 100644 index 64f07f981bef..000000000000 --- a/docs/html/resources/articles/layout-tricks-stubs.jd +++ /dev/null @@ -1,86 +0,0 @@ -page.title=Layout Tricks: Using ViewStubs -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Sharing and reusing UI components is very easy with Android, thanks to the <include /> tag. Sometimes it's so -easy to create complex UI constructs that your UI ends up with a large number of -views, some of which are rarely used. Thankfully, Android offers a very special -widget called {@link android.view.ViewStub}, which brings you all the benefits -of the <include /> without polluting your user interface with -rarely used views.

    - -

    A ViewStub is a dumb and lightweight view. It has no dimension, -it does not draw anything and does not participate in the layout in any way. -This means that a ViewStub is very cheap to inflate and very cheap -to keep in a view hierarchy. A ViewStub can be best described as a -lazy include. The layout referenced by a ViewStub is -inflated and added to the user interface only when you decide so.

    - -

    The following screenshot comes from the Shelves application. The main purpose of -the activity shown in the screenshot is to present the user with a browsable -list of books:

    - - - -

    The same activity is also used when the user adds or imports new books. -During such an operation, Shelves shows extra bits of user interface. -The screenshot below shows the progress bar and cancel button that -appear at the bottom of the screen during an import:

    - - - -

    Because importing books is not a common operation, at least when compared to -browsing the list of books, the import panel is originally represented -by a ViewStub:

    - - - -

    When the user initiates the import process, the ViewStub is -inflated and replaced by the content of the layout file it references:

    - - - -

    To use a ViewStub, all you need is to specify an -android:id attribute, to later inflate the stub, and an -android:layout attribute, to reference what layout file -to include and inflate. A stub lets you use a third attribute, -android:inflatedId, which can be used to override the -id of the root of the included file. Finally, the layout -parameters specified on the stub will be applied to the roof of the -included layout. Here is an example:

    - -
    <ViewStub
    -  android:id="@+id/stub_import"
    -  android:inflatedId="@+id/panel_import"
    -
    -  android:layout="@layout/progress_overlay"
    -
    -  android:layout_width="fill_parent"
    -  android:layout_height="wrap_content"
    -  android:layout_gravity="bottom" />
    - -

    When you are ready to inflate the stub, simply invoke the -{@link android.view.ViewStub#inflate()} method. You can also simply change the -visibility of the stub to {@link android.view.View#VISIBLE} or -{@link android.view.View#INVISIBLE} and the stub will inflate. Note however that the -inflate() method has the benefit of returning the root -View of the inflate layout:

    - -
    ((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
    -// or
    -View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
    - -

    It is very important to remember that after the stub is inflated, the stub is -removed from the view hierarchy. As such, it is unnecessary to keep a -long-lived reference, for instance in an class instance field, to a -ViewStub.

    - -

    A ViewStub is a great compromise between ease of programming and -efficiency. Instead of inflating views manually and adding them at runtime to -your view hierarchy, simply use a ViewStub. It's cheap and easy. -The only drawback of ViewStub is that it currently does -not support the <merge /> -tag.

    diff --git a/docs/html/resources/articles/listview-backgrounds.jd b/docs/html/resources/articles/listview-backgrounds.jd deleted file mode 100644 index c4037bace625..000000000000 --- a/docs/html/resources/articles/listview-backgrounds.jd +++ /dev/null @@ -1,88 +0,0 @@ -page.title=ListView Backgrounds: An Optimization -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    {@link android.widget.ListView} is one of Android's most widely used widgets. -It is rather easy to use, very flexible, and incredibly powerful. -ListView can also be difficult to understand at times.

    - -

    One of the most common issues with ListView happens when you try -to use a custom background. By default, like many Android widgets, -ListView has a transparent background which means that you can see -through the default window's background, a very dark gray -(#FF191919 with the current dark theme.) Additionally, -ListView enables the fading edges by default, as you can -see at the top of the following screenshot — the first text item gradually -fades to black. This technique is used throughout the system to indicate that -the container can be scrolled.

    - -
    Android's default ListView
    - -

    The fade effect is implemented using a combination of -{@link android.graphics.Canvas#saveLayerAlpha(float, float, float, float, int, int) Canvas.saveLayerAlpha()} -and the {@link android.graphics.PorterDuff.Mode#DST_OUT Porter-Duff Destination Out blending mode}.

    - -

    Unfortunately, things start to get ugly when you try to use a custom -background on the ListView or when you change the window's -background. The following two screenshots show what happens in an application -when you change the window's background. The left image shows what the list -looks like by default and the right image shows what the list looks like during -a scroll initiated with a touch gesture:

    - -
    -Dark fade -Dark list
    - -

    This rendering issue is caused by an optimization of the Android framework -enabled by default on all instances of ListView. I mentioned -earlier that the fade effect is implemented using a Porter-Duff blending mode. -This implementation works really well but is unfortunately very costly and can -bring down drawing performance by quite a bit as it requires to capture a -portion of the rendering in an offscreen bitmap and then requires extra blending -(which implies readbacks from memory.)

    - -

    Since ListView is most of the time displayed on a solid -background, there is no reason to go down that expensive route. That's why we -introduced an optimization called the "cache color hint." The cache color hint -is an RGB color set by default to the window's background color, that is #191919 -in Android's dark theme. When this hint is set, ListView (actually, -its base class View) knows it will draw on a solid background and -therefore replaces th expensive saveLayerAlpha()/Porter-Duff -rendering with a simple gradient. This gradient goes from fully transparent to -the cache color hint value and this is exactly what you see on the image above, -with the dark gradient at the bottom of the list. However, this still does not -explain why the entire list turns black during a scroll.

    - -

    As mentioned before, ListView has a transparent/translucent -background by default, and so all default widgets in the Android UI toolkit. -This implies that when ListView redraws its children, it has to -blend the children with the window's background. Once again, this requires -costly readbacks from memory that are particularly painful during a scroll or a -fling when drawing happens dozen of times per second.

    - -

    To improve drawing performance during scrolling operations, the Android -framework reuses the cache color hint. When this hint is set, the framework -copies each child of the list in a Bitmap filled with the hint -value (assuming that another optimization, called scrolling cache, is -not turned off). ListView then blits these bitmaps directly on -screen and because these bitmaps are known to be opaque, no blending is -required. Also, since the default cache color hint is #191919, you -get a dark background behind each item during a scroll.

    - -

    To fix this issue, all you have to do is either disable the cache color hint -optimization, if you use a non-solid color background, or set the hint to the -appropriate solid color value. You can do this from code (see -{@link android.widget.AbsListView#setCacheColorHint(int)}) or preferably from -XML, by using the android:cacheColorHint attribute. To disable the -optimization, simply use the transparent color #00000000. The -following screenshot shows a list with -android:cacheColorHint="#00000000" set in the XML layout file:

    - -
    Fade on a custom background
    - -

    As you can see, the fade works perfectly against the custom wooden -background. The cache color hint feature is interesting because it -shows how optimizations can make your life more difficult in -some situations. In this particular case, however, the benefit of the -default behavior outweighs the added complexity..

    diff --git a/docs/html/resources/articles/live-folders.jd b/docs/html/resources/articles/live-folders.jd deleted file mode 100644 index aeab9974c1c6..000000000000 --- a/docs/html/resources/articles/live-folders.jd +++ /dev/null @@ -1,170 +0,0 @@ -page.title=Live Folders -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Live folders, introduced in Android 1.5 (API Level 3), let you display any source of data -on the Home screen without forcing the user to launch an application. A live -folder is simply a real-time view of a {@link android.content.ContentProvider}. -As such, a live folder can be used to display all of the user's contacts or -bookmarks, email, playlists, an RSS feed, and so on. The possibilities are -endless!

    - -

    The platform includes several standard folders for displaying contacts. For -instance, the screenshot below shows the content of the live folders that -displays all contacts with a phone number:

    - - - -

    If a contacts sync happens in the background while the user is browsing this live -folder, the user will see the change happen in real-time. Live folders are not -only useful, but they are also easy to add to to your application and data. - -This articles shows how to add a live folder to an example application called -Shelves. To better understand how live folders work, you can download the source code of the -application and modify it by following the instructions below.

    - -

    To give the user the option to create a new live folder for an application, -you first need to create a new activity with an intent filter whose action is -android.intent.action.CREATE_LIVE_FOLDER. To do so, simply open -AndroidManifest.xml and add something similar to this:

    - -
    <activity
    -    android:name=".activity.BookShelfLiveFolder"
    -    android:label="BookShelf">
    -    <intent-filter>	
    -        <action android:name="android.intent.action.CREATE_LIVE_FOLDER" />
    -        <category android:name="android.intent.category.DEFAULT" />
    -    </intent-filter>
    -</activity>
    - -

    The label and icon of this activity are what the user will see on the Home -screen when choosing a live folder to create:

    - - - -

    Since you just need an intent filter, it is possible, and sometimes advised, -to reuse an existing activity. In the case of Shelves, we will create a new -activity, org.curiouscreature.android.shelves.activity.BookShelfLiveFolder. -The role of this activity is to send an Intent result to Home -containing the description of the live folder: its name, icon, display mode and -content URI. The content URI is very important as it describes what -ContentProvider will be used to populate the live folder. The code -of the activity is very simple as you can see here:

    - -
    public class BookShelfLiveFolder extends Activity {
    -    public static final Uri CONTENT_URI = Uri.parse("content://shelves/live_folders/books");
    -
    -    @Override
    -    protected void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -
    -        final Intent intent = getIntent();
    -        final String action = intent.getAction();
    -
    -        if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) {
    -            setResult(RESULT_OK, createLiveFolder(this, CONTENT_URI,
    -                    "Books", R.drawable.ic_live_folder));
    -        } else {
    -            setResult(RESULT_CANCELED);
    -        }
    -
    -        finish();
    -    }
    -
    -    private static Intent createLiveFolder(Context context, Uri uri, String name, int icon) {
    -        final Intent intent = new Intent();
    -
    -        intent.setData(uri);
    -        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, name);
    -        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON,
    -                Intent.ShortcutIconResource.fromContext(context, icon));
    -        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST);
    -
    -        return intent;
    -    }
    -}
    - -

    This activity, when invoked with theACTION_CREATE_LIVE_FOLDER -intent, returns an intent with a URI, -content://shelves/live_folders/books, and three extras to describe -the live folder. There are other extras and constants you can use and you should -refer to the documentation of android.provider.LiveFolders for more -details. When Home receives this intent, a new live folder is created on the -user's desktop, with the name and icon you provided. Then, when the user clicks -on the live folder to open it, Home queries the content provider referenced by -the provided URI.

    - -

    Live folders' content providers must obey specific naming rules. The -Cursor returned by the query() method must have at -least two columns named LiveFolders._ID and -LiveFolders.NAME. The first one is the unique identifier of each -item in the live folder and the second one is the name of the item. There are -other column names you can use to specify an icon, a description, the intent to -associate with the item (fired when the user clicks that item), etc. Again, -refer to the documentation of android.provider.LiveFolders for more -details.

    In our example, all we need to do is modify the existing provider -in Shelves called -org.curiouscreature.android.shelves.provider.BooksProvider. First, -we need to modify the URI_MATCHER to recognize our -content://shelves/live_folders/books content URI:

    - -
    private static final int LIVE_FOLDER_BOOKS = 4;
    -// ...
    -URI_MATCHER.addURI(AUTHORITY, "live_folders/books", LIVE_FOLDER_BOOKS);
    - -

    Then we need to create a new projection map for the cursor. A projection map -can be used to "rename" columns. In our case, we will replace -BooksStore.Book._ID, BooksStore.Book.TITLE and -BooksStore.Book.AUTHORS with LiveFolders._ID, -LiveFolders.TITLE and LiveFolders.DESCRIPTION:

    - -
    private static final HashMap<string, string=""> LIVE_FOLDER_PROJECTION_MAP;
    -static {
    -    LIVE_FOLDER_PROJECTION_MAP = new HashMap<string, string="">();
    -    LIVE_FOLDER_PROJECTION_MAP.put(LiveFolders._ID, BooksStore.Book._ID +
    -            " AS " + LiveFolders._ID);
    -    LIVE_FOLDER_PROJECTION_MAP.put(LiveFolders.NAME, BooksStore.Book.TITLE +
    -            " AS " + LiveFolders.NAME);
    -    LIVE_FOLDER_PROJECTION_MAP.put(LiveFolders.DESCRIPTION, BooksStore.Book.AUTHORS +
    -            " AS " + LiveFolders.DESCRIPTION);
    -}
    - -

    Because we are providing a title and a description for each row, Home will -automatically display each item of the live folder with two lines of text. -Finally, we implement the query() method by supplying our -projection map to the SQL query builder:

    - -
    public Cursor query(Uri uri, String[] projection, String selection,
    -        String[] selectionArgs, String sortOrder) {
    -
    -    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    -
    -    switch (URI_MATCHER.match(uri)) {
    -        // ...
    -        case LIVE_FOLDER_BOOKS:
    -            qb.setTables("books");
    -            qb.setProjectionMap(LIVE_FOLDER_PROJECTION_MAP);
    -            break;
    -        default:
    -            throw new IllegalArgumentException("Unknown URI " + uri);
    -    }
    -
    -    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    -    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, BooksStore.Book.DEFAULT_SORT_ORDER);
    -    c.setNotificationUri(getContext().getContentResolver(), uri);
    -
    -    return c;
    -}
    - -

    You can now compile and deploy the application, go to the Home screen and -try to add a live folder. You can add a books live folder to your Home screen -and when you open it, see the list of all of your books, with their -titles and authors, and all it took was a few lines of code:

    - -

    - -

    The live folders API is extremely simple and relies only on intents and -content URI. If you want to see more examples of live folders -implementation, you can read the source code of the Contacts application and of the Contacts provider.

    You can also download the result of our exercise, the modified version of Shelves with live folders support.

    \ No newline at end of file diff --git a/docs/html/resources/articles/live-wallpapers.jd b/docs/html/resources/articles/live-wallpapers.jd deleted file mode 100644 index 0692a626f766..000000000000 --- a/docs/html/resources/articles/live-wallpapers.jd +++ /dev/null @@ -1,102 +0,0 @@ -page.title=Live Wallpapers -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -
    -
    - -

    See also

    -
      -
    1. Live Wallpaper -sample
    2. -
    - -
    -
    - -

    Starting with Android 2.1 (API Level 7), users can now enjoy live -wallpapers — richer, animated, interactive backgrounds — on -their home screens. A live wallpaper is very similar to a normal Android -application and has access to all the facilities of the platform: SGL (2D -drawing), OpenGL (3D drawing), GPS, accelerometers, network access, etc. The -live wallpapers included on Nexus One demonstrate the use of some of these APIs -to create fun and interesting user experiences. For instance, the Grass -wallpaper uses the phone's location to compute sunrise and sunset times in order -to display the appropriate sky.

    - - - -

    Creating your own live wallpaper is easy, especially if you have had -previous experience with {@link android.view.SurfaceView} or {@link -android.graphics.Canvas}. -To learn how to create a live wallpaper, you should check out the CubeLiveWallpaper sample code.

    - -

    In terms of implementation, a live wallpaper is very similar to a {@link android.app.Service}. -The only difference is the addition of a new method, {@link -android.service.wallpaper.WallpaperService#onCreateEngine()}, whose goal is to create a {@link -android.service.wallpaper.WallpaperService.Engine}. The engine is responsible for -handling the lifecycle and drawing of a wallpaper. The system provides a surface -on which you can draw, just like you would with a {@link android.view.SurfaceView}. -Drawing a wallpaper can be very expensive so you should optimize your code -as much as possible to avoid using too much CPU, not only for battery life -but also to avoid slowing down the rest of the system. That is also why the -most important part of the lifecycle of a wallpaper is when it becomes visible, as indicated -by a call to {@link android.service.wallpaper.WallpaperService.Engine#onVisibilityChanged -onVisibilityChanged()}. -When invisible, such as when the user launches an application that covers -the home screen, a wallpaper must stop all activity.

    - -

    The engine can also implement several methods to interact with the user -or the home application. For instance, if you want your wallpaper to scroll -along when the user swipes from one home screen to another, you can use -{@link android.service.wallpaper.WallpaperService.Engine#onOffsetsChanged -onOffsetsChanged()}. -To react to touch events, simply implement {@link -android.service.wallpaper.WallpaperService.Engine#onTouchEvent onTouchEvent()}. -Finally, applications can send arbitrary commands to the live wallpaper. -Currently, only the standard home application sends commands to the -{@link android.service.wallpaper.WallpaperService.Engine#onCommand onCommand()} -method of the live wallpaper:

    - -
      -
    • android.wallpaper.tap: When the user taps an empty space -on the workspace. This command is interpreted by the Nexus and Water live -wallpapers to make the wallpaper react to user interaction. For instance, -if you tap an empty space on the Water live wallpaper, new ripples appear -under your finger.
    • -
    • android.home.drop: When the user drops an icon or a widget -on the workspace. This command is also interpreted by the Nexus and Water -live wallpapers.
    • -
    - -

    If you are developing a live wallpaper, remember that the feature is -supported only on Android 2.1 (API level 7) and higher versions of the platform. -To ensure that your application can only be installed on devices that support -live wallpapers, remember to add the following to the application's manifest -before publishing to Google Play:

    - -
      -
    • <uses-sdk android:minSdkVersion="7" />, which indicates -to Google Play and the platform that your application requires Android 2.1 or -higher. For more information, see the API -Levels and the documentation for the -<uses-sdk> -element.
    • -
    • <uses-feature android:name="android.software.live_wallpaper" />, -which tells Google Play that your application includes a live wallpaper -Google Play uses this feature as a filter, when presenting users lists of -available applications. When you declaring this feature, Google Play -displays your application only to users whose devices support live wallpapers, -while hiding it from other devices on which it would not be able to run. For -more information, see the documentation for the -{@code -<uses-feature> -element.
    • -
    - -

    Many great live wallpapers are already available on Google Play and -we can't wait to see more!

    diff --git a/docs/html/resources/articles/multitasking-android-way.jd b/docs/html/resources/articles/multitasking-android-way.jd deleted file mode 100644 index 0dc862728aa3..000000000000 --- a/docs/html/resources/articles/multitasking-android-way.jd +++ /dev/null @@ -1,103 +0,0 @@ -page.title=Multitasking the Android Way -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -
    -
    - -

    See also

    -
      -
    1. Tasks and Back Stack
    2. -
    3. Services
    4. -
    - -

    Key classes

    -
      -
    1. {@link android.app.Service}
    2. -
    3. {@link android.content.BroadcastReceiver}
    4. -
    - -
    -
    - -

    Android is fairly unique in the ways it allows multiple applications to run at the same time. Developers coming from a different platform may find the way it operates surprising. Understanding its behavior is important for designing applications that will work well and integrate seamlessly with the rest of the Android platform. This article covers the reasons for Android's multitasking design, its impact on how applications work, and how you can best take advantage of Android's unique features.

    -

    Design considerations

    -

    Mobile devices have technical limitations and user experience requirements not present in desktop or web systems. Here are the four key constraints we were working under as we designed Android's multitasking:

    -
      -
    • -

      We did not want to require that users close applications when "done" with them. Such a usage pattern does not work well in a mobile environment, where usage tends to involve repeated brief contact with a wide variety of applications throughout the day.

      -
    • -
    • -

      Mobile devices don't have the luxury of swap space, so have fairly hard limits on memory use. Robert Love has a very good article covering the topic.

      -
    • -
    • -

      Application switching on a mobile device is extremely critical; we target significantly less than 1 second to launch a new application. This is especially important when the user is switching between a few applications, such as switching to look at a new SMS message while watching a video, and then returning to that video. A noticeable wait in such situations will quickly make users hate you.

      -
    • -
    • -

      The available APIs must be sufficient for writing the built-in Google applications, as part of our "all applications are created equal" philosophy. This means background music playback, data syncing, GPS navigation, and application downloading must be implemented with the same APIs that are available to third party developers.

      -
    • -
    -

    The first two requirements highlight an interesting conflict. We don't want users to worry about closing their apps, but rather make it appear that all of the applications are always running. At the same time, mobile devices have hard limits on memory use, so that a system will degrade or even start failing very quickly as it needs more RAM than is available; a desktop computer, with swap, in contrast will simply start slowing down as it needs to page RAM to its swap space. These competing constraints were a key motivation for Android's design.

    -

    When does an application "stop"?

    -

    A common misunderstanding about Android multitasking is the difference between a process and an application. In Android these are not tightly coupled entities: applications may seem present to the user without an actual process currently running the app; multiple applications may share processes, or one application may make use of multiple processes depending on its needs; the process(es) of an application may be kept around by Android even when that application is not actively doing something.

    -

    The fact that you can see an application's process "running" does not mean the application is running or doing anything. It may simply be there because Android needed it at some point, and has decided that it would be best to keep it around in case it needs it again. Likewise, you may leave an application for a little bit and return to it from where you left off, and during that time Android may have needed to get rid of the process for other things.

    -

    A key to how Android handles applications in this way is that processes don't shut down cleanly. When the user leaves an application, its process is kept around in the background, allowing it to continue working (for example downloading web pages) if needed, and come immediately to the foreground if the user returns to it. If a device never runs out of memory, then Android will keep all of these processes around, truly leaving all applications "running" all of the time.

    -

    Of course, there is a limited amount of memory, and to accommodate this Android must decide when to get rid of processes that are not needed. This leads to Android's process lifecycle, the rules it uses to decide how important each process is and thus the next one that should be dropped. These rules are based on both how important a process is for the user's current experience, as well as how long it has been since the process was last needed by the user.

    -

    Once Android determines that it needs to remove a process, it does this brutally, simply force-killing it. The kernel can then immediately reclaim all resources needed by the process, without relying on that application being well written and responsive to a polite request to exit. Allowing the kernel to immediately reclaim application resources makes it a lot easier to avoid serious out of memory situations.

    -

    If a user later returns to an application that's been killed, Android needs a way to re-launch it in the same state as it was last seen, to preserve the "all applications are running all of the time" experience. This is done by keeping track of the parts of the application the user is aware of (the Activities), and re-starting them with information about the last state they were seen in. This last state is generated each time the user leaves that part of the application, not when it is killed, so that the kernel can later freely kill it without depending on the application to respond correctly at that point.

    -

    In some ways, Android's process management can be seen as a form of swap space: application processes represent a certain amount of in-use memory; when memory is low, some processes can be killed (swapped out); when those processes are needed again, they can be re-started from their last saved state (swapped in).

    -

    Explicitly running in the background

    -

    So far, we have a way for applications to implicitly do work in the background, as long as the process doesn't get killed by Android as part of its regular memory management. This is fine for things like loading web pages in the background, but what about features with harder requirements? Background music playback, data synchronization, location tracking, alarm clocks, etc.

    -

    -

    For these tasks, the application needs a way to tell Android "I would explicitly like to run at this point." There are two main facilities available to applications for this, represented by two kinds of components they can publish in their manifest: broadcast receivers and services.

    -

    Broadcast Receivers

    -

    A BroadcastReceiver allows an application to run, for a brief amount of time, in the background as a result of something else happening. It can be used in many ways to build higher-level facilities: for example the AlarmManager allows an application to have a broadcast sent at a certain time in the future, and the LocationManager can send a broadcast when it detects interesting changes in location. Because information about the receiver is part of an application's manifest, Android can find and launch the application even if it isn't running; of course if it already has its process available in the background, the broadcast can very efficiently be directly dispatched to it.

    -

    When handling a broadcast, the application is given a fixed set of time (currently 10 seconds) in which to do its work. If it doesn't complete in that time, the application is considered to be misbehaving, and its process immediately tossed into the background state to be killed for memory if needed.

    -

    Broadcast receivers are great for doing small pieces of work in response to an external stimulus, such as posting a notification to the user after being sent a new GPS location report. They are very lightweight, since the application's process only needs to be around while actively receiving the broadcast. Because they are active for a deterministic amount of time, fairly strong guarantees can be made about not killing their process while running. However they are not appropriate for anything of indeterminate length, such as networking.

    -

    Services

    -

    A Service allows an application to implement longer-running background operations. There are actually a lot of other functions that services provide, but for the discussion here their fundamental purpose is for an application to say "hey I would like to continue running even while in the background, until I say I am done." An application controls when its service runs by explicitly starting and stopping the service.

    -

    While services do provide a rich client-server model, its use is optional. Upon starting an application's services, Android simply instantiates the component in the application's process to provide its context. How it is used after that is up to the application: it can put all of the needed code inside of the service itself without interacting with other parts of the application, make calls on other singleton objects shared with other parts of the app, directly retrieve the Service instance from elsewhere if needed, or run it in another process and do a full-blown RPC protocol if that is desired.

    -

    Process management for services is different than broadcast receivers, because an unbounded number of services can ask to be running for an unknown amount of time. There may not be enough RAM to have all of the requesting services run, so as a result no strong guarantees are made about being able to keep them running.

    -

    If there is too little RAM, processes hosting services will be immediately killed like background processes are. However, if appropriate, Android will remember that these services wish to remain running, and restart their process at a later time when more RAM is available. For example, if the user goes to a web page that requires large amounts of RAM, Android may kill background service processes like sync until the browser's memory needs go down.

    -

    Services can further negotiate this behavior by requesting they be considered "foreground." This places the service in a "please don't kill" state, but requires that it include a notification to the user about it actively running. This is useful for services such as background music playback or car navigation, which the user is actively aware of; when you're playing music and using the browser, you can always see the music-playing glyph in the status bar. Android won't try to kill these services, but as a trade-off, ensures the user knows about them and is able to explicitly stop them when desired.

    -

    The value of generic components

    -

    Android's generic broadcast receiver and service components allow developers to create a wide variety of efficient background operations, including things that were never originally considered. In Android 1.0 they were used to implement nearly all of the background behavior that the built-in and proprietary Google apps provided:

    -
      -
    • - Music playback runs in a service to allow it to continue operating after the user leaves the music application. -
    • -
    • - The alarm clock schedules a broadcast receiver with the alarm manager, to go off at the next set alarm time. -
    • -
    • - The calendar application likewise schedules an alarm to display or update its notification at the appropriate time for the next calendar event. -
    • -
    • - Background file download is implemented a service that runs when there are any downloads to process. -
    • -
    • - The e-mail application schedules an alarm to wake up a service at regular intervals that looks for and retrieves any new mail. -
    • -
    • - The Google applications maintain a service to receive push notifications from the network; it in turn sends broadcasts to individual apps when it is told that they need to do things like synchronize contacts.

      -
    • -
    -

    As the platform has evolved, these same basic components have been used to implement many of the major new developer features: -

      -
    • - Input methods are implemented by developers as a Service component that Android manages and works with to display as the current IME. -
    • -
    • - Application widgets are broadcast receivers that Android sends broadcasts to when it needs to interact with them. This allows app widgets to be quite lightweight, by not needing their application's process remain running. -
    • -
    • - Accessibility features are implemented as services that Android keeps running while in use and sends appropriate information to about user interactions. -
    • -
    • - Sync adapters introduced in Android 2.0 are services that are run in the background when a particular data sync needs to be performed. -
    • -
    • - Live wallpapers are a service started by Android when selected by the user. -
    • -
    diff --git a/docs/html/resources/articles/on-screen-inputs.jd b/docs/html/resources/articles/on-screen-inputs.jd deleted file mode 100644 index 6a028c8ea231..000000000000 --- a/docs/html/resources/articles/on-screen-inputs.jd +++ /dev/null @@ -1,265 +0,0 @@ -page.title=Onscreen Input Methods -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -
    - -
    - - -

    Starting from Android 1.5, the Android platform offers an Input Method -Framework (IMF) that lets you create on-screen input methods such as software -keyboards. This article provide an overview of what Android input method editors -(IMEs) are and what an application needs to do to work well with them. The IMF -is designed to support new classes of Android devices, such as those without -hardware keyboards, so it is important that your application works well with the -IMF and offers a great experience for users.

    - -

    What is an input method?

    - -

    The Android IMF is designed to support a variety of IMEs, including soft -keyboard, hand-writing recognizers, and hard keyboard translators. Our focus, -however, will be on soft keyboards, since this is the kind of input method that -is currently part of the platform.

    - -

    A user will usually access the current IME by tapping on a text view to -edit, as shown here in the home screen:

    - - - - -

    The soft keyboard is positioned at the bottom of the screen over the -application's window. To organize the available space between the application -and IME, we use a few approaches; the one shown here is called pan and -scan, and simply involves scrolling the application window around so that -the currently focused view is visible. This is the default mode, since it is the -safest for existing applications.

    - -

    Most often the preferred screen layout is a resize, where the -application's window is resized to be entirely visible. An example is shown -here, when composing an e-mail message:

    - - - - -

    The size of the application window is changed so that none of it is hidden by -the IME, allowing full access to both the application and IME. This of course -only works for applications that have a resizeable area that can be reduced to -make enough space, but the vertical space in this mode is actually no less than -what is available in landscape orientation, so very often an application can -already accommodate it.

    - -

    The final major mode is fullscreen or extract -mode. This is used when the IME is too large to reasonably share space -with the underlying application. With the standard IMEs, you will only -encounter this situation when the screen is in a landscape orientation, -although other IMEs are free to use it whenever they desire. In this -case the application window is left as-is, and the IME simply displays -fullscreen on top of it, as shown here:

    - - - - -

    Because the IME is covering the application, it has its own editing area, -which shows the text actually contained in the application. There are also some -limited opportunities the application has to customize parts of the IME (the -"done" button at the top and enter key label at the bottom) to improve the user -experience.

    - -

    Basic XML attributes for controlling IMEs

    - -

    There are a number of things the system does to try to help existing -applications work with IMEs as well as possible, such as:

    - -
      -
    • Use pan and scan mode by default, unless it can reasonably guess that -resize mode will work by the existence of lists, scroll views, etc.
    • -
    • Analyze the various existing TextView attributes to guess at the kind of -content (numbers, plain text, etc) to help the soft keyboard display an -appropriate key layout.
    • -
    • Assign a few default actions to the fullscreen IME, such as "next field" -and "done".
    • -
    - -

    There are also some simple things you can do in your application that will -often greatly improve its user experience. Except where explicitly mentioned, -these will work in any Android platform version, even those previous to Android -1.5 (since they will simply ignore these new options).

    - -

    Specifying each EditText control's input type

    - -

    The most important thing for an application to do is to use the new -android:inputType -attribute on each EditText. The attribute provides much richer -information -about the text content. This attribute actually replaces many existing -attributes (android:password, -android:singleLine, -android:numeric, -android:phoneNumber, -android:capitalize, -android:autoText, and -android:editable). If you specify the older attributes -and the new android:inputType attribute, the system uses -android:inputType and ignores the others.

    - -

    The android:inputType attribute has three pieces:

    - -
      -
    • The class is the overall interpretation of characters. The -currently supported classes are text (plain text), -number (decimal number), phone (phone number), and -datetime (a date or time).
    • -
    • The variation is a further refinement on the class. In the -attribute you will normally specify the class and variant together, with the -class as a prefix. For example, textEmailAddress is a text field -where the user will enter something that is an e-mail address (foo@bar.com) so -the key layout will have an '@' character in easy access, and -numberSigned is a numeric field with a sign. If only the class is -specified, then you get the default/generic variant.
    • -
    • Additional flags can be specified that supply further refinement. -These flags are specific to a class. For example, some flags for the -text class are textCapSentences, -textAutoCorrect, and textMultiline.
    • -
    - -

    As an example, here is the new EditText for the IM application's message text view:

    - -
        <EditText android:id="@+id/edtInput"
    -        android:layout_width="0dip"
    -        android:layout_height="wrap_content"
    -        android:layout_weight="1"
    -        android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine"
    -        android:imeOptions="actionSend|flagNoEnterAction"
    -        android:maxLines="4"
    -        android:maxLength="2000"
    -        android:hint="@string/compose_hint"/>
    - -

    A full description of all of the input types can be found in the -documentation. It is important to make use of the correct input types that are -available, so that the soft keyboard can use the optimal keyboard layout for the -text the user will be entering.

    - -

    Enabling resize mode and other window features

    - -

    The second most important thing for your app to do is to specify the overall -behavior of your window in relation to the input method. The most visible aspect -of this is controlling resize vs. pan and scan mode, but there are other things -you can do as well to improve your user experience.

    - -

    You will usually control this behavior through the -android:windowSoftInputMode attribute on each -<activity> definition in your -AndroidManifest.xml. Like the input type, there are a couple -different pieces of data that can be specified here by combining them -together:

    - -
      -
    • The window adjustment mode is specified with either -adjustResize or adjustPan. It is highly recommended -that you always specify one or the other.
    • -
    • You can further control whether the IME will be shown automatically when -your activity is displayed and other situations where the user moves to it. The -system won't automatically show an IME by default, but in some cases it can be -convenient for the user if an application enables this behavior. You can request -this with stateVisible. There are also a number of other state -options for finer-grained control that you can find in the documentation.
    • -
    - -

    A typical example of this field can be see in the edit contact activity, -which ensures it is resized and automatically displays the IME for the user:

    - -
        <activity name="EditContactActivity"
    -        android:windowSoftInputMode="stateVisible|adjustResize">
    -        ...
    -    </activity>
    - -

    Note:Starting from Android 1.5 (API Level 3), -the platform offers a new method, -{@link android.view.Window#setSoftInputMode(int mode)}, -that non-Activity windows can use to control their behavior. Calling this method -in your will make your application incompatible with previous versions of the -Android platform.

    - -

    Controlling the action buttons

    - -

    The final customization we will look at is the "action" buttons in the IME. -There are currently two types of actions:

    - -
      -
    • The enter key on a soft keyboard is typically bound to an action when not -operating on a mult-line edit text. For example, on the G1 pressing the hard -enter key will typically move to the next field or the application will -intercept it to execute an action; with a soft keyboard, this overloading of the -enter key remains, since the enter button just sends an enter key event.
    • -
    • When in fullscreen mode, an IME may also put an additional action button to -the right of the text being edited, giving the user quick access to a common -application operation.
    • -
    - -

    These options are controlled with the android:imeOptions -attribute on TextView. The value you supply here can be any -combination of:

    - -
      -
    • One of the pre-defined action constants (actionGo, -actionSearch, actionSend, actionNext, -actionDone). If none of these are specified, the system will infer -either actionNext or actionDone depending on whether -there is a focusable field after this one; you can explicitly force no action -with actionNone.
    • -
    • The flagNoEnterAction option tells the IME that the action -should not be available on the enter key, even if the text itself is -not multi-line. This avoids having unrecoverable actions like (send) that can be -accidentally touched by the user while typing.
    • -
    • The flagNoAccessoryAction removes the action button from the -text area, leaving more room for text.
    • The flagNoExtractUi -completely removes the text area, allowing the application to be seen behind -it.
    • -
    - -

    The previous IM application message view also provides an example of an -interesting use of imeOptions, to specify the send action but not -let it be shown on the enter key:

    - -
    android:imeOptions="actionSend|flagNoEnterAction"
    - -

    APIs for controlling IMEs

    - -

    For more advanced control over the IME, there are a variety of new APIs you -can use. Unless special care is taken (such as by using reflection), using these -APIs will cause your application to be incompatible with previous versions of -Android, and you should make sure you specify -android:minSdkVersion="3" in your manifest. For more information, -see the documentation for the <uses-sdk> manifest element.

    - -

    The primary API is the new android.view.inputmethod.InputMethodManager class, which you can retrieve with Context.getSystemService(). -It allows you to interact with the global input method state, such as -explicitly hiding or showing the current IME's input area.

    - -

    There are also new window flags controlling input method interaction, which you can control through the existing Window.addFlags() method and new Window.setSoftInputMode() method. The PopupWindow -class has grown corresponding methods to control these options on its -window. One thing in particular to be aware of is the new WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM constant, which is used to control whether a window is on top of or behind the current IME.

    - -

    Most of the interaction between an active IME and application is done through the android.view.inputmethod.InputConnection -class. This is the API an application implement, which an IME calls to -perform the appropriate edit operations on the application. You won't -normally need to worry about this, since TextView provides its own implementation for itself.

    - -

    There are also a handful of new View APIs, the most important of these being onCreateInputConnection() which creates a new InputConnection for an IME (and fills in an android.view.inputmethod.EditorInfo -structure with your input type, IME options, and other data); again, -most developers won't need to worry about this, since TextView takes -care of it for you.

    \ No newline at end of file diff --git a/docs/html/resources/articles/painless-threading.jd b/docs/html/resources/articles/painless-threading.jd deleted file mode 100644 index fea7ee21d57e..000000000000 --- a/docs/html/resources/articles/painless-threading.jd +++ /dev/null @@ -1,149 +0,0 @@ -page.title=Painless Threading -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    This article discusses the threading model used by Android applications and how applications can ensure best UI performance by spawning worker threads to handle long-running operations, rather than handling them in the main thread. The article also explains the API that your application can use to interact with Android UI toolkit components running on the main thread and spawn managed worker threads.

    - -

    The UI thread

    - -

    When an application is launched, the system creates a thread called -"main" for the application. The main thread, also called the UI -thread, is very important because it is in charge of dispatching the -events to the appropriate widgets, including drawing events. -It is also the thread where your application interacts with running -components of the Android UI toolkit.

    - -

    For instance, if you touch the a button on screen, the UI thread dispatches -the touch event to the widget, which in turn sets its pressed state and -posts an invalidate request to the event queue. The UI thread dequeues -the request and notifies the widget to redraw itself.

    - -

    This single-thread model can yield poor performance unless your application -is implemented properly. Specifically, if everything is happening in a single -thread, performing long operations such as network access or database -queries on the UI thread will block the whole user interface. No event -can be dispatched, including drawing events, while the long operation -is underway. From the user's perspective, the application appears hung. -Even worse, if the UI thread is blocked for more than a few seconds -(about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog.

    - -

    If you want to see how bad this can look, write a simple application -with a button that invokes Thread.sleep(2000) in its -OnClickListener. -The button will remain in its pressed state for about 2 seconds before -going back to its normal state. When this happens, it is very easy for -the user to perceive the application as slow.

    - -

    To summarize, it's vital to the responsiveness of your application's UI to -keep the UI thread unblocked. If you have long operations to perform, you should -make sure to do them in extra threads (background or worker -threads).

    - -

    Here's an example of a click listener downloading an image over the -network and displaying it in an ImageView:

    - -
    public void onClick(View v) {
    -  new Thread(new Runnable() {
    -    public void run() {
    -      Bitmap b = loadImageFromNetwork();
    -      mImageView.setImageBitmap(b);
    -    }
    -  }).start();
    -}
    - -

    At first, this code seems to be a good solution to your problem, as it does -not block the UI thread. Unfortunately, it violates the single-threaded model -for the UI: the Android UI toolkit is not thread-safe and must always -be manipulated on the UI thread. In this piece of code above, the -ImageView is manipulated on a worker thread, which can cause really -weird problems. Tracking down and fixing such bugs can be difficult and -time-consuming.

    - -

    Android offers several ways to access the UI -thread from other threads. You may already be familiar with some of -them but here is a comprehensive list:

    - -
      -
    • {@link android.app.Activity#runOnUiThread(java.lang.Runnable) Activity.runOnUiThread(Runnable)}
    • -
    • {@link android.view.View#post(java.lang.Runnable) View.post(Runnable)}
    • -
    • {@link android.view.View#postDelayed(java.lang.Runnable, long) View.postDelayed(Runnable, long)}
    • -
    • {@link android.os.Handler}
    • -
    - -

    You can use any of these classes and methods to correct the previous code example:

    - -
    public void onClick(View v) {
    -  new Thread(new Runnable() {
    -    public void run() {
    -      final Bitmap b = loadImageFromNetwork();
    -      mImageView.post(new Runnable() {
    -        public void run() {
    -          mImageView.setImageBitmap(b);
    -        }
    -      });
    -    }
    -  }).start();
    -}
    - -

    Unfortunately, -these classes and methods could also tend to make your code more complicated -and more difficult to read. It becomes even worse when your implement -complex operations that require frequent UI updates.

    - -

    To remedy this problem, Android 1.5 and later platforms offer a utility class -called {@link android.os.AsyncTask}, that simplifies the creation of -long-running tasks that need to communicate with the user interface.

    - -

    An AsyncTask equivalent is also available for applications that -will run on Android 1.0 and 1.1. The name of the class is UserTask. It offers the -exact same API and all you have to do is copy its source code in your -application.

    - -

    The goal of AsyncTask is to take care of thread management for -you. Our previous example can easily be rewritten with -AsyncTask:

    - -
    public void onClick(View v) {
    -  new DownloadImageTask().execute("http://example.com/image.png");
    -}
    -
    -private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    -     protected Bitmap doInBackground(String... urls) {
    -         return loadImageFromNetwork(urls[0]);
    -     }
    -
    -     protected void onPostExecute(Bitmap result) {
    -         mImageView.setImageBitmap(result);
    -     }
    - }
    - -

    As you can see, AsyncTask must be used by subclassing -it. It is also very important to remember that an AsyncTask -instance has to be created on the UI thread and can be executed only once. You -can read the -AsyncTask documentation for a full understanding on how to use this class, -but here is a quick overview of how it works:

    - - - -

    In addition to the official documentation, you can read several complex examples in the source code of Shelves (ShelvesActivity.java and AddBookActivity.java) and Photostream (LoginActivity.java, PhotostreamActivity.java and ViewPhotoActivity.java). We highly recommend reading the source code of Shelves to see how to persist tasks across configuration changes and how to cancel them properly when the activity is destroyed.

    - -

    Regardless of whether or not you use AsyncTask, -always remember these two rules about the single thread model:

    - -
      -
    1. Do not block the UI thread, and -
    2. Make sure that you access the Android UI toolkit only on the UI thread. -
    - -

    AsyncTask just makes it easier to do both of these things.

    diff --git a/docs/html/resources/articles/qsb.jd b/docs/html/resources/articles/qsb.jd deleted file mode 100644 index 01fb115819eb..000000000000 --- a/docs/html/resources/articles/qsb.jd +++ /dev/null @@ -1,169 +0,0 @@ -page.title=Quick Search Box -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -
    -
    - -

    See also

    -
      -
    1. Search
    2. -
    3. Searchable Dictionary -sample
    4. -
    - -
    -
    - -
    - -
    - -

    Starting with Android 1.6, the platform includes support for Quick Search -Box (QSB), a powerful, system-wide search framework. Quick Search Box makes it -possible for users to quickly and easily find what they're looking for, both on -their devices and on the web. It suggests content on your device as you type, -like apps, contacts, browser history, and music. It also offers results from the -web search suggestions, local business listings, and other info from -Google, such as stock quotes, weather, and flight status. All of this is -available right from the home screen, by tapping on Quick Search Box.

    - -

    What -we're most excited about with this new feature is the ability for you, -the developers, to leverage the QSB framework to provide quicker and -easier access to the content inside your apps. Your apps can provide -search suggestions that will surface to users in QSB alongside other -search results and suggestions. This makes it possible for users to -access your application's content from outside your application—for -example, from the home screen.

    - -

    Note: The code fragments in this document are -related to a sample app called Searchable Dictionary. The app is -available for Android 1.6 and later platforms.

    - -

    The story before now: searching within your app

    - -

    Platform releases versions previous to Android 1.6 already provided a mechanism -that let you expose search and search suggestions in your app, as described in -the docs for {@link android.app.SearchManager}. That mechanism has not changed -and requires the following two things in your -AndroidManifest.xml:

    - -

    1) In your <activity>, an intent filter, and a reference -to a searchable.xml file (described below):

    - -
    <intent-filter>
    -    <action android:name="android.intent.action.SEARCH" />
    -    <category android:name="android.intent.category.DEFAULT" />
    -</intent-filter>
    -            
    -<meta-data android:name="android.app.searchable"
    -       android:resource="@xml/searchable" />
    - -

    2) A content provider that can provide search suggestions according to the -URIs and column formats specified by the -Search Suggestions -section of the SearchManager docs:

    - -
    <!-- Provides search suggestions for words and their definitions. -->
    -<provider android:name="DictionaryProvider"
    -       android:authorities="dictionary"
    -       android:syncable="false" />
    - -

    In the searchable.xml file, you specify a few things about how -you want the search system to present search for your app, including the -authority of the content provider that provides suggestions for the user as they -type. Here's an example of the searchable.xml of an Android app -that provides search suggestions within its own activities:

    - -
    <searchable xmlns:android="http://schemas.android.com/apk/res/android"
    -        android:label="@string/search_label"
    -        android:searchSuggestAuthority="dictionary"
    -        android:searchSuggestIntentAction="android.intent.action.VIEW">
    -</searchable>
    - -

    Note that the android:searchSuggestAuthority attribute refers to -the authority of the content provider we declared in -AndroidManifest.xml.

    - -

    For more details on this, see the -Searchability Metadata -section of the of the SearchManager docs.

    - -

    Including your app in Quick Search Box

    - - - -

    In Android 1.6, we added a new attribute to the metadata for searchables: -android:includeInGlobalSearch. By specifying this as -"true" in your searchable.xml, you allow QSB to pick -up your search suggestion content provider and include its suggestions along -with the rest (if the user enables your suggestions from the system search -settings).

    - -

    You should also specify a string value for -android:searchSettingsDescription, which describes to users what -sorts of suggestions your app provides in the system settings for search.

    - -
    <searchable xmlns:android="http://schemas.android.com/apk/res/android"
    -       android:label="@string/search_label"
    -       android:searchSettingsDescription="@string/settings_description"
    -       android:includeInGlobalSearch="true"
    -       android:searchSuggestAuthority="dictionary"
    -       android:searchSuggestIntentAction="android.intent.action.VIEW">
    -</searchable>
    - -

    These new attributes are supported only in Android 1.6 and later.

    - -

    What to expect

    - -

    The -first and most important thing to note is that when a user installs an -app with a suggestion provider that participates in QSB, this new app -will not be enabled for QSB by default. The user can choose -to enable particular suggestion sources from the system settings for -search (by going to "Search" > "Searchable items" in settings).

    - -

    You -should consider how to handle this in your app. Perhaps show a notice -that instructs the user to visit system settings and enable your app's -suggestions.

    - -

    Once the user enables your searchable item, the -app's suggestions will have a chance to show up in QSB, most likely -under the "more results" section to begin with. As your app's -suggestions are chosen more frequently, they can move up in the list.

    - - - - -

    Shortcuts

    - -

    One -of our objectives with QSB is to make it faster for users to access the -things they access most often. One way we've done this is by -'shortcutting' some of the previously chosen search suggestions, so -they will be shown immediately as the user starts typing, instead of -waiting to query the content providers. Suggestions from your app may -be chosen as shortcuts when the user clicks on them.

    - -

    For dynamic suggestions that may wish to change their content (or become invalid) -in the future, you can provide a 'shortcut id'. This tells QSB to query -your suggestion provider for up-to-date content for a suggestion after -it has been displayed. For more details on how to manage shortcuts, see -the Shortcuts section -within the SearchManager docs.

    diff --git a/docs/html/resources/articles/service-api-changes-starting-with.jd b/docs/html/resources/articles/service-api-changes-starting-with.jd deleted file mode 100644 index 7bafd815e96e..000000000000 --- a/docs/html/resources/articles/service-api-changes-starting-with.jd +++ /dev/null @@ -1,177 +0,0 @@ -page.title=Service API changes starting with Android 2.0 -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -
    -
    - -

    See also

    -
      -
    1. Services
    2. -
    - -

    Key classes

    -
      -
    1. {@link android.app.Service}
    2. -
    - -
    -
    - -

    Watching developers use the Android platform the last year has shown a number of trouble areas in the Service API as well as growing issues in the ways services operate. As a result, Android 2.0 introduced a number of changes and improvements in this area for both developers and users.

    -

    The three main changes to be aware of are:

    -
      -
    • Service.setForeground() is now deprecated and in 2.0 does nothing.
    • -
    • There were many edge cases in the service lifecycle that made it very easy to accidentally leave a service running; new APIs in 2.0 make this much easier to deal with.
    • -
    • Android 2.0 also introduces a new UI for end users to monitor and manage the running services on their device.
    • -
    -

    Background on services

    -

    Before going into the details of 2.0, it may be useful to go over a quick summary of services. The Service API in Android is one of the key mechanisms for applications to do work in the background. Due to the way Android is designed, once an application is no longer visible to the user it is generally considered expendable and a candidate to be killed by the system if it ever needs memory elsewhere. The main way applications get around this is by starting a Service component, which explicitly tells the system that they are doing some valuable work and would prefer that the system not kill their process if it doesn't truly need to.

    -

    This is a very powerful facility but along with that power comes some responsibility: an actively running service is taking resources away from other things that can run (including inactive processes in the background that don't need to be initialized the next time the user visits them). It is thus important that developers take care when designing their services that they only run when truly needed and avoid any bugs where they may accidentally leave the service running for long durations.

    -

    Redesigning Service.setForeground()

    -

    During the final stabilization period of Android 1.6 we started to see more issues due to an increasing number of applications using the Service.setForeground() API when they shouldn't be. This is an API that we haven't advertised much because it should not be used by most applications and can be very hard on the system: it asks that the service's process be treated as in the foreground, essentially making it unkillable and thus more difficult for the system to recover from low memory situations.

    -

    At that point in 1.6 it was too late to make any significant changes to the behavior here, but in 2.0 we have done so: Service.setForeground() now does nothing. The API was always intended to be something a service would do in conjunction with putting up an ongoing notification for the user; by saying you are in the foreground, the user should be "aware" that the service is running in some way and know how to stop it. Thus in place of the old API Andriod 2.0 introduces two new APIs that require a notification go along with being in the foreground:

    -
    -public final void startForeground(int id, Notification notification);
    -public final void stopForeground(boolean removeNotification);
    -
    -

    This also not coincidentally makes it much easier to manage the notification state along with the service, since the system can now guarantee that there is always a notification while the service is in the foreground, and that the notification goes away whenever the service does.

    -

    Many developers will want to write a service that works on older platforms as well as 2.0 and later; this can be accomplished by using something like the following code to selectively call the new APIs when they are available.

    -
    -private static final Class[] mStartForegroundSignature = new Class[] {
    -    int.class, Notification.class};
    -private static final Class[] mStopForegroundSignature = new Class[] {
    -    boolean.class};
    -
    -private NotificationManager mNM;
    -private Method mStartForeground;
    -private Method mStopForeground;
    -private Object[] mStartForegroundArgs = new Object[2];
    -private Object[] mStopForegroundArgs = new Object[1];
    -
    -@Override
    -public void onCreate() {
    -    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    -    try {
    -        mStartForeground = getClass().getMethod("startForeground",
    -                mStartForegroundSignature);
    -        mStopForeground = getClass().getMethod("stopForeground",
    -                mStopForegroundSignature);
    -    } catch (NoSuchMethodException e) {
    -        // Running on an older platform.
    -        mStartForeground = mStopForeground = null;
    -    }
    -}
    -
    -/**
    - * This is a wrapper around the new startForeground method, using the older
    - * APIs if it is not available.
    - */
    -void startForegroundCompat(int id, Notification notification) {
    -    // If we have the new startForeground API, then use it.
    -    if (mStartForeground != null) {
    -        mStartForegroundArgs[0] = Integer.valueOf(id);
    -        mStartForegroundArgs[1] = notification;
    -        try {
    -            mStartForeground.invoke(this, mStartForegroundArgs);
    -        } catch (InvocationTargetException e) {
    -            // Should not happen.
    -            Log.w("MyApp", "Unable to invoke startForeground", e);
    -        } catch (IllegalAccessException e) {
    -            // Should not happen.
    -            Log.w("MyApp", "Unable to invoke startForeground", e);
    -        }
    -        return;
    -    }
    -    
    -    // Fall back on the old API.
    -    setForeground(true);
    -    mNM.notify(id, notification);
    -}
    -
    -/**
    - * This is a wrapper around the new stopForeground method, using the older
    - * APIs if it is not available.
    - */
    -void stopForegroundCompat(int id) {
    -    // If we have the new stopForeground API, then use it.
    -    if (mStopForeground != null) {
    -        mStopForegroundArgs[0] = Boolean.TRUE;
    -        try {
    -            mStopForeground.invoke(this, mStopForegroundArgs);
    -        } catch (InvocationTargetException e) {
    -            // Should not happen.
    -            Log.w("MyApp", "Unable to invoke stopForeground", e);
    -        } catch (IllegalAccessException e) {
    -            // Should not happen.
    -            Log.w("MyApp", "Unable to invoke stopForeground", e);
    -        }
    -        return;
    -    }
    -    
    -    // Fall back on the old API.  Note to cancel BEFORE changing the
    -    // foreground state, since we could be killed at that point.
    -    mNM.cancel(id);
    -    setForeground(false);
    -}
    -
    -

    Service lifecycle changes

    -

    Another situation we were increasingly seeing in 1.6 was that, even ignoring the services that inappropriately make themselves foreground, we had a growing number of devices with a large number of services running in the background all fighting each other over the available memory.

    -

    Part of this problem is services that are running more than they should or there simply being too much stuff trying to be done on the device. However, we also found many issues in the interaction between services and the platform that made it easy for an application to leave a service running even when it is trying to do the right thing. Consider this typical scenario:

    -
      -
    1. An application calls startService().
    2. -
    3. That service gets onCreate(), onStart(), and then spawns a background thread to do some work.
    4. -
    5. The system is tight on memory, so has to kill the currently running service.
    6. -
    7. Later when memory is free, the service is restarted, and gets onCreate() called but not onStart() because there has not been another call to startService() with a new Intent command to send it.
    8. -
    -

    Now the service will sit there created, not realizing it used to be doing some work, and so not knowing it should stop itself at some point.

    -

    To address this, in Android 2.0 Service.onStart() as been deprecated (though still exists and operates as it used to in previous versions of the platform). It is replaced with a new {@link android.app.Service#onStartCommand(android.content.Intent, int, int)} callback that allows the service to better control how the system should manage it. The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

    -
      -
    • {@link android.app.Service#START_STICKY} is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.
    • -
    • {@link android.app.Service#START_NOT_STICKY} says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
    • -
    • {@link android.app.Service#START_REDELIVER_INTENT} is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.
    • -
    -

    For compatibility with existing applications, the default return code for applications that are targeting an earlier version of the platform is a special {@link android.app.Service#START_STICKY_COMPATIBILITY} code that provides the old behavior of not calling onStart() with a null intent. Once you start targeting API version 5 or later, the default mode is START_STICKY and you must be prepared to deal with onStart() or onStartCommand() being called with a null Intent.

    -

    You can also easily write a Service that uses both the old and new APIs, depending on the platform. All you need to do is compile against the 2.0 SDK with this code:

    -
    -// This is the old onStart method that will be called on the pre-2.0
    -// platform.  On 2.0 or later we override onStartCommand() so this
    -// method will not be called.
    -@Override
    -public void onStart(Intent intent, int startId) {
    -    handleStart(intent, startId);
    -}
    -
    -@Override
    -public int onStartCommand(Intent intent, int flags, int startId) {
    -    handleStart(intent, startId);
    -    return START_NOT_STICKY;
    -}
    -
    -void handleStart(Intent intent, int startId) {
    -    // do work
    -}
    -
    -

    New "running services" user interface

    -

    Our final issue to address is the case where there are simply too many service running in the amount of memory available on a device. This may be due to bugs or design flaws in installed applications, or the user simply trying to do too much. Historically users have had no visibility into what is going on at this level in the system, but it has become important to expose this, at least for lower-end devices, as the use of services has had an increasing impact on the user experience.

    -

    To help address this, Android 2.0 introduces a new "Running Services" activity available from the Application system settings. When brought up, it looks something like this:

    -Running Services -

    The main content is a list of all running services that may be of interest to the user, organized by the processes they run in. In the example here, we see three services:

    -
      -
    • GTalkService is part of the standard Google application suit; it is running in Google's "gapps" process, which currently consumes 6.8MB. It has been started for 3 hours 55 minutes, which on this device is the time from when it was first booted.
    • -
    • ActivityService is part of the Phonebook app, and its process consumes 4MB. This also has been running since boot.
    • -
    • SoftKeyboard is a third party input method. It has been running since I switched to it, about 4 minutes ago.
    • -
    -

    The user can tap on any of these services to control it; for normal services that are running because they were explicitly started, this will present a dialog allowing the user to explicitly stop it:

    -Stop Service -

    Some other services, like the input method, are running for other reasons. For these, tapping on the service will go to the corresponding UI to manage it (in this case the system's input settings).

    -

    Finally, along the bottom of the screen are some obscure numbers. If you know how to interpret them, this gives you a lot of information on the memory status of your device:

    -
      -
    • Avail: 38MB+114MB in 25 says that the device has 38MB of completely free (or likely used for unrequired caches) memory, and has another 114MB of available memory in 25 background processes it can kill at any time.
    • -
    • Other: 32MB in 3 says that the device has 32MB of unavailable memory in 3 unkillable processes (that is, processes that are currently considered to be foreground and must be kept running)
    • -
    -

    For most users, this new user interface should be a much more effective way to manage the background applications on their device than the existing "task killer" applications. In the vast majority of cases the reason for a slow running device is too many services trying to run. This prevents the system from being able to run any background processes (which speed up app switching), and ultimately can result in thrashing through the services when not even they can all be kept running. The Running Services UI is intended to provide very specific information about the services that are running, to help make a good decision about what should be stopped. It also does not use the API to force stop an application, which can unintentionally break applications in numerous ways.

    -

    For developers, this is an important tool to ensure your services are well behaved. As you develop your app, be sure to keep an eye on Running Services to ensure that you are not accidentally leaving your services running when they shouldn't be. You should also now keep in mind that users may freely stop any of your services as they wish, without your control, and account for that.

    -

    Android's Services are a very powerful tool, but one of the main and subtle ways that application developers can harm the overall experience a user has with their phone.

    diff --git a/docs/html/resources/articles/speech-input.jd b/docs/html/resources/articles/speech-input.jd deleted file mode 100644 index 2f9cd69d4e58..000000000000 --- a/docs/html/resources/articles/speech-input.jd +++ /dev/null @@ -1,94 +0,0 @@ -page.title=Speech Input -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    People love their mobile phones because they can stay in touch wherever they -are. That means not just talking, but e-mailing, texting, microblogging, and so -on.

    - -

    Speech input adds another dimension to staying in touch. -Google's Voice Search application, which is pre-installed on many Android devices -and available on Google Play, provides powerful features like "search by voice" -and Voice Actions like "Navigate to." Further -enhancing the voice experience, Android 2.1 introduces a -voice-enabled keyboard, which makes it even easier -to stay connected. Now you can dictate your message instead of typing it. Just -tap the new microphone button on the keyboard, and you can speak in just about -any context in which you would normally type.

    - -

    We believe speech can -fundamentally change the mobile experience. We would like to invite every -Android application developer to consider integrating speech input capabilities -via the Android SDK. One of our favorite apps on Google Play that integrates -speech input is Handcent SMS, -because you can dictate a reply to any SMS with a -quick tap on the SMS popup window. Here is Speech input integrated into -Handcent SMS:

    - - - - -

    The Android SDK makes it easy to integrate speech input directly into your -own application. Just copy and paste from this sample -application to get -started. The sample application first verifies that the target device is able -to recognize speech input:

    -
    -// Check to see if a recognition activity is present
    -PackageManager pm = getPackageManager();
    -List activities = pm.queryIntentActivities(
    -  new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    -if (activities.size() != 0) {
    -  speakButton.setOnClickListener(this);
    -} else {
    -  speakButton.setEnabled(false);
    -  speakButton.setText("Recognizer not present");
    -}
    -
    -

    -The sample application then uses {@link -android.app.Activity#startActivityForResult(android.content.Intent, int) -startActivityForResult()} to broadcast an intent that requests voice -recognition, including an extra parameter that specifies one of two language -models. The voice recognition application that handles the intent processes the -voice input, then passes the recognized string back to your application by -calling the {@link android.app.Activity#onActivityResult(int, int, -android.content.Intent) onActivityResult()} callback.

    - - -

    Android is an open platform, so your application can potentially make -use of any speech recognition service on the device that's registered to receive -a {@link android.speech.RecognizerIntent}. Google's Voice Search application, -which is pre-installed on -many Android devices, responds to a RecognizerIntent by displaying the -"Speak -now" dialog and streaming audio to Google's servers -- the same servers used -when a user taps the microphone button on the search widget or the voice-enabled -keyboard. You can check whether Voice Search is installed in -Settings > Applications > Manage applications.

    - -

    One important tip: for speech input to be as accurate as possible, it's -helpful to have an idea of what words are likely to be spoken. While a message -like "Mom, I'm writing you this message with my voice!" might be appropriate for -an email or SMS message, you're probably more likely to say something like -"weather in Mountain View" if you're using Google Search. You can make sure your -users have the best experience possible by requesting the appropriate -language model: {@link -android.speech.RecognizerIntent#LANGUAGE_MODEL_FREE_FORM free_form} for -dictation, or {@link android.speech.RecognizerIntent#LANGUAGE_MODEL_WEB_SEARCH -web_search} for shorter, search-like phrases. We developed the "free form" -model to improve dictation accuracy for the voice keyboard, -while the "web search" model is used when users want to search by voice.

    - -

    Google's servers support many languages for voice input, with more arriving -regularly. You can use the -{@link android.speech.RecognizerIntent#ACTION_GET_LANGUAGE_DETAILS} -broadcast intent to query for the list of supported languages. -The web search model is available for all languages, while the free-form model -may not be optimized for all languages. As we work hard to support more models in -more languages, and to improve the accuracy of the speech recognition technology -we use in our products, Android developers who integrate speech capabilities -directly into their applications can reap the benefits as well.

    diff --git a/docs/html/resources/articles/spell-checker-framework.jd b/docs/html/resources/articles/spell-checker-framework.jd deleted file mode 100644 index 8d57b4eb09cd..000000000000 --- a/docs/html/resources/articles/spell-checker-framework.jd +++ /dev/null @@ -1,236 +0,0 @@ -page.title=Using the Spell Checker Framework -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body -
    -
    -

    In This Document

    -
      -
    1. - Spell Check Lifecycle -
    2. -
    3. - Implementing a Spell Checker Service -
    4. -
    5. - Implementing a Spell Checker Client -
    6. -
    -

    See also

    -
      -
    1. - - Spell Checker Service sample app -
    2. -
    3. - - Spell Checker Client sample app -
    4. -
    -
    -
    - -

    - The Android platform offers a spell checker framework that lets you implement - and access spell checking in your application. The framework is one of the - Text Service APIs offered by the Android platform. -

    -

    - To use the framework in your app, you create a special type of Android service that - generates a spell checker session object. Based on text you provide, - the session object returns spelling suggestions generated by the spell checker. -

    -

    Spell Checker Lifecycle

    -

    - The following diagram shows the lifecycle of the spell checker service: -

    - -

    - Figure 1. The spell checker service lifecycle. -

    -

    - To initiate spell checking, your app starts its implementation of the spell checker - service. Clients in your app, such as activities or individual UI elements, request a - spell checker session from the service, then use the session to get suggestions for text. - As a client terminates its operation, it closes its spell checker session. If necessary, your - app can shut down the spell checker service at any time. -

    -

    Implementing a Spell Checker Service

    -

    - To use the spell checker framework in your app, add a spell checker service component including - the session object definition. You can also add to your app an optional activity that - controls settings. You must also add an XML metadata file that describes - the spell checker service, and add the appropriate elements to your manifest file. -

    -

    Spell checker classes

    -

    - Define the service and session object with the following classes: -

    -
    -
    - A subclass of {@link android.service.textservice.SpellCheckerService} -
    -
    - The {@link android.service.textservice.SpellCheckerService} implements both the - {@link android.app.Service} class and the spell checker framework interface. Within your - subclass, you must implement the following method: -
    -
    {@link android.service.textservice.SpellCheckerService#createSession()}
    -
    - A factory method that returns a - {@link android.service.textservice.SpellCheckerService.Session} object to a - client that wants to do spell checking. -
    -
    -

    - See the - - Spell Checker Service sample app to learn more about implementing this class. -

    -
    -
    - An implementation of {@link android.service.textservice.SpellCheckerService.Session} -
    -
    - An object that the spell checker service provides to clients, to let them pass text to - the spell checker and receive suggestions. Within this class, you must implement the - following methods: -
    -
    - {@link android.service.textservice.SpellCheckerService.Session#onCreate()} -
    -
    - Called by the system in response to - {@link android.service.textservice.SpellCheckerService#createSession()}. In this - method, you can initialize the - {@link android.service.textservice.SpellCheckerService.Session} object based on - the current locale and so forth. -
    -
    - {@link android.service.textservice.SpellCheckerService.Session#onGetSuggestions(TextInfo, int) - onGetSuggestions()} -
    -
    - Does the actual spell checking. This method returns an object containing - suggestions for the text passed to it. -
    -
    -

    - Optionally, you can implement - {@link android.service.textservice.SpellCheckerService.Session#onCancel()}, which - handles requests to cancel spell checking, or -{@link android.service.textservice.SpellCheckerService.Session#onGetSuggestionsMultiple(TextInfo[], int, boolean) -onGetSuggestionsMultiple()}, which handles batches of suggestion requests, or both. -

    -

    - See the - - Spell Checker Client sample app to learn more about implementing this class. -

    -
    -
    -

    - Note: You must implement all aspects of spell checking as asynchronous and - thread-safe. A spell checker may be called simultaneously by different threads running on - different cores. The {@link android.service.textservice.SpellCheckerService} and - {@link android.service.textservice.SpellCheckerService.Session} take care of this - automatically. -

    -

    Spell checker manifest and metadata

    -

    - In addition to code, you need to provide the appropriate manifest file and a metadata file for - the spell checker. -

    -

    - The manifest file defines the application, the service, and the activity for controlling - settings, as shown in the following snippet: -

    -
    -<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    -    package="com.example.android.samplespellcheckerservice" >
    -    <application
    -        android:label="@string/app_name" >
    -        <service
    -            android:label="@string/app_name"
    -            android:name=".SampleSpellCheckerService"
    -            android:permission="android.permission.BIND_TEXT_SERVICE" >
    -            <intent-filter >
    -                <action android:name="android.service.textservice.SpellCheckerService" />
    -            </intent-filter>
    -
    -            <meta-data
    -                android:name="android.view.textservice.scs"
    -                android:resource="@xml/spellchecker" />
    -        </service>
    -
    -        <activity
    -            android:label="@string/sample_settings"
    -            android:name="SpellCheckerSettingsActivity" >
    -            <intent-filter >
    -                <action android:name="android.intent.action.MAIN" />
    -            </intent-filter>
    -        </activity>
    -    </application>
    -</manifest>
    -
    -

    - Notice that components that want to use the service must request the permission - {@link android.Manifest.permission#BIND_TEXT_SERVICE} to ensure that only the system binds to - the service. The service's definition also specifies the spellchecker.xml metadata - file, which is described in the next section. -

    -

    - The metadata file spellchecker.xml contains the following XML: -

    -
    -<spell-checker xmlns:android="http://schemas.android.com/apk/res/android"
    -        android:label="@string/spellchecker_name"
    -        android:settingsActivity="com.example.SpellCheckerSettingsActivity">
    -    <subtype
    -            android:label="@string/subtype_generic"
    -            android:subtypeLocale="en”
    -    />
    -    <subtype
    -            android:label="@string/subtype_generic"
    -            android:subtypeLocale="fr”
    -    />
    -</spell-checker>
    -
    -

    - The metadata specifies the activity that the spell checker uses for controlling settings. It - also defines subtypes for the spell checker; in this case, the subtypes define locales that - the spell checker can handle. -

    - - - -

    Accessing the Spell Checker Service from a Client

    -

    - Applications that use {@link android.widget.TextView} views automatically benefit from spell - checking, because {@link android.widget.TextView} automatically uses a spell checker. The - following screenshots show this: -

    - -
    - -

    - Figure 2. Spell checking in TextView. -

    -

    - However, you may want to interact directly with a spell checker service in other cases as well. - The following diagram shows the flow of control for interacting with a spell checker service: -

    - -

    - Figure 3. Interacting with a spell checker service. -

    -

    - The - Spell Checker Client sample app shows how to interact with a spell checker service. The - LatinIME input method editor in the Android Open Source Project also contains an example of - spell checking. -

    \ No newline at end of file diff --git a/docs/html/resources/articles/timed-ui-updates.jd b/docs/html/resources/articles/timed-ui-updates.jd deleted file mode 100644 index 7a0804f6fb94..000000000000 --- a/docs/html/resources/articles/timed-ui-updates.jd +++ /dev/null @@ -1,151 +0,0 @@ -page.title=Updating the UI from a Timer -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - - -

    Background: While developing my first useful -(though small) application for Android, which was a port of an existing -utility I use when podcasting, I needed a way of updating a clock -displayed on the UI at regular intervals, but in a lightweight and CPU -efficient way.

    - -

    Problem: In the original application I used -java.util.Timer to update the clock, but that class is not such a good -choice on Android. Using a Timer introduces a new thread into the -application for a relatively minor reason. Thinking in terms of mobile -applications often means re-considering choices that you might make -differently for a desktop application with relatively richer resources -at its disposal. We would like to find a more efficient way of updating -that clock.

    - -

    The Application: The original application is a -Java Swing and SE application. It is like a stopwatch with a lap timer -that we use when recording podcasts; when you start the recording, you -start the stopwatch. Then for every mistake that someone makes, you hit -the flub button. At the end you can save out the bookmarked mistakes -which can be loaded into the wonderful -Audacity -audio editor as a labels track. You can then see where all of the mistakes -are in the recording and edit them out.

    - -

    The article describing it is: http://www.developer.com/java/ent/print.php/3589961

    - -

    In the original version, the timer code looked like this:

    - -
    class UpdateTimeTask extends TimerTask {
    -   public void run() {
    -       long millis = System.currentTimeMillis() - startTime;
    -       int seconds = (int) (millis / 1000);
    -       int minutes = seconds / 60;
    -       seconds     = seconds % 60;
    -
    -       timeLabel.setText(String.format("%d:%02d", minutes, seconds));
    -   }
    -}

    And in the event listener to start this update, the following Timer() instance is used: -

    if(startTime == 0L) {
    -   startTime = evt.getWhen();
    -   timer = new Timer();
    -   timer.schedule(new UpdateTimeTask(), 100, 200);
    -}
    - -

    In particular, note the 100, 200 parameters. The first parameter -means wait 100 ms before running the clock update task the first time. -The second means repeat every 200ms after that, until stopped. 200 ms -should not be too noticeable if the second resolution happens to fall -close to or on the update. If the resolution was a second, you could -find the clock sometimes not updating for close to 2 seconds, or -possibly skipping a second in the counting, it would look odd).

    - -

    When I ported the application to use the Android SDKs, this code -actually compiled in Eclipse, but failed with a runtime error because -the Timer() class was not available at runtime (fortunately, this was -easy to figure out from the error messages). On a related note, the -String.format method was also not available, so the eventual solution -uses a quick hack to format the seconds nicely as you will see.

    - -

    Fortunately, the role of Timer can be replaced by the -android.os.Handler class, with a few tweaks. To set it up from an event -listener:

    - -
    private Handler mHandler = new Handler();
    -
    -...
    -
    -OnClickListener mStartListener = new OnClickListener() {
    -   public void onClick(View v) {
    -       if (mStartTime == 0L) {
    -            mStartTime = System.currentTimeMillis();
    -            mHandler.removeCallbacks(mUpdateTimeTask);
    -            mHandler.postDelayed(mUpdateTimeTask, 100);
    -       }
    -   }
    -};
    - -

    A couple of things to take note of here. First, the event doesn't -have a .getWhen() method on it, which we handily used to set the start -time for the timer. Instead, we grab the System.currentTimeMillis(). -Also, the Handler.postDelayed() method only takes one time parameter, -it doesn't have a "repeating" field. In this case we are saying to the -Handler "call mUpdateTimeTask() after 100ms", a sort of fire and forget -one time shot. We also remove any existing callbacks to the handler -before adding the new handler, to make absolutely sure we don't get -more callback events than we want.

    - -

    But we want it to repeat, until we tell it to stop. To do this, just -put another postDelayed at the tail of the mUpdateTimeTask run() -method. Note also that Handler requires an implementation of Runnable, -so we change mUpdateTimeTask to implement that rather than extending -TimerTask. The new clock updater, with all these changes, looks like -this:

    - -
    private Runnable mUpdateTimeTask = new Runnable() {
    -   public void run() {
    -       final long start = mStartTime;
    -       long millis = SystemClock.uptimeMillis() - start;
    -       int seconds = (int) (millis / 1000);
    -       int minutes = seconds / 60;
    -       seconds     = seconds % 60;
    -
    -       if (seconds < 10) {
    -           mTimeLabel.setText("" + minutes + ":0" + seconds);
    -       } else {
    -           mTimeLabel.setText("" + minutes + ":" + seconds);            
    -       }
    -     
    -       mHandler.postAtTime(this,
    -               start + (((minutes * 60) + seconds + 1) * 1000));
    -   }
    -};
    - -

    and can be defined as a class member field.

    - -

    The if statement is just a way to make sure the label is set to -10:06 instead of 10:6 when the seconds modulo 60 are less than 10 -(hopefully String.format() will eventually be available). At the end of -the clock update, the task sets up another call to itself from the -Handler, but instead of a hand-wavy 200ms before the update, we can -schedule it to happen at a particular wall-clock time — the line: start -+ (((minutes * 60) + seconds + 1) * 1000) does this.

    - -

    All we need now is a way to stop the timer when the stop button -is pressed. Another button listener defined like this:

    - -
    OnClickListener mStopListener = new OnClickListener() {
    -   public void onClick(View v) {
    -       mHandler.removeCallbacks(mUpdateTimeTask);
    -   }
    -};
    - -

    will make sure that the next callback is removed when the stop button -is pressed, thus interrupting the tail iteration.

    - -

    Handler is actually a better choice than Timer for another reason -too. The Handler runs the update code as a part of your main thread, -avoiding the overhead of a second thread and also making for easy -access to the View hierarchy used for the user interface. Just remember -to keep such tasks small and light to avoid slowing down the user -experience.

    - - diff --git a/docs/html/resources/articles/touch-mode.jd b/docs/html/resources/articles/touch-mode.jd deleted file mode 100644 index 5eae9b9ea1a7..000000000000 --- a/docs/html/resources/articles/touch-mode.jd +++ /dev/null @@ -1,140 +0,0 @@ -page.title=Touch Mode -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    This article explains the touch mode, one of the most -important principles of Android's UI toolkit.

    - -

    The touch mode is a state of the view hierarchy that depends solely on the -user interaction with the phone. By itself, the touch mode is something very -easy to understand as it simply indicates whether the last user interaction was -performed with the touch screen. For example, if you are using an -Android-powered device, selecting a widget with the trackball will take you out -of touch mode; however, if you touch a button on the screen with your finger, -you will enter touch mode. When the user is not in touch mode, we talk about the -trackball mode, navigation mode or keyboard navigation, so do not be surprised -if you encounter these terms.

    - -

    There is only one API directly related to touch mode, -{@link android.view.View#isInTouchMode() View.isInTouchMode()}.

    - -

    Sounds easy enough, right? Oddly enough, touch mode is deceivingly simple and -the consequences of entering touch mode are far greater than you might -think. Let's look at some of the reasons why.

    - -

    Touch Mode, Selection, and Focus

    - -

    Designing a UI toolkit for mobile devices is difficult because of the various -interaction mechanisms they provide. Some devices offer only 12 keys, some have -a touch screen, some require a stylus, some have both a touch screen and a -keyboard. Based on the hardware capabilities of the he user can interact with -your application using different mechanisms, so we had to think very hard about -all the possible issues that could arise. One issue led us to create the touch -mode.

    - -

    Imagine a simple application, ApiDemos -for example, that shows a list of text items. The user can freely -navigate through the list using the trackball but also, alternatively, scroll -and fling the list using the touch screen. The issue in this scenario is -how to handle the selection properly when the user manipulates the list -through the touch screen.

    - -

    In this case, if the user selects an item at the top of the list and then -flings the list towards the bottom, what should happen to the selection? Should -it remain on the item and scroll off the screen? What should happen if the user -then decided to move the selection with the trackball? Or worse, what should -happen if the user presses the trackball to act upon the currently selected -item, which is not shown on screen anymore?

    - -

    After careful consideration, we decided to remove the selection altogether, -when the user manipulates the UI through the touch screen.

    - -

    In touch mode, there is no focus and no selection. Any selected item in a -list of in a grid becomes unselected as soon as the user enters touch -mode. Similarly, any focused widgets become unfocused when the user -enters touch mode. The image below illustrates what happens when the -user touches a list after selecting an item with the trackball.

    - - - - -

    To -make things more natural for the user, the framework knows how to -resurrect the selection/focus whenever the user leaves touch mode. For -instance, in the example above, if the user were to use the trackball -again, the selection would reappear on the previously-selected item. -This is why some developers are confused when they create a custom view -and start receiving key events only after moving the trackball once: -their application is in touch mode, and they need to use the trackball -to exit touch mode and resurrect the focus.

    - -

    The relationship between touch mode, selection, and focus means you must not -rely on selection and/or focus to exist in your application. A very common -problem with new Android developers is to rely on -{@link android.widget.AdapterView#getSelectedItemPosition() ListView.getSelectedItemPosition()}. -In touch mode, this method will return -{@link android.widget.AdapterView#INVALID_POSITION INVALID_POSITION}. - You should instead use click listeners (see -{@link android.widget.AdapterView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)}) -or the choice mode (see -{@link android.widget.ListView#setChoiceMode(int)}).

    - -

    Focusable in Touch Mode

    - -

    In general, focus doesn't exist in touch mode. However, focus can exist in -touch mode in a very special way called focusable. This special mode -was created for widgets that receive text input, such as -{@link android.widget.EditText} or, when filtering is enabled, -{@link android.widget.ListView}. The focusable mode is what lets the user enter text -inside a text field on the screen, without first selecting it with the trackball -or their finger.

    - -

    When a user -touches the screen, the application will enter touch mode if it wasn't -in touch mode already. What happens during the transition to -touch mode depends on what the user touched, and what currently has -focus. If the user touches a widget that is focusable in touch -mode, that widget will receive focus. Otherwise, any currently -focused widget will not retain focus unless it is focusable in touch -mode. For instance, in the picture below, when the user touches -the screen, the input text field receives the focus.

    - - - -

    Fousable in touch mode (see -{@link android.view.View#setFocusableInTouchMode(boolean) View.setFocusableInTouchMode}) - is a property that you can set yourself, either from code or from XML. -However, you should use it sparingly and only in very specific situations, -because it breaks consistency with the normal behavior of the Android UI. A game -is a good example of an application that could make good use of the focusable in -touch mode property. MapView, if used in fullscreen as in Google Maps, is -another good example of where you can use focusable in touch mode correctly.

    - -

    Below is another example of a focusable in touch mode widget. When the user -taps an AutoCompleteTextView suggestion with his finger, the focus -remains on the input text field:

    - - - - -

    Developers new to Android often think that focusable in touch mode is the -solution they need to "fix" the problem of "disappearing" selection/focus. We -really encourage you to think very hard before using it. If used incorrectly, it -can make your application behave differently from the rest of the system and -simply throw off the user's habits. The Android framework contains all the tools -you need to handle user interactions without using focusable in touch mode. For -example, instead of trying to make ListView always keep its -selection, simply use the appropriate choice mode, as shown in -{@link android.widget.ListView#setChoiceMode(int)}. - -

    Touch Mode Cheat Sheet

    - -

    Do:

    -
      -
    • Remain consistent with the core applications
    • Use the appropriate feature if you need persistent selection (radio button, check box, the ListView choice mode, etc.)
    • -
    • Use focusable in touch mode if you write a game
    • -
    - -

    Don't:

    -
    • Do not try to keep the focus or selection in touch mode
    diff --git a/docs/html/resources/articles/track-mem.jd b/docs/html/resources/articles/track-mem.jd deleted file mode 100644 index c4184b5764aa..000000000000 --- a/docs/html/resources/articles/track-mem.jd +++ /dev/null @@ -1,64 +0,0 @@ -page.title=Tracking Memory Allocations -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Writing efficient mobile applications is not always straightforward. In -particular, Android applications rely on automatic memory management handled by -Dalvik's garbage collector, which can sometimes cause performance issues if you -are not careful with memory allocations.

    - -

    In a performance-sensitive code path, such as the layout or drawing method of -a view or the logic code of a game, any allocation comes at a price. After too -many allocations, the garbage collector will kick in and stop your application -to let it free some memory. Most of the time, garbage collections happen fast -enough for you not to notice. However, if a collection happens while you are -scrolling through a list of items or while you are trying to defeat a foe in a -game, you may suddenly see a drop in performance/responsiveness of the -application. It's not unusual for a garbage collection to take 100 to 200 ms. -For comparison, a smooth animation needs to draw each frame in 16 to 33 ms. If -the animation is suddenly interrupted for 10 frames, you can be certain that -your users will notice.

    - -

    Most of the time, garbage collection occurs because of tons of small, -short-lived objects and some garbage collectors, like generational garbage -collectors, can optimize the collection of these objects so that the application -does not get interrupted too often. The Android garbage collector is -unfortunately not able to perform such optimizations and the creation of -short-lived objects in performance critical code paths is thus very costly for -your application.

    - -

    To help you avoid frequent garbage collections, the Android SDK ships with a -very useful tool called allocation tracker. This tool is part of DDMS, -which you must have already used for debugging purposes. To start using the -allocation tracker, you must first launch the standalone version of DDMS, which -can be found in the tools/ directory of the SDK. The version of -DDMS included in the Eclipse plugin does not offer you ability to use the -allocation tracker yet.

    - -

    Once DDMS is running, simply select your application process and then click -the Allocation Tracker tab. In the new view, click Start -Tracking and then use your application to make it execute the code paths -you want to analyze. When you are ready, click Get Allocations. A list -of allocated objects will be shown in the first table. By clicking on a line you -can see, in the second table, the stack trace that led to the allocation. Not -only you will know what type of object was allocated, but also in which thread, -in which class, in which file and at which line. The following screenshot shows -the allocations performed by Shelves while scrolling a -ListView.

    - - - - - - -

    Even though it is not necessary — and sometimes not possible — to -remove all allocations for your performance critical code paths. the allocation -tracker will help you identify important issues in your code. For instance, a -common mistake I have seen in many applications is to create a new -Paint object on every draw. Moving the paint into an instance field -is a simple fix that helps performance a lot. I highly encourage you to peruse -the Android source code to see how we -reduce allocations in performance-critical code paths. You will also thus -discover the APIs Android provide to help you reuse objects.

    diff --git a/docs/html/resources/articles/tts.jd b/docs/html/resources/articles/tts.jd deleted file mode 100644 index 929d08438f7e..000000000000 --- a/docs/html/resources/articles/tts.jd +++ /dev/null @@ -1,243 +0,0 @@ -page.title=Using Text-to-Speech -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Starting with Android 1.6 (API Level 4), the Android platform includes a new -Text-to-Speech (TTS) capability. Also known as "speech synthesis", TTS enables -your Android device to "speak" text of different languages.

    - -

    Before we explain how to use the TTS API itself, let's first review a few -aspects of the engine that will be important to your TTS-enabled application. We -will then show how to make your Android application talk and how to configure -the way it speaks.

    - -

    Languages and resources

    - -

    The TTS engine that ships with the Android platform supports a number of -languages: English, French, German, Italian and Spanish. Also, depending on -which side of the Atlantic you are on, American and British accents for English -are both supported.

    - -

    The TTS engine needs to know which language to speak, as a word like "Paris", -for example, is pronounced differently in French and English. So the voice and -dictionary are language-specific resources that need to be loaded before the -engine can start to speak.

    - -

    Although all Android-powered devices that support the TTS functionality ship -with the engine, some devices have limited storage and may lack the -language-specific resource files. If a user wants to install those resources, -the TTS API enables an application to query the platform for the availability of -language files and can initiate their download and installation. So upon -creating your activity, a good first step is to check for the presence of the -TTS resources with the corresponding intent:

    - -
    Intent checkIntent = new Intent();
    -checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    -startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    - -

    A successful check will be marked by a CHECK_VOICE_DATA_PASS -result code, indicating this device is ready to speak, after the creation of -our -{@link android.speech.tts.TextToSpeech} object. If not, we need to let the user -know to install the data that's required for the device to become a -multi-lingual talking machine! Downloading and installing the data is -accomplished by firing off the ACTION_INSTALL_TTS_DATA intent, which will take -the user to Google Play, and will let her/him initiate the download. -Installation of the data will happen automatically once the download completes. -Here is an example of what your implementation of -onActivityResult() would look like:

    - -
    private TextToSpeech mTts;
    -protected void onActivityResult(
    -        int requestCode, int resultCode, Intent data) {
    -    if (requestCode == MY_DATA_CHECK_CODE) {
    -        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
    -            // success, create the TTS instance
    -            mTts = new TextToSpeech(this, this);
    -        } else {
    -            // missing data, install it
    -            Intent installIntent = new Intent();
    -            installIntent.setAction(
    -                TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
    -            startActivity(installIntent);
    -        }
    -    }
    -}
    - -

    In the constructor of the TextToSpeech instance we pass a -reference to the Context to be used (here the current Activity), -and to an OnInitListener (here our Activity as well). This listener -enables our application to be notified when the Text-To-Speech engine is fully -loaded, so we can start configuring it and using it.

    - -

    Languages and Locale

    - -

    At Google I/O 2009, we showed an example of TTS where it was used to speak the result of a -translation from and to one of the 5 languages the Android TTS engine currently -supports. Loading a language is as simple as calling for instance:

    - -
    mTts.setLanguage(Locale.US);

    to load and set the language to -English, as spoken in the country "US". A locale is the preferred way to specify -a language because it accounts for the fact that the same language can vary from -one country to another. To query whether a specific Locale is supported, you can -use isLanguageAvailable(), which returns the level of support for -the given Locale. For instance the calls:

    - -
    mTts.isLanguageAvailable(Locale.UK))
    -mTts.isLanguageAvailable(Locale.FRANCE))
    -mTts.isLanguageAvailable(new Locale("spa", "ESP")))
    - -

    will return TextToSpeech.LANG_COUNTRY_AVAILABLE to indicate that the language -AND country as described by the Locale parameter are supported (and the data is -correctly installed). But the calls:

    - -
    mTts.isLanguageAvailable(Locale.CANADA_FRENCH))
    -mTts.isLanguageAvailable(new Locale("spa"))
    - -

    will return TextToSpeech.LANG_AVAILABLE. In the first example, -French is supported, but not the given country. And in the second, only the -language was specified for the Locale, so that's what the match was made on.

    - -

    Also note that besides the ACTION_CHECK_TTS_DATA intent to check -the availability of the TTS data, you can also use -isLanguageAvailable() once you have created your -TextToSpeech instance, which will return -TextToSpeech.LANG_MISSING_DATA if the required resources are not -installed for the queried language.

    - -

    Making the engine speak an Italian string while the engine is set to the -French language will produce some pretty interesting results, but it will -not exactly be something your user would understand So try to match the -language of your application's content and the language that you loaded in your -TextToSpeech instance. Also if you are using -Locale.getDefault() to query the current Locale, make sure that at -least the default language is supported.

    - -

    Making your application speak

    - -

    Now that our TextToSpeech instance is properly initialized and -configured, we can start to make your application speak. The simplest way to do -so is to use the speak() method. Let's iterate on the following -example to make a talking alarm clock:

    - -
    String myText1 = "Did you sleep well?";
    -String myText2 = "I hope so, because it's time to wake up.";
    -mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
    -mTts.speak(myText2, TextToSpeech.QUEUE_ADD, null);
    - -

    The TTS engine manages a global queue of all the entries to synthesize, which -are also known as "utterances". Each TextToSpeech instance can -manage its own queue in order to control which utterance will interrupt the -current one and which one is simply queued. Here the first speak() -request would interrupt whatever was currently being synthesized: the queue is -flushed and the new utterance is queued, which places it at the head of the -queue. The second utterance is queued and will be played after -myText1 has completed.

    - -

    Using optional parameters to change the playback stream type

    - -

    On Android, each audio stream that is played is associated with one stream -type, as defined in -{@link android.media.AudioManager android.media.AudioManager}. For a talking -alarm clock, we would like our text to be played on the -AudioManager.STREAM_ALARM stream type so that it respects the alarm -settings the user has chosen on the device. The last parameter of the speak() -method allows you to pass to the TTS engine optional parameters, specified as -key/value pairs in a HashMap. Let's use that mechanism to change the stream type -of our utterances:

    - -
    HashMap<String, String> myHashAlarm = new HashMap();
    -myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
    -        String.valueOf(AudioManager.STREAM_ALARM));
    -mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
    -mTts.speak(myText2, TextToSpeech.QUEUE_ADD, myHashAlarm);
    - -

    Using optional parameters for playback completion callbacks

    - -

    Note that speak() calls are asynchronous, so they will return -well before the text is done being synthesized and played by Android, regardless -of the use of QUEUE_FLUSH or QUEUE_ADD. But you might -need to know when a particular utterance is done playing. For instance you might -want to start playing an annoying music after myText2 has finished -synthesizing (remember, we're trying to wake up the user). We will again use an -optional parameter, this time to tag our utterance as one we want to identify. -We also need to make sure our activity implements the -TextToSpeech.OnUtteranceCompletedListener interface:

    - -
    mTts.setOnUtteranceCompletedListener(this);
    -myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
    -        String.valueOf(AudioManager.STREAM_ALARM));
    -mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
    -myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
    -        "end of wakeup message ID");
    -// myHashAlarm now contains two optional parameters
    -mTts.speak(myText2, TextToSpeech.QUEUE_ADD, myHashAlarm);
    - -

    And the Activity gets notified of the completion in the implementation -of the listener:

    - -
    public void onUtteranceCompleted(String uttId) {
    -    if (uttId == "end of wakeup message ID") {
    -        playAnnoyingMusic();
    -    } 
    -}
    - -

    File rendering and playback

    - -

    While the speak() method is used to make Android speak the text -right away, there are cases where you would want the result of the synthesis to -be recorded in an audio file instead. This would be the case if, for instance, -there is text your application will speak often; you could avoid the synthesis -CPU-overhead by rendering only once to a file, and then playing back that audio -file whenever needed. Just like for speak(), you can use an -optional utterance identifier to be notified on the completion of the synthesis -to the file:

    - -
    HashMap<String, String> myHashRender = new HashMap();
    -String wakeUpText = "Are you up yet?";
    -String destFileName = "/sdcard/myAppCache/wakeUp.wav";
    -myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, wakeUpText);
    -mTts.synthesizeToFile(wakuUpText, myHashRender, destFileName);
    - -

    Once you are notified of the synthesis completion, you can play the output -file just like any other audio resource with -{@link android.media.MediaPlayer android.media.MediaPlayer}.

    - -

    But the TextToSpeech class offers other ways of associating -audio resources with speech. So at this point we have a WAV file that contains -the result of the synthesis of "Wake up" in the previously selected language. We -can tell our TTS instance to associate the contents of the string "Wake up" with -an audio resource, which can be accessed through its path, or through the -package it's in, and its resource ID, using one of the two -addSpeech() methods:

    - -
    mTts.addSpeech(wakeUpText, destFileName);
    - -

    This way any call to speak() for the same string content as -wakeUpText will result in the playback of -destFileName. If the file is missing, then speak will behave as if -the audio file wasn't there, and will synthesize and play the given string. But -you can also take advantage of that feature to provide an option to the user to -customize how "Wake up" sounds, by recording their own version if they choose -to. Regardless of where that audio file comes from, you can still use the same -line in your Activity code to ask repeatedly "Are you up yet?":

    - -
    mTts.speak(wakeUpText, TextToSpeech.QUEUE_ADD, myHashAlarm);
    - -

    When not in use...

    The text-to-speech functionality relies on a -dedicated service shared across all applications that use that feature. When you -are done using TTS, be a good citizen and tell it "you won't be needing its -services anymore" by calling mTts.shutdown(), in your Activity -onDestroy() method for instance.

    - -

    Conclusion

    - -

    Android now talks, and so can your apps. Remember that in order for -synthesized speech to be intelligible, you need to match the language you select -to that of the text to synthesize. Text-to-speech can help you push your app in -new directions. Whether you use TTS to help users with disabilities, to enable -the use of your application while looking away from the screen, or simply to -make it cool, we hope you'll enjoy this new feature.

    \ No newline at end of file diff --git a/docs/html/resources/articles/ui-1.5.jd b/docs/html/resources/articles/ui-1.5.jd deleted file mode 100644 index 2edaa2e0e352..000000000000 --- a/docs/html/resources/articles/ui-1.5.jd +++ /dev/null @@ -1,50 +0,0 @@ -page.title=UI Framework Changes in Android 1.5 -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -

    Android 1.5 offers a different default look for -the Android UI framework, in relation to Android 1.0 and 1.1. The -screenshots below show the same activity (creating a new contact) on -Android 1.1 and Android 1.5:

    - - - -

    You -can see in this example that the buttons and checkboxes have a new -appearance. Even though these changes do not affect binary nor source -compatibility, they might still break the UI of your apps. As part of -the UI refresh, the minimum size of some of the widgets has changed. -For instance, Android 1.1 buttons have a minimum size of 44x48 pixels -whereas Android 1.5 buttons now have a minimum size of 24x48 pixels. -The image below compares the sizes of Android 1.1 buttons with Android -1.5 buttons:

    - - - -

    If you rely on the button's minimum size, then the layout of your application -may not be the same in Android 1.5 as it was in Android 1.1 because of this -change. This would happen for instance if you created a grid of buttons using -LinearLayout and relying on the minimum size yielded by -wrap_content to align the buttons properly:

    - - - -

    This layout could easily be fixed by using the -android:layout_weight attribute or by replacing the -LinearLayout containers with a TableLayout.

    - -

    This example is probably the worst-case UI issue you may encounter when -running your application on Android 1.5. Other changes introduced in Android -1.5, especially bug fixes in the layout views, may also impact your -application—especially if it is relying on faulty/buggy behavior of the UI -framework.

    - -

    If you encounter issues when running your application on Android 1.5, please -join us on the Android -developer groups or IRC so that we and the -Android community can help you fix your application.

    - -

    Happy coding!

    diff --git a/docs/html/resources/articles/ui-1.6.jd b/docs/html/resources/articles/ui-1.6.jd deleted file mode 100644 index b3238e3b0fc9..000000000000 --- a/docs/html/resources/articles/ui-1.6.jd +++ /dev/null @@ -1,132 +0,0 @@ -page.title=UI Framework Changes in Android 1.6 -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Android 1.6 introduces numerous enhancements and bug fixes in the UI -framework. This article highlights two improvements in particular: more flexible -and robust RelativeLayout and easier click listeners.

    - -

    More flexible, more robust RelativeLayout

    - -

    RelativeLayout is the most versatile layout offered by the Android UI toolkit -and can be successfully used to reduce the number of views created by your -applications. This layout used to suffer from various bugs and limitations, -sometimes making it difficult to use without having some knowledge of its -implementation. To make your life easier, Android 1.6 comes with a revamped -RelativeLayout.

    - -

    This new implementation not only fixes all known bugs in -RelativeLayout but also addresses its major limitation: the -fact that views had to be declared in a particular order. Consider the following -XML layout:

    - -
    <?xml version="1.0" encoding="utf-8"?>
    -
    -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:layout_width="fill_parent"
    -    android:layout_height="64dip"
    -    android:padding="6dip">
    -
    -    <TextView
    -        android:id="@+id/band"  
    -        android:layout_width="fill_parent" 
    -        android:layout_height="26dip" 
    -
    -        android:layout_below="@+id/track"
    -        android:layout_alignLeft="@id/track"
    -        android:layout_alignParentBottom="true"
    -
    -        android:gravity="top"
    -        android:text="The Airborne Toxic Event" />
    -
    -    <TextView
    -        android:id="@id/track"  
    -        android:layout_marginLeft="6dip"
    -        android:layout_width="fill_parent"
    -        android:layout_height="26dip"
    -
    -        android:layout_toRightOf="@+id/artwork"
    -
    -        android:textAppearance="?android:attr/textAppearanceMedium"
    -        android:gravity="bottom"
    -        android:text="Sometime Around Midnight" />
    -        
    -    <ImageView
    -        android:id="@id/artwork"
    -        android:layout_width="56dip"
    -        android:layout_height="56dip"
    -        android:layout_gravity="center_vertical"
    -
    -        android:src="@drawable/artwork" />
    -        
    -</RelativeLayout>
    - -

    This code builds a very simple layout—an image on the left with two lines of -text stacked vertically. This XML layout is perfectly fine and contains no -errors. Unfortunately, Android 1.5's RelativeLayout is incapable of rendering it -correctly, as shown in the screenshot below.

    - - - -

    The problem is that this layout uses forward references. For instance, the -"band" TextView is positioned below the "track" TextView but "track" is declared -after "band" and, in Android 1.5, RelativeLayout does not know how to handle -this case. Now look at the exact same layout running on Android 1.6:

    - - - -

    As you can see Android 1.6 is now better able to handle forward reference. -The result on screen is exactly what you would expect when writing the -layout.

    - -

    Easier click listeners

    - -

    Setting up a click listener on a button is very common task, but -it requires quite a bit of boilerplate code:

    - -
    findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {
    -    public void onClick(View v) {
    -        // Do stuff
    -    }
    -});
    - -

    One way to reduce the amount of boilerplate is to share a single click -listener between several buttons. While this technique reduces the -number of classes, it still requires a fair amount of code and it still -requires giving each button an id in your XML layout file:

    - -
    View.OnClickListener handler = View.OnClickListener() {
    -    public void onClick(View v) {
    -        switch (v.getId()) {
    -            case R.id.myButton: // doStuff
    -                break;
    -            case R.id.myOtherButton: // doStuff
    -                break;
    -        }
    -    }
    -}
    -
    -findViewById(R.id.myButton).setOnClickListener(handler);
    -findViewById(R.id.myOtherButton).setOnClickListener(handler);
    - -

    With Android 1.6, none of this is necessary. All you have to do is -declare a public method in your Activity to handle the click -(the method must have one View argument):

    - -
    class MyActivity extends Activity {
    -    public void myClickHandler(View target) {
    -        // Do stuff
    -    }
    -}
    - -

    And then reference this method from your XML layout:

    - -
    <Button android:onClick="myClickHandler" />
    - -

    This new feature reduces both the amount of Java and XML you have to write, -leaving you more time to concentrate on your application.

    - -

    The Android team is committed to helping you write applications in the -easiest and most efficient way possible. We hope you find these improvements -useful and we're excited to see your applications on Google Play.

    diff --git a/docs/html/resources/articles/using-webviews.jd b/docs/html/resources/articles/using-webviews.jd deleted file mode 100644 index 3a2430b9496c..000000000000 --- a/docs/html/resources/articles/using-webviews.jd +++ /dev/null @@ -1,63 +0,0 @@ -page.title=Using WebViews -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    A small application called WebViewDemo shows how you can add web content to your -application. You can find it in the apps-for-android project. -This application demonstrates how you can embed a {@link android.webkit.WebView} -into an activity and also how you can have two way communication between your -application and the web content.

    - -

    A -WebView uses the same rendering and JavaScript engine as the browser, -but it runs under the control of your application. The WebView can be -full screen or you can mix it with other Views. The content for your -WebView can come from anywhere. The WebView can download content from -the web, or it can come from local files stored in your assets -directory. The content can even be dynamically generated by your -application code. For this example, the HTML comes from a local file -called demo.html.

    - -

    This application does not do very much: when you click on the -android, he raises his arm.

    - -
    - -

    This -could, of course, easily be accomplished with a little bit of -JavaScript. Instead, though, WebViewDemo takes a slightly more -complicated path to illustrate two very powerful features of WebView.

    - -

    First, -JavaScript running inside the WebView can call out to code in your -Activity. You can use this to have your JavaScript trigger actions like -starting a new activity, or it can be used to fetch data from a -database or {@link android.content.ContentProvider}. The API for this -is very simple: just call the -{@link android.webkit.WebView#addJavascriptInterface(java.lang.Object, java.lang.String) addJavascriptInterface()} -method on your WebView. You pass an object whose methods you want to -expose to JavaScript and the name to use when making calls. You can see -the exact syntax in WebViewDemo. -java. Here we are making our DemoJavascriptInterface object available to -JavaScript where it will be called "window.demo".

    - -

    Second, your Activity can invoke JavaScript methods. All you have to do -is call the {@link android.webkit.WebView#loadUrl(java.lang.String) loadUrl} -method with the appropriate JavaScript call:

    - -

    mWebView.loadUrl("javascript:wave()");

    - -

    Our WebViewDemo uses both techniques: when you click on the -android, it calls out to the activity, which then turns around and calls back -into the JavaScript. WebViews are very powerful, and they may be a valuable tool -to help you build your application – especially if you already have a lot of -HTML content. As it happens, we've used exactly this approach in some of the -applications we've written.

    diff --git a/docs/html/resources/articles/wikinotes-intents.jd b/docs/html/resources/articles/wikinotes-intents.jd deleted file mode 100644 index 78fe62e101d1..000000000000 --- a/docs/html/resources/articles/wikinotes-intents.jd +++ /dev/null @@ -1,257 +0,0 @@ -page.title=WikiNotes: Routing Intents -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - - -

    In the Linkify! article, we talked about -using Linkify to turn wiki words (those that match a regular expression that we -have defined) into a content: URI and defining a path to data that -matched a note belonging to that wiki word. As an example, a matching word like -ToDoList would be turned into a URI such as -content://com.google.android.wikinotes.db.wikinotes/wikinotes/ToDoList - and then acted upon using the VIEW action from the Linkify class.

    - -

    This article examines how the Android system takes this combination of -VIEW action and content: URI and finds the correct -activity to fire in order to do something with the data. It will also explain -how the other default links created by Linkify, such as web URLs and telephone -numbers, also result in the correct activity to handle that data type being -fired. Finally, this article will start to examine the custom -ContentProvider that has been created to handle WikiNotes data. The -full description of the ContentProvider and what it does will span a couple more -articles as well, because there is a lot to cover.

    - -

    The Linkify-calls-intent Workflow

    - -

    At a high level, the steps for Linkify to invoke an intent, and for the -resulting activity (if any) to handle it, look like this:

    - -
      -
    1. Linkify is invoked on a TextView to turn matching text patterns into Intent links.
    2. -
    3. Linkify takes over monitoring for those Intent links being selected by the user.
    4. -
    5. When the user selects a link, Linkify calls the VIEW action using the content: URI associated with the link.
    6. -
    7. Android takes the content: URI that represents the data, and looks for a -ContentProvider registered in the system that matches the URI.
    8. -
    9. If a match is found, Android queries the ContentProvider using the URI, -and asks what MIME type the data that will be returned from the URI is.
    10. -
    11. Android then looks for an activity registered in the system with an -intent-filter that matches both the VIEW action, and the MIME type for -the data represented by the content: URI.
    12. -
    13. Assuming a match is found, Linkify then invokes the intent for -the URI, at which point the activity takes over, and is handed -the content: URI.
    14. -
    15. The activity can then use the URI to retrieve the data and act on -it.
    16. -
    - -

    This is actually a simpler process than it -sounds, and it is quite lightweight as well. Perhaps a more -understandable statement about how it works might be:

    - -

    Linkify is used to turn matching text into hot-links. When the user -selects a hot-link, Android takes the data locator represented by the -hot-link and looks for a data handler for that data locator. If it -finds one, it asks for what type of data is returned for that locator. -It then looks for something registered with the system that handles -that type of data for the VIEW action, and starts it, including the -data locator in the request.

    - -

    The real key here is the MIME type. MIME stands for Multipurpose Internet Mail -Extensions — a standard for sending attachments over email. The MIME -type (which is the part Android uses) is a way of describing certain kinds of -data. That type is then used to look for an Activity that can do something with -that data type. In this way, ContentProviders and Activities (or other -IntentReceivers) are decoupled, meaning that a given Content URI might have a -different ContentProvider to handle it, but could still use the same MIME type -meaning that the same activity could be called upon to handle the resulting -data.

    - -

    Linkify on a wiki word

    - -

    Using the above workflow, let's take a look at exactly how the process -works in WikiNotes for Android:

    - -

    First, Linkify is used to turn text matching the wiki word regular expression -into a link that provides a Content URI for that wiki word, for example -content://com.google.android.wikinotes.db.wikinotes/wikinotes/ToDoList.

    - -

    When the user clicks on the wiki word link, Linkify invokes the VIEW -action on the Content URI. At this point, the Android system takes over -getting the Intent request to the correct activity.

    - -

    Next, Android looks for a ContentProvider that has been registered -with the system to handle URIs matching our Content URI format.

    - -

    In our case, we have a definition inside -our application's AndroidManifest.xml -file that reads:

    - -
    <provider name="com.google.android.wikinotes.db.WikiNotesProvider" 
    -    android:authorities="com.google.android.wikinotes.db.wikinotes" />
    - -

    This establishes that we have a ContentProvider defined in our application -that provides the "root authority": -com.google.android.wikinotes.db.wikinotes. This is the first part -of the Content URI that we create for a wiki word link. Root Authority is just -another way of thinking about a descriptor that is registered with Android to -allow requests for certain URLs to be routed to the correct class.

    - -

    So, the whole definition is that a class called -com.google.android.wikinotes.db.WikiNotesProvider is registered -with the system as able to handle the -com.google.android.wikinotes.db.wikinotes root authority (i.e. URIs -starting with that identifier).

    - -

    From here, Android takes the rest of the URI and presents it to that -ContentProvider. If you look at the -WikiNotesProvider -class and scroll to the very bottom, in the static block there, you can see -the pattern definitions to match the rest of the URL.

    - -

    In particular, take a look at the two lines:

    - -
    URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes", NOTES);
    -URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes/*", NOTE_NAME);
    - -

    These are the definitions of URIs that our ContentProvider recognizes and can -handle. The first recognizes a full URI of -content://com.google.android.wikinotes.db.wikinotes/wikinotes and -associates that with a constant called NOTES. This is used elsewhere in the -ContentProvider to provide a list of all of the wiki notes in the database when -the URI is requested.

    - -

    The second line uses a wildcard — '*' — to match a request of the -form that Linkify will create, e.g. -content://com.google.android.wikinotes.db.wikinotes/wikinotes/ToDoList -. In this example, the * matches the ToDoList part of the URI and is -available to the handler of the request, so that it can fish out the matching -note for ToDoList and return it as the data. This also associates that match -with a constant called NOTE_NAME, which again is used as an identifier elsewhere -in the ContentProvider.

    - -

    The other matches in this static block are related to forms of -searching that have been implemented in the WikiNotes for Android -application, and will be covered in later articles. Likewise, how the -data is obtained from this matching pattern will be the subject of the -next article.

    - -

    For right now we are concerned with the MIME type for the URI. This is -defined in the getType() method also in the -WikiNotesProvider -class (about halfway through the file). Take a quick look at this. The key -parts for now are:

    - -
    case NOTES:
    -    return "vnd.android.cursor.dir/vnd.google.wikinote";
    - -

    and

    - -
    case NOTE_NAME:
    -    return "vnd.android.cursor.item/vnd.google.wikinote";
    - -

    These are the same constant names we defined in our pattern -matchers. In the first case, that of the all notes URI, the MIME type -returned is vnd.android.cursor.dir/vnd.google.wikinote -which is like saying an Android list (dir) of Google wiki notes (the -vnd bit is MIME-speak for "vendor specific definition"). Likewise, in -the case of a NOTE_NAME match, the MIME type returned is -vnd.android.cursor.item/vnd.google.wikinote which is -like saying an Android item of Google wiki notes.

    - -

    Note that if you define your own MIME data types like this, the -vnd.android.cursor.dir and vnd.android.cursor.item -categories should be retained, since they have meaning to the Android -system, but the actual item types should be changed to reflect your -particular data type.

    - -

    So far Android has been able to find a ContentProvider that handles -the Content URI supplied by the Linkify Intent call, and has queried -the ContentProvider to find out the MIME types for that URI. The final -step is to find an activity that can handle the VIEW action for that -MIME type. Take a look in the the -AndroidManifest.xml file -again. Inside the WikiNotes activity definition, you will see:

    - -
    <intent-filter>
    -    <action name="android.intent.action.VIEW"/>
    -    <category name="android.intent.category.DEFAULT"/>
    -    <category name="android.intent.category.BROWSABLE"/>
    -    <data mimetype="vnd.android.cursor.item/vnd.google.wikinote"/>
    -</intent-filter>
    - -

    This is the correct combination of matches for the VIEW action on a -WikiNote type that is requested from the LINKIFY class. The DEFAULT -category indicates that the WikiNotes activity should be treated as a -default handler (a primary choice) for this kind of data, and the -BROWSABLE category means it can be invoked from a "browser", in this -case the marked-up Linkified text.

    - -

    Using this information, Android can match up the VIEW action request -for the WikiNotes data type with the WikiNotes activity, and can then -use the WikiNotes activity to handle the request.

    - -

    Why do it like this?

    - -

    It's quite a trip through the system, and there is a lot to absorb -here, but this is one of the main reasons I wanted to write WikiNotes -in the first place. If you follow and understand the steps here, you'll -have a good grasp of the whole Intents mechanism in Android, and how it -helps loosely coupled activities cooperate to get things done.

    - -

    In this case, we could have found another way to detect wiki words -based on a regular expression, and maybe written our own handler to -intercept clicks within the TextView and dig out the right data and -display it. This would seem to accomplish the same functionality just -as easily as using intents, so what is the advantage to using the full -Intents mechanism?

    - -

    In fact there are several advantages:

    - -

    The most obvious is that because we are using the standard Intent -based approach, we are not limited to just linking and navigating to -other wiki notes. We get similar behavior to a number of other data -types as well. For example, a telephone number or web URL in a wiki -note will be marked up by Linkify, and using this same mechanism (VIEW -action on the linked data type) the browser or dialer activities will -be automatically fired.

    - -

    It also means that each operation on a wiki note can be treated as a -separate life cycle by our activity. We are not dealing with swapping -data in and out of an existing activity - each activity works on a -particular wiki note and that's all you have to worry about.

    - -

    Another advantage is that we now have a public activity to handle -VIEW actions in WikiNotes no matter where the request comes from. -Another application could request to view a wiki note (perhaps without -even knowing what kind of data it is) and our activity could start up -and handle it.

    - -

    The backstack is automatically maintained for you too. As you -forward navigate through WikiNotes, Android maintains the history of -notes visited, and so when you hit the back button you go back to the -last note you were on. All this is free because we rely on the Android -intents mechanism.

    - -

    Finally, if you run WikiNotes for Android and then start DDMS to -take a look at the Activity threads in the WikiNotes application while -it is running, you can see that despite what you might think, letting -Android manage the navigation is very efficient. Create a few linked -notes, as many links deep as you like, and then follow them. If you -follow links hundreds of notes deep, you will still only see a handful -of WikiNotes activities. Android is managing the activities, closing -the older ones as necessary and using the life cycle to swap data in -and out.

    - -

    Next Time

    - -

    This was a long article, but necessarily so. It demonstrates the -importance of the Intents mechanism and to reinforce the notion that it -should be used whenever possible for forward navigation, even within a -single application. Illustrating this is one of the primary reasons I -wrote WikiNotes for Android in the first place.

    - -

    In the next article we will look deeper into the ContentProvider and -examine how it turns a Content URI into a row (or several rows) of data -that can be used by an activity.

    diff --git a/docs/html/resources/articles/wikinotes-linkify.jd b/docs/html/resources/articles/wikinotes-linkify.jd deleted file mode 100644 index fb49f8694ee5..000000000000 --- a/docs/html/resources/articles/wikinotes-linkify.jd +++ /dev/null @@ -1,115 +0,0 @@ -page.title=WikiNotes: Linkify your Text! -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -Linkify example - -

    This article introduces WikiNotes for Android, part of the Apps for Android -project. It covers the use of Linkify to turn ordinary text views -into richer, link-oriented content that causes Android intents to fire -when a link is selected.

    - -

    Linkify: The {@link android.text.util.Linkify} class in the -framework is perfect for creating a wiki note pad. It lets you specify a regular expression -» -to match, and a scheme to prepend. The scheme is a string that, when -the matched text is added, forms a Content URI to allow the correct -data to be looked up.

    - -

    For example, in our case we want to look for a regular expression match for a -WikiWord (that is, a word with camel case » and no -spaces). Linkify can then turn this into a Content URI — something like -content://com.google.android.wikinotes.db.wikinotes/wikinotes/WikiWord, -which can then be used to locate the correct wiki page from a -{@link android.content.ContentProvider}.

    - -

    As a bonus, the Linkify class also defines several default matches, -in particular it is able to turn web URLs, email addresses and -telephone numbers into active links which fire Android intents -automatically.

    - -

    Linkify can be passed any TextView in your application, and will -take care of creating the links and enabling their "clickability" for -you.

    - -

    Default Linkify: Using the set of default active -link options is very straightforward. Simply pass it a handle to a -TextView with content in it, and the Linkify.ALL flag:

    - -
    TextView noteView = (TextView) findViewById(R.id.noteview);
    -noteView.setText(someContent);
    -Linkify.addLinks(noteView, Linkify.ALL);
    - -

    and that's it. The Linkify.ALL flag applies all of the predefined -link actions, and the TextView will be immediately updated with a set -of active links which, if you select them, fire default intents for the -actions (e.g. a web URL will start the browser with that URL, a -telephone number will bring up the phone dialer with that number ready -to call, etc.).

    - -

    Custom Linkify: So what about our WikiWord? There is no -pre-defined action for that, so it needs to be defined and associated with a -scheme.

    - -

    The first task is to define a regular expression that matches the kind of -WikiWords we want to find. The regex in this case is:

    - -
    \b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\b
    - -

    Obvious, no? Well actually this is equivalent to the following -description: "Starting with a word boundary (the \b) find at least one -upper case letter, followed by at least one lower case letter or a -numeric digit, followed by another upper case letter, and then any mix -of upper case, lower case or numeric until the next word boundary (the -final \b)". Regular expressions are not very pretty, but they are an -extremely concise and accurate way of specifying a search pattern.

    - -

    We also need to tell Linkify what to do with a match to the -WikiWord. Linkify will automatically append whatever is matched to a -scheme that is supplied to it, so for the sake of argument let's assume -we have a {@link android.content.ContentProvider} that matches the -following content URI:

    - -
    content://com.google.android.wikinotes.db.wikinotes/wikinotes/WikiWord
    - -

    The WikiWord part will be appended by Linkify when it finds a match, so we -just need the part before that as our scheme.

    - -

    Now that we have these two things, we use Linkify to connect them up:

    - -
    Pattern wikiWordMatcher = Pattern.compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b");
    -String wikiViewURL =    "content://com.google.android.wikinotes.db.wikinotes/wikinotes/";
    -Linkify.addLinks(noteView, wikiWordMatcher, wikiViewURL);
    - -

    Note that the \b's had to be escaped with double backslashes for the Java -Pattern.compile line.

    - -

    Linkify can be used multiple times on the same view to add more -links, so using this after the Default Linkify call means that the -existing active links will be maintained and the new WikiWords will be -added. You could define more Linkify actions and keep applying them to -the same TextView if you wanted to.

    - -

    Now, if we have a WikiWord in the TextView, let's say -MyToDoList, Linkify will turn it into an active link with the -content URI:

    - -
    content://com.google.android.wikinotes.db.wikinotes/wikinotes/MyToDoList
    - -

    and if you click on it, Android will fire the default intent for that content -URI.

    - -

    For this to all work, you will need a ContentProvider that -understands that Content URI, and you will need a default activity -capable of doing something with the resulting data. I plan to cover -these in future blog entries (and soon). In fact, the whole Wiki Note -Pad application is currently undergoing some clean up and review, and -will then hopefully be released as a sample application.

    diff --git a/docs/html/resources/articles/window-bg-speed.jd b/docs/html/resources/articles/window-bg-speed.jd deleted file mode 100644 index c5e5e9095a98..000000000000 --- a/docs/html/resources/articles/window-bg-speed.jd +++ /dev/null @@ -1,127 +0,0 @@ -page.title=Window Backgrounds & UI Speed -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    Some Android applications require to squeeze every bit of performance out of -the UI toolkit and there are many ways to do so. In this article, you will -discover how to speed up the drawing and the perceived startup time of -your activities. Both these techniques rely on a single feature, the window's -background drawable.

    - -

    The term window background is a bit misleading, however. When you -setup your user interface by calling setContentView() on an -{@link android.app.Activity}, Android adds your views to the Activity's -window. The window however does not contain only your views, but a few others -created for you. The most important one is, in the current implementation used -on the T-Mobile G1, the DecorView, highlighted in the view -hierarchy below:

    - -
    A typical Android view hierarchy
    - -

    The DecorView is the view that actually holds the -window's background drawable. Calling -{@link android.view.Window#setBackgroundDrawable(android.graphics.drawable.Drawable) getWindow().setBackgroundDrawable()} -from your Activity changes the background of the window by changing -the DecorView's background drawable. As mentioned before, this -setup is very specific to the current implementation of Android and can change -in a future version or even on another device.

    - -

    If you are using the standard Android themes, a default background drawable -is set on your activities. The standard theme currently used on the T-Mobile G1 -uses for instance a {@link android.graphics.drawable.ColorDrawable}. For most -applications, this background drawable works just fine and can be left alone. It -can however impacts your application's drawing performance. Let's take the -example of an application that always draws a full screen opaque picture:

    - -
    An opaque user interface doesn't need a window background
    - -

    You can see on this screenshot that the window's background is invisible, -entirely covered by an ImageView. This application is setup to -redraw as fast as it can and draws at about 44 frames per second, or 22 -milliseconds per frame (note: the number of frames per second -used in this article were obtained on a T-Mobile G1 with my finger on the screen -so as to reduce the drawing speed which would otherwise be capped at 60 fps.) An -easy way to make such an application draw faster is to remove the -background drawable. Since the user interface is entirely opaque, drawing the -background is simply wasteful. Removing the background improves the performance -quite nicely:

    - -
    Remove the background for faster drawing
    - -

    In this new version of the application, the drawing speed went up to 51 -frames per second, or 19 milliseconds per frame. The difference of 3 -milliseconds per is easily explained by the speed of the memory bus on the -T-Mobile G1: it is exactly the time it takes to move the equivalent of a -screenful of pixels on the bus. The difference could be even greater if the -default background was using a more expensive drawable.

    - -

    Removing the window's background can be achieved very easily by using -a custom theme. To do so, first create a file called -res/values/theme.xml containing the following:

    - -
    <resources>
    -    <style name="Theme.NoBackground" parent="android:Theme">
    -        <item name="android:windowBackground">@null</item>
    -    </style>
    -</resources>
    - -

    You then need to apply the theme to your activity by adding the attribute -android:theme="@style/Theme.NoBackground" to your -<activity /> or <application /> tag. This -trick comes in very handy for any app that uses a MapView, a -WebView or any other full screen opaque view.

    - -

    Opaque views and Android: this optimization is currently -necessary because the Android UI toolkit is not smart enough to prevent the -drawing of views hidden by opaque children. The main reason why this -optimization was not implemented is simply because there are usually very few -opaque views in Android applications. This is however something that I -definitely plan on implementing as soon as possible and I can only apologize for -not having been able to do this earlier.

    Using a theme to change the -window's background is also a fantastic way to improve the perceived -startup performance of some of your activities. This particular trick can only -be applied to activities that use a custom background, like a texture or a logo. -The Shelves application is a good -example:

    - -
    Textured backgrounds are good candidates for window's background
    - -

    If this application simply set the wooden background in the XML layout or in -onCreate() the user would see the application startup with the -default theme and its dark background. The wooden texture would only appear -after the inflation of the content view and the first layout/drawing pass. This -causes a jarring effect and gives the user the impression that the application -takes time to load (which can actually be the case.) Instead, the application -defines the wooden background in a theme, picked up by the system as soon as the -application starts. The user never sees the default theme and gets the -impression that the application is up and running right away. To limit the -memory and disk usage, the background is a tiled texture defined in -res/drawable/background_shelf.xml:

    - -
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:src="@drawable/shelf_panel"
    -    android:tileMode="repeat" />

    This drawable is simply referenced by the theme:

    - -
    <resources>
    -    <style name="Theme.Shelves" parent="android:Theme">
    -        <item name="android:windowBackground">@drawable/background_shelf</item>
    -        <item name="android:windowNoTitle">true</item>
    -    </style>
    -</resources>
    - -

    The same exact trick is used in the Google Maps application that ships -with the T-Mobile G1. When the application is launched, the user immediately -sees the loading tiles of MapView. This is only a trick, the theme -is simply using a tiled background that looks exactly like the loading tiles of -MapView.

    - -

    Sometimes the best tricks are also the simplest, so the next time you create -an activity with an opaque UI or a custom background, remember to change the -window's background.

    - -

    Download the source code of the first example.

    - -

    Download the source code of Shelves.

    - - diff --git a/docs/html/resources/articles/zipalign.jd b/docs/html/resources/articles/zipalign.jd deleted file mode 100644 index d3c68a6b690f..000000000000 --- a/docs/html/resources/articles/zipalign.jd +++ /dev/null @@ -1,100 +0,0 @@ -page.title=Zipalign: an Easy Optimization -parent.title=Articles -parent.link=../browser.html?tag=article -@jd:body - -

    The Android SDK includes a tool called zipalign -that optimizes the way an application is packaged. Running zipalign against your -application enables Android to interact it more efficiently at run time and thus -has the potential to make it and the overall system run faster. We strongly -encourage you to use zipalign on both new and already published -applications and to make the optimized version available — even if your -application targets a previous version of Android. This article describes how -zipalign helps performance and how to use it to optimize your -app.

    - -

    In Android, data files stored in each application's apk are accessed by -multiple processes: the installer reads the manifest to handle the -permissions associated with that application; the Home application -reads resources to get the application's name and icon; the system -server reads resources for a variety of reasons (e.g. to display that -application's notifications); and last but not least, the resource -files are obviously used by the application itself.

    - -

    The resource-handling code in Android can efficiently access resources when -they're aligned on 4-byte boundaries by memory-mapping them. But for resources -that are not aligned (that is, when zipalign hasn't been run on an -apk), it has to fall back to explicitly reading them — which is slower and -consumes additional memory.

    - -

    For an application developer, this fallback mechanism is very -convenient. It provides a lot of flexibility by allowing for several -different development methods, including those that don't include -aligning resources as part of their normal flow.

    - -

    Unfortunately, for users the situation is reversed — reading resources -from unaligned apks is slow and takes a lot of memory. In the best case, the -only visible result is that both the Home application and the unaligned -application launch slower than they otherwise should. In the worst case, -installing several applications with unaligned resources increases memory -pressure, thus causing the system to thrash around by having to constantly start -and kill processes. The user ends up with a slow device with a poor battery -life.

    - -

    Luckily, it's very easy for you to align the resources in your application:

    - -
      -
    • Using ADT:
    • -
    • -
        -
      • The ADT plugin for Eclipse (starting from version 0.9.3) will automatically -align release application packages if the export wizard is used to create them. -To use the wizard, right click the project and choose "Android Tools" > -"Export Signed Application Package..." It can also be accessed from the first -page of the AndroidManifest.xml editor.
      • -
      -
    • -
    • Using Ant:
    • - -
        -
      • The Ant build script (starting from Android 1.6) can align -application packages. Targets for older versions of the Android platform are not -aligned by the Ant build script and need to be manually aligned.
      • -
      • Starting from the Android 1.6 SDK, Ant aligns and signs packages automatically, -when building in debug mode.
      • -
      • In release mode, Ant aligns packages only if it has enough -information to sign the packages, since aligning has to happen after signing. In -order to be able to sign packages, and therefore to align them, Ant -needs to know the location of the keystore and the name of the key in -ant.properties. The name of the properties are -key.store and key.alias respectively. If those -properties are present, the signing tool will prompt to enter the store/key -passwords during the build, and the script will sign and then align the apk -file. If the properties are missing, the release package will not be signed, and -therefore will not get aligned either.
      • -
      -
    • -
    • Manually:
    • -
    • -
        -
      • In order to manually align a package, zipalign -is in the tools/ folder of Android 1.6 and later SDKs. You can use -it to align application packages targeting any version of Android. You should run -it only after signing the apk file, using the following command: -
        zipalign -v 4 source.apk destination.apk
      • -
      -
    • -
    • Verifying alignment:
    • -
    • -
        -
      • The following command verifies that a package is aligned:
        zipalign -c -v 4 application.apk -
      • -
      -
    • -
    - -

    We encourage you manually run zipalign -on your currently published applications and to make the newly aligned -versions available to users. Also, don't forget to align any new -applications going forward!

    diff --git a/docs/html/resources/browser.jd b/docs/html/resources/browser.jd deleted file mode 100644 index 8a0876996ccf..000000000000 --- a/docs/html/resources/browser.jd +++ /dev/null @@ -1,49 +0,0 @@ -page.title=Technical Resources -@jd:body - - - - - - -
    -

    Filter:

    -

    Showing all technical resources:

    -
    - - - -
    -
    No results.
    -
    - - diff --git a/docs/html/resources/community-groups.jd b/docs/html/resources/community-groups.jd deleted file mode 100644 index 6bd347c82735..000000000000 --- a/docs/html/resources/community-groups.jd +++ /dev/null @@ -1,120 +0,0 @@ -community=true -page.title=Developer Forums -@jd:body - - - -

    Welcome to the Android developers community! We're glad you're here and invite you to participate in discussions with other Android application developers on topics that interest you.

    - -

    The lists on this page are primarily for discussion about Android application development. If you are seeking discussion about Android source code (not application development), then please refer to the Open Source Project Mailing lists.

    - -

    Stack Overflow

    - -

    Stack Overflow is a collaboratively edited question and answer site for programmers. It's a great place to ask technical questions about developing and maintaining Android applications. The site is especially useful for asking questions with definite answers, but can also be used for discussing best practices.

    - -

    On the site, questions and answers relating to Android use the 'android' tag. You can look for Android topics by adding '[android]' to your search query, or by visiting the tag page at:

    - -

    http://stackoverflow.com/questions/tagged/android

    - -

    If you want to ask a question on Stack Overflow, you can use this form. Before submitting the form, make sure to add the 'android' tag so that other Android developers will be able to find your question. As always, before submitting a new question, take a look at the existing topics to see whether another developer has already asked or answered the question.

    - -

    If you are getting started with Android development, Stack Overflow may be a great location to ask questions about general Java programming or setting up the Eclipse development environment. Simply tag your questions with the Java or Eclipse tags in these cases.

    - - -

    Mailing lists

    - -

    There are a number of mailing lists, powered by Google Groups, available for discussing Android application development.

    - - -

    Before you post

    -

    Before writing a post, please try the following:

    - -
      - -
    1. Look through the support information available in the 'More' section of this tab. You may find the answer to your question in the Common Tasks, Troubleshooting Tips, or FAQs sections.
    2. -
    3. Type in keywords of your questions in the main Android site's search bar (such as the one above). This search encompasses all previous discussions, across all groups, as well as the full contents of the site, documentation, and blogs. Chances are good that somebody has run into the same issue before.
    4. - -
    - -

    If you can't find your answer, then we encourage you to address the community. -As you write your post, please do the following: -

      -
    1. Read -the mailing list charter that covers the community guidelines. -
    2. -
    3. Select the most appropriate mailing list for your question. There are several different lists for -developers, described below.
    4. -
    5. - Be very clear about your question -in the subject -- it helps everyone, both those trying to answer your -question as well as those who may be looking for information in the -future.
    6. -
    7. Give plenty of details in your post to -help others understand your problem. Code or log snippets, as well as -pointers to screenshots, may also be helpful. For a great guide to -phrasing your questions, read How To Ask Questions The Smart Way. -
    8. -
    - - -

    Using email with the mailing lists

    -

    Instead of using the Google Groups site, you can use your email client of choice to participate in the mailing lists.

    -

    To subscribe to a group without using the Google Groups site, use the link under "subscribe via email" in the lists above.

    -

    To set up how you receive mailing list postings by email:

    - -
    1. Sign into the group via the Google Groups site. For example, for the android-framework group you would visit http://groups.google.com/group/android-framework.
    2. -
    3. Click "Edit my membership" on the right side.
    4. -
    5. Under "How do you want to read this group?" select one of the email options.
    6. -
    - - -

    Application developer mailing lists

    -
      -
    • android-developers -(subscribe)
      -You're now an experienced Android application developer. You've grasped the basics of Android app development, you're comfortable using the SDK, now you want to move to advanced topics. Get help here with troubleshooting applications, advice on implementation, and strategies for improving your application's performance and user experience. This is the not the right place to discuss user issues (use android-discuss for that) or beginner questions with the Android SDK (use android-beginners for that). -
    • - -
    • android-discuss -(subscribe)
      -The "water cooler" of Android discussion. You can discuss just about anything Android-related here, ideas for the Android platform, announcements about your applications, discussions about Android devices, community resources... As long as your discussion is related to Android, it's on-topic here. However, if you have a discussion here that could belong on another list, you are probably not reaching all of your target audience here and may want to consider shifting to a more targeted list. -
    • - -
    • android-ndk -(subscribe)
      -A place for discussing the Android NDK and topics related to using native code in Android applications. -
    • - -
    • android-security-discuss -(subscribe)
      -A place for open discussion on secure development, emerging security concerns, and best practices for and by android developers. Please don't disclose vulnerabilities directly on this list, you'd be putting all Android users at risk. -
    • - -
    • android-security-announce -(subscribe)
      -A low-volume group for security-related announcements by the Android Security Team. -
    • -
    - - -

    Google Play Help Forum

    - -

    The Google Play Help Forum is a web-based discussion forum where you can ask questions or report issues relating to Google Play.

    - -

    http://support.google.com/googleplay

    diff --git a/docs/html/resources/community-more.jd b/docs/html/resources/community-more.jd deleted file mode 100644 index 3089d45aa9b5..000000000000 --- a/docs/html/resources/community-more.jd +++ /dev/null @@ -1,71 +0,0 @@ -community=true -page.title=IRC, G+, Twitter -@jd:body - -

    In addition to the Android developer forums, you can participate in the Android developer community through IRC and you can follow us on Twitter.

    - -

    IRC

    - -

    Several IRC channels are available for discussions about developing Android applications.

    - - - - - - - - - - - - - - - -
    ChannelHostDescription
    #androidirc.freenode.netGeneral discussion about Android (and Android development).
    #android-devirc.freenode.netDiscussion focused on developing Android apps.
    - -

    If you haven't used IRC before, check http://en.wikipedia.org/wiki/ -List_of_IRC_clients » for a helpful list of IRC clients. Alternatively, you could also use -this web interface », which -does not require any installation, to join discussions on the Android IRC channels.

    - -

    Here are some tips for using IRC: - -

      -
    • Set your nickname before you join the channel.
    • -
    • Registering your nickname prevents others from using your nickname or impersonating you later: -
      /nick <yournickname>
      -/msg nickserv register <password> <email>
      -

      Afterwards, when you connect, you'll need to supply a password:

      -
      /connect irc.freenode.net
      -/nick <yournickname>
      -/msg nickserv identify <password>
      -/join #android-dev
      -
    • -
    - - -

    Google+

    -

    We use a Google+ page to host Hangouts for developers, talk about the latest -releases, development and design tips, and much more.

    - -
    - - -

    Twitter

    -

    You can follow us on Twitter at this account:

    - -

    http://twitter.com/androiddev

    - - - \ No newline at end of file diff --git a/docs/html/resources/dashboard/opengl.jd b/docs/html/resources/dashboard/opengl.jd deleted file mode 100644 index 4c55522b743d..000000000000 --- a/docs/html/resources/dashboard/opengl.jd +++ /dev/null @@ -1,79 +0,0 @@ -page.title=OpenGL ES Versions -@jd:body - - - -

    This page provides data about the relative number of active devices that support a particular -version of OpenGL ES. Note that support for one particular version of OpenGL ES also implies -support for any lower version (for example, support for version 2.0 also implies support for -1.1).

    - -

    To declare which version of OpenGL ES your application requires, you should use the {@code -android:glEsVersion} attribute of the {@code <uses-feature>} -element. You can also use the {@code -<supports-gl-texture>} element to declare the GL compression formats that your application -uses.

    - -

    Note: This data is based on the number -of Android devices that have accessed Google Play within a 7-day period -ending on the data collection date noted below.

    - - -
    - - - - - - - - - - - - - - -
    OpenGL ES VersionDistribution
    1.1 only -11.9%
    2.0 & 1.1 -88.1%
    - -

    Data collected during a 7-day period ending on April 2, 2012

    -
    - diff --git a/docs/html/resources/dashboard/platform-versions.jd b/docs/html/resources/dashboard/platform-versions.jd deleted file mode 100644 index 2cbbe99dce63..000000000000 --- a/docs/html/resources/dashboard/platform-versions.jd +++ /dev/null @@ -1,117 +0,0 @@ -page.title=Platform Versions -@jd:body - - - -

    This page provides data about the relative number of active devices -running a given version of the Android platform. This can help you -understand the landscape of device distribution and decide how to prioritize -the development of your application features for the devices currently in -the hands of users. For information about how to target your application to devices based on -platform version, see API Levels.

    - - -

    Current Distribution

    - -

    The following pie chart and table is based on the number of Android devices that have accessed -Google Play within a 14-day period ending on the data collection date noted below.

    - -
    - - - - - - - - - - - - - - - - - - - - - - - -
    PlatformCodenameAPI LevelDistribution
    Android 1.5Cupcake 30.3%
    Android 1.6Donut 40.7%
    Android 2.1Eclair 76.0%
    Android 2.2Froyo 823.1%
    Android 2.3 -
    - Android 2.3.2
    Gingerbread 90.5%
    Android 2.3.3 -
    - Android 2.3.7
    1063.2%
    Android 3.0Honeycomb 110.1%
    Android 3.1121.0%
    Android 3.2132.2%
    Android 4.0 -
    - Android 4.0.2
    Ice Cream Sandwich140.5%
    Android 4.0.3152.4%
    - -

    Data collected during a 14-day period ending on April 2, 2012

    - -
    - - -

    Historical Distribution

    - -

    The following stacked line graph provides a history of the relative number of -active Android devices running different versions of the Android platform. It also provides a -valuable perspective of how many devices your application is compatible with, based on the -platform version.

    - -

    Notice that the platform versions are stacked on top of each other with the oldest active -version at the top. This format indicates the total percent of active devices that are compatible -with a given version of Android. For example, if you develop your application for -the version that is at the very top of the chart, then your application is -compatible with 100% of active devices (and all future versions), because all Android APIs are -forward compatible. Or, if you develop your application for a version lower on the chart, -then it is currently compatible with the percentage of devices indicated on the y-axis, where the -line for that version meets the y-axis on the right.

    - -

    Each dataset in the timeline is based on the number of Android devices that accessed -Google Play within a 14-day period ending on the date indicated on the x-axis.

    - -
    - - - -

    Last historical dataset collected during a 14-day period ending on April 2, 2012

    - - -
    - diff --git a/docs/html/resources/dashboard/screens.jd b/docs/html/resources/dashboard/screens.jd deleted file mode 100644 index e5c79a125d33..000000000000 --- a/docs/html/resources/dashboard/screens.jd +++ /dev/null @@ -1,101 +0,0 @@ -page.title=Screen Sizes and Densities -@jd:body - - - -

    This page provides data about the relative number of active devices that have a particular -screen configuration, defined by a combination of screen size and density. To simplify the way that -you design your user interfaces for different screen configurations, Android divides the range of -actual screen sizes and densities into:

    - -
      -
    • A set of four generalized sizes: small, normal, -large, and xlarge
    • -
    • A set of four generalized densities: ldpi (low), mdpi -(medium), hdpi (high), and xhdpi (extra high)
    • -
    - -

    For information about how you can support multiple screen configurations in your -application, see Supporting Multiple -Screens.

    - -

    Note: This data is based on the number -of Android devices that have accessed Google Play within a 7-day period -ending on the data collection date noted below.

    - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ldpimdpihdpixhdpi
    small1.9% 2.5%
    normal0.7% 19.6% 64.6% 2.4%
    large0.2% 2.3%
    xlarge 5.8%
    - -

    Data collected during a 7-day period ending on April 2, 2012

    -
    - diff --git a/docs/html/resources/images/ActionBarCompat1.png b/docs/html/resources/images/ActionBarCompat1.png new file mode 100644 index 000000000000..64d3e66f621b Binary files /dev/null and b/docs/html/resources/images/ActionBarCompat1.png differ diff --git a/docs/html/resources/images/ActionBarCompat2.png b/docs/html/resources/images/ActionBarCompat2.png new file mode 100644 index 000000000000..04a7e6c5feca Binary files /dev/null and b/docs/html/resources/images/ActionBarCompat2.png differ diff --git a/docs/html/resources/images/BluetoothChat1.png b/docs/html/resources/images/BluetoothChat1.png new file mode 100644 index 000000000000..f87da6a952b1 Binary files /dev/null and b/docs/html/resources/images/BluetoothChat1.png differ diff --git a/docs/html/resources/images/BluetoothChat2.png b/docs/html/resources/images/BluetoothChat2.png new file mode 100644 index 000000000000..6218eff5ffea Binary files /dev/null and b/docs/html/resources/images/BluetoothChat2.png differ diff --git a/docs/html/resources/images/BluetoothHDP.png b/docs/html/resources/images/BluetoothHDP.png new file mode 100644 index 000000000000..c04cfde46681 Binary files /dev/null and b/docs/html/resources/images/BluetoothHDP.png differ diff --git a/docs/html/resources/images/BusinessCard1.png b/docs/html/resources/images/BusinessCard1.png new file mode 100644 index 000000000000..55ff7e565c8d Binary files /dev/null and b/docs/html/resources/images/BusinessCard1.png differ diff --git a/docs/html/resources/images/BusinessCard2.png b/docs/html/resources/images/BusinessCard2.png new file mode 100644 index 000000000000..347c317f185f Binary files /dev/null and b/docs/html/resources/images/BusinessCard2.png differ diff --git a/docs/html/resources/images/ContactManager1.png b/docs/html/resources/images/ContactManager1.png new file mode 100644 index 000000000000..d787ffd17d23 Binary files /dev/null and b/docs/html/resources/images/ContactManager1.png differ diff --git a/docs/html/resources/images/ContactManager2.png b/docs/html/resources/images/ContactManager2.png new file mode 100644 index 000000000000..f7837498ebb2 Binary files /dev/null and b/docs/html/resources/images/ContactManager2.png differ diff --git a/docs/html/resources/images/CubeLiveWallpaper1.png b/docs/html/resources/images/CubeLiveWallpaper1.png new file mode 100644 index 000000000000..55bc1e9ed004 Binary files /dev/null and b/docs/html/resources/images/CubeLiveWallpaper1.png differ diff --git a/docs/html/resources/images/CubeLiveWallpaper3.png b/docs/html/resources/images/CubeLiveWallpaper3.png new file mode 100644 index 000000000000..2747a88e5750 Binary files /dev/null and b/docs/html/resources/images/CubeLiveWallpaper3.png differ diff --git a/docs/html/resources/images/HomeSample.png b/docs/html/resources/images/HomeSample.png new file mode 100644 index 000000000000..990bebbdb485 Binary files /dev/null and b/docs/html/resources/images/HomeSample.png differ diff --git a/docs/html/resources/images/JetBoy.png b/docs/html/resources/images/JetBoy.png new file mode 100644 index 000000000000..3da044827d7a Binary files /dev/null and b/docs/html/resources/images/JetBoy.png differ diff --git a/docs/html/resources/images/KeyChainDemo1.png b/docs/html/resources/images/KeyChainDemo1.png new file mode 100644 index 000000000000..d426c225a45e Binary files /dev/null and b/docs/html/resources/images/KeyChainDemo1.png differ diff --git a/docs/html/resources/images/KeyChainDemo2.png b/docs/html/resources/images/KeyChainDemo2.png new file mode 100755 index 000000000000..e181e5877a5e Binary files /dev/null and b/docs/html/resources/images/KeyChainDemo2.png differ diff --git a/docs/html/resources/images/KeyChainDemo3.png b/docs/html/resources/images/KeyChainDemo3.png new file mode 100755 index 000000000000..acfdd89f1a07 Binary files /dev/null and b/docs/html/resources/images/KeyChainDemo3.png differ diff --git a/docs/html/resources/images/KeyChainDemo4.png b/docs/html/resources/images/KeyChainDemo4.png new file mode 100755 index 000000000000..a9101abaee61 Binary files /dev/null and b/docs/html/resources/images/KeyChainDemo4.png differ diff --git a/docs/html/resources/images/MultiResolution.png b/docs/html/resources/images/MultiResolution.png new file mode 100644 index 000000000000..8b245d99532a Binary files /dev/null and b/docs/html/resources/images/MultiResolution.png differ diff --git a/docs/html/resources/images/NewsReader.png b/docs/html/resources/images/NewsReader.png new file mode 100644 index 000000000000..f44c6494f09d Binary files /dev/null and b/docs/html/resources/images/NewsReader.png differ diff --git a/docs/html/resources/images/NfcDemo.png b/docs/html/resources/images/NfcDemo.png new file mode 100644 index 000000000000..c175d12b5d7e Binary files /dev/null and b/docs/html/resources/images/NfcDemo.png differ diff --git a/docs/html/resources/images/SampleSyncAdapter1.png b/docs/html/resources/images/SampleSyncAdapter1.png new file mode 100644 index 000000000000..242fd3672a6f Binary files /dev/null and b/docs/html/resources/images/SampleSyncAdapter1.png differ diff --git a/docs/html/resources/images/SampleSyncAdapter2.png b/docs/html/resources/images/SampleSyncAdapter2.png new file mode 100644 index 000000000000..055beafb55df Binary files /dev/null and b/docs/html/resources/images/SampleSyncAdapter2.png differ diff --git a/docs/html/resources/images/SampleSyncAdapter3.png b/docs/html/resources/images/SampleSyncAdapter3.png new file mode 100644 index 000000000000..8ec468e308aa Binary files /dev/null and b/docs/html/resources/images/SampleSyncAdapter3.png differ diff --git a/docs/html/resources/images/SearchableDictionary1.png b/docs/html/resources/images/SearchableDictionary1.png new file mode 100644 index 000000000000..ebb4604f8607 Binary files /dev/null and b/docs/html/resources/images/SearchableDictionary1.png differ diff --git a/docs/html/resources/images/SearchableDictionary2.png b/docs/html/resources/images/SearchableDictionary2.png new file mode 100644 index 000000000000..34746cd15563 Binary files /dev/null and b/docs/html/resources/images/SearchableDictionary2.png differ diff --git a/docs/html/resources/images/SipDemo.png b/docs/html/resources/images/SipDemo.png new file mode 100755 index 000000000000..999bea944719 Binary files /dev/null and b/docs/html/resources/images/SipDemo.png differ diff --git a/docs/html/resources/images/Snake.png b/docs/html/resources/images/Snake.png new file mode 100644 index 000000000000..c5211d8835dd Binary files /dev/null and b/docs/html/resources/images/Snake.png differ diff --git a/docs/html/resources/images/SoftKeyboard.png b/docs/html/resources/images/SoftKeyboard.png new file mode 100644 index 000000000000..8a4ec6322cc8 Binary files /dev/null and b/docs/html/resources/images/SoftKeyboard.png differ diff --git a/docs/html/resources/images/SpinnerTest1.png b/docs/html/resources/images/SpinnerTest1.png new file mode 100644 index 000000000000..21442f20b983 Binary files /dev/null and b/docs/html/resources/images/SpinnerTest1.png differ diff --git a/docs/html/resources/images/SpinnerTest2.png b/docs/html/resources/images/SpinnerTest2.png new file mode 100644 index 000000000000..79ffeb6a929f Binary files /dev/null and b/docs/html/resources/images/SpinnerTest2.png differ diff --git a/docs/html/resources/images/StackWidget.png b/docs/html/resources/images/StackWidget.png new file mode 100644 index 000000000000..f2f83a0adcb0 Binary files /dev/null and b/docs/html/resources/images/StackWidget.png differ diff --git a/docs/html/resources/images/TicTacToeLib.png b/docs/html/resources/images/TicTacToeLib.png new file mode 100644 index 000000000000..398eff38ffb4 Binary files /dev/null and b/docs/html/resources/images/TicTacToeLib.png differ diff --git a/docs/html/resources/images/TicTacToeMain.png b/docs/html/resources/images/TicTacToeMain.png new file mode 100644 index 000000000000..44cee11b9519 Binary files /dev/null and b/docs/html/resources/images/TicTacToeMain.png differ diff --git a/docs/html/resources/images/VoicemailProviderDemo.png b/docs/html/resources/images/VoicemailProviderDemo.png new file mode 100644 index 000000000000..1a45d7aa440a Binary files /dev/null and b/docs/html/resources/images/VoicemailProviderDemo.png differ diff --git a/docs/html/resources/images/WeatherListWidget.png b/docs/html/resources/images/WeatherListWidget.png new file mode 100644 index 000000000000..f0cbdaff095f Binary files /dev/null and b/docs/html/resources/images/WeatherListWidget.png differ diff --git a/docs/html/resources/images/WifiDirect.png b/docs/html/resources/images/WifiDirect.png new file mode 100644 index 000000000000..86f7f2f2e946 Binary files /dev/null and b/docs/html/resources/images/WifiDirect.png differ diff --git a/docs/html/resources/images/Wiktionary.png b/docs/html/resources/images/Wiktionary.png new file mode 100644 index 000000000000..78fee7c4494c Binary files /dev/null and b/docs/html/resources/images/Wiktionary.png differ diff --git a/docs/html/resources/images/WiktionarySimple.png b/docs/html/resources/images/WiktionarySimple.png new file mode 100644 index 000000000000..57cd11d9a5a9 Binary files /dev/null and b/docs/html/resources/images/WiktionarySimple.png differ diff --git a/docs/html/resources/images/XmlPhotosAdapter.png b/docs/html/resources/images/XmlPhotosAdapter.png new file mode 100644 index 000000000000..c018d54c83ec Binary files /dev/null and b/docs/html/resources/images/XmlPhotosAdapter.png differ diff --git a/docs/html/resources/images/XmlRssReader.png b/docs/html/resources/images/XmlRssReader.png new file mode 100644 index 000000000000..00f841b3482b Binary files /dev/null and b/docs/html/resources/images/XmlRssReader.png differ diff --git a/docs/html/resources/images/hcgallery-phone1.png b/docs/html/resources/images/hcgallery-phone1.png new file mode 100644 index 000000000000..9f0c2805581d Binary files /dev/null and b/docs/html/resources/images/hcgallery-phone1.png differ diff --git a/docs/html/resources/images/hcgallery-phone2.png b/docs/html/resources/images/hcgallery-phone2.png new file mode 100644 index 000000000000..b049a6559ab8 Binary files /dev/null and b/docs/html/resources/images/hcgallery-phone2.png differ diff --git a/docs/html/resources/images/hcgallery.png b/docs/html/resources/images/hcgallery.png new file mode 100644 index 000000000000..42b018341fc2 Binary files /dev/null and b/docs/html/resources/images/hcgallery.png differ diff --git a/docs/html/resources/images/randommusicplayer.png b/docs/html/resources/images/randommusicplayer.png new file mode 100644 index 000000000000..e16e0677da00 Binary files /dev/null and b/docs/html/resources/images/randommusicplayer.png differ diff --git a/docs/html/resources/images/sample_lunarlander.png b/docs/html/resources/images/sample_lunarlander.png new file mode 100644 index 000000000000..a2ff75ab6467 Binary files /dev/null and b/docs/html/resources/images/sample_lunarlander.png differ diff --git a/docs/html/resources/images/sample_note.png b/docs/html/resources/images/sample_note.png new file mode 100644 index 000000000000..8fc9dcc0e627 Binary files /dev/null and b/docs/html/resources/images/sample_note.png differ diff --git a/docs/html/resources/images/sample_notepad.png b/docs/html/resources/images/sample_notepad.png new file mode 100644 index 000000000000..46f221104b20 Binary files /dev/null and b/docs/html/resources/images/sample_notepad.png differ diff --git a/docs/html/resources/images/sample_notepadtest_junit.png b/docs/html/resources/images/sample_notepadtest_junit.png new file mode 100644 index 000000000000..4cda54e94eae Binary files /dev/null and b/docs/html/resources/images/sample_notepadtest_junit.png differ diff --git a/docs/html/resources/images/vpn-confirmation.png b/docs/html/resources/images/vpn-confirmation.png new file mode 100755 index 000000000000..ae2e58332089 Binary files /dev/null and b/docs/html/resources/images/vpn-confirmation.png differ diff --git a/docs/html/resources/index.jd b/docs/html/resources/index.jd deleted file mode 100644 index 905586884018..000000000000 --- a/docs/html/resources/index.jd +++ /dev/null @@ -1,90 +0,0 @@ -page.title=Developer Resources -@jd:body - - - -

    -This section provides articles, tutorials, sample code, and other -information to help you quickly implement the features you want in your -application. To return to this page later, just click the "Resources" -tab while any Resources page is loaded. -

    - -

    Technical Resources

    - - - - - - - - -
    - - - -

    - Sample Code -

    -

    Fully-functioning sample applications that you can build and run - to learn about how Android works. Feel free to reuse any of the code or - techniques in the samples.

    -
    - - - -

    - Articles -

    -

    Focused discussions about Android development subjects, including - optimizations, tips, interesting implementations, "how-tos", - and so on.

    -
    - - - -

    - Tutorials -

    -

    Step-by-step instructions demonstrating how to build an Android application - that has the specific features you want.

    -
    - -

    Other Resources

    - -
    -
    Community
    -
    Links to the Android discussion groups and information about other ways to -collaborate with other developers.
    - -
    Device Dashboard
    -
    Device distribution data, grouped by various dimensions such as screen size -and Android platform version.
    - -
    More
    -
    Quick development tips, troubleshooting information, and frequently asked -questions (FAQs).
    -
    diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js deleted file mode 100644 index fb4225dc8a2d..000000000000 --- a/docs/html/resources/resources-data.js +++ /dev/null @@ -1,946 +0,0 @@ -var ANDROID_TAGS = { - type: { - 'article': 'Article', - 'tutorial': 'Tutorial', - 'sample': 'Sample', - 'video': 'Video', - 'library': 'Code Library' - }, - topic: { - 'accessibility': 'Accessibility', - 'accountsync': 'Accounts & Sync', - 'bestpractice': 'Best Practices', - 'communication': 'Communication', - 'compatibility': 'Compatibility', - 'data': 'Data Access', - 'drawing': 'Canvas Drawing', - 'gamedev': 'Game Development', - 'gl': 'OpenGL ES', - 'input': 'Input Methods', - 'intent': 'Intents', - 'layout': 'Layouts/Views', - 'media': 'Multimedia', - 'multitasking': 'Multi-tasking', - 'newfeature': 'New Features', - 'performance': 'Performance', - 'search': 'Search', - 'testing': 'Testing', - 'ui': 'User Interface', - 'web': 'Web Content', - 'widgets': 'App Widgets' - }, - misc: { - 'external': 'External', - 'new': 'New', - 'updated': 'Updated' - } -}; - -var ANDROID_RESOURCES = [ - -////////////////////////// -/// TECHNICAL ARTICLES /// -////////////////////////// - - { - tags: ['article', 'performance', 'bestpractice'], - path: 'articles/avoiding-memory-leaks.html', - title: { - en: 'Avoiding Memory Leaks' - }, - description: { - en: 'Mobile devices often have limited memory, and memory leaks can cause your application to waste this valuable resource without your knowledge. This article provides tips to help you avoid common causes of memory leaks on the Android platform.' - } - }, - { - tags: ['article', 'compatibility'], - path: 'articles/backward-compatibility.html', - title: { - en: 'Backward Compatibility' - }, - description: { - en: 'The Android platform strives to ensure backwards compatibility. However, sometimes you want to use new features which aren\'t supported on older platforms. This article discusses strategies for selectively using these features based on availability, allowing you to keep your applications portable across a wide range of devices.' - } - }, - { - tags: ['article', 'intent'], - path: 'articles/can-i-use-this-intent.html', - title: { - en: 'Can I Use this Intent?' - }, - description: { - en: 'Android offers a very powerful and yet easy-to-use message type called an intent. You can use intents to turn applications into high-level libraries and make code modular and reusable. While it is nice to be able to make use of a loosely coupled API, there is no guarantee that the intent you send will be received by another application. This article describes a technique you can use to find out whether the system contains any application capable of responding to the intent you want to use.' - } - }, - { - tags: ['article', 'input'], - path: 'articles/creating-input-method.html', - title: { - en: 'Creating an Input Method' - }, - description: { - en: 'Input Method Editors (IMEs) provide the mechanism for entering text into text fields and other Views. Android devices come bundled with at least one IME, but users can install additional IMEs. This article covers the basics of developing an IME for the Android platform.' - } - }, - { - tags: ['article', 'drawing', 'ui'], - path: 'articles/drawable-mutations.html', - title: { - en: 'Drawable Mutations' - }, - description: { - en: 'Drawables are pluggable drawing containers that allow applications to display graphics. This article explains some common pitfalls when trying to modify the properties of multiple Drawables.' - } - }, - { - tags: ['article', 'bestpractice', 'ui'], - path: 'articles/faster-screen-orientation-change.html', - title: { - en: 'Faster Screen Orientation Change' - }, - description: { - en: 'When an Android device changes its orientation, the default behavior is to automatically restart the current activity with a new configuration. However, this can become a bottleneck in applications that access a large amount of external data. This article discusses how to gracefully handle this situation without resorting to manually processing configuration changes.' - } - }, - { - tags: ['article', 'compatibility'], - path: 'articles/future-proofing.html', - title: { - en: 'Future-Proofing Your Apps' - }, - description: { - en: 'A collection of common sense advice to help you ensure that your applications don\'t break when new versions of the Android platform are released.' - } - }, - { - tags: ['article', 'input'], - path: 'articles/gestures.html', - title: { - en: 'Gestures' - }, - description: { - en: 'Touch screens allow users to perform gestures, such as tapping, dragging, flinging, or sliding, to perform various actions. The gestures API enables your application to recognize even complicated gestures with ease. This article explains how to integrate this API into an application.' - } - }, - { - tags: ['article', 'gamedev', 'gl'], - path: 'articles/glsurfaceview.html', - title: { - en: 'Introducing GLSurfaceView' - }, - description: { - en: 'This article provides an overview of GLSurfaceView, a class that makes it easy to implement 2D or 3D OpenGL rendering inside of an Android application.' - } - }, - { - tags: ['article', 'ui', 'layout'], - path: 'articles/layout-tricks-reuse.html', - title: { - en: 'Layout Tricks: Creating Reusable UI Components' - }, - description: { - en: 'Learn how to combine multiple standard UI widgets into a single high-level component, which can be reused throughout your application.' - } - }, - { - tags: ['article', 'layout', 'ui', 'performance', 'bestpractice'], - path: 'articles/layout-tricks-efficiency.html', - title: { - en: 'Layout Tricks: Creating Efficient Layouts' - }, - description: { - en: 'Learn how to optimize application layouts as this article walks you through converting a LinearLayout into a RelativeLayout, and analyzes the resulting implications on performance.' - } - }, - { - tags: ['article', 'layout', 'ui', 'performance', 'bestpractice'], - path: 'articles/layout-tricks-stubs.html', - title: { - en: 'Layout Tricks: Using ViewStubs' - }, - description: { - en: 'Learn about using ViewStubs inside an application\'s layout in order to inflate rarely used UI elements, without the performance implications which would otherwise be caused by using the <include> tag.' - } - }, - { - tags: ['article', 'layout', 'ui', 'performance', 'bestpractice'], - path: 'articles/layout-tricks-merge.html', - title: { - en: 'Layout Tricks: Merging Layouts' - }, - description: { - en: 'Learn how to use the <merge> tag in your XML layouts in order to avoid unnecessary levels of hierarchy within an application\'s view tree.' - } - }, - { - tags: ['article', 'ui', 'performance'], - path: 'articles/listview-backgrounds.html', - title: { - en: 'ListView Backgrounds: An Optimization' - }, - description: { - en: 'ListViews are very popular widgets within the Android framework. This article describes some of the optimizations used by the ListView widget, and how to avoid some common issues that this causes when trying to use a custom background.' - } - }, - { - tags: ['article', 'ui'], - path: 'articles/live-folders.html', - title: { - en: 'Live Folders' - }, - description: { - en: 'Live Folders allow users to display any source of data on their home screen without launching an application. This article discusses how to export an application\'s data in a format suitable for display inside of a live folder.' - } - }, - { - tags: ['article', 'ui'], - path: 'articles/live-wallpapers.html', - title: { - en: 'Live Wallpapers' - }, - description: { - en: 'Live wallpapers are richer, animated, interactive backgrounds that users can display in their home screens. Learn how to create a live wallpaper and bundle it in an application that users can install on their devices.' - } - }, - { - tags: ['article', 'bestpractice', 'multitasking'], - path: 'articles/multitasking-android-way.html', - title: { - en: 'Multitasking the Android Way' - }, - description: { - en: 'This article describes best practices and user experience guidelines for multi-tasking on Android.' - } - }, - { - tags: ['article', 'input'], - path: 'articles/on-screen-inputs.html', - title: { - en: 'Onscreen Input Methods' - }, - description: { - en: 'The Input Method Framework (IMF) allows users to take advantage of on-screen input methods, such as software keyboards. This article provides an overview of Input Method Editors (IMEs) and how applications interact with them.' - } - }, - { - tags: ['article', 'performance', 'bestpractice'], - path: 'articles/painless-threading.html', - title: { - en: 'Painless Threading' - }, - description: { - en: 'This article discusses the threading model used by Android applications and how applications can ensure best UI performance by spawning worker threads to handle long-running operations, rather than handling them in the main thread. The article also explains the API that your application can use to interact with Android UI toolkit components running on the main thread and spawn managed worker threads.' - } - }, - { - tags: ['article', 'ui', 'search'], - path: 'articles/qsb.html', - title: { - en: 'Quick Search Box' - }, - description: { - en: 'Quick Search Box (QSB) is a powerful, system-wide search framework. QSB makes it possible for users to quickly and easily find what they\'re looking for, both on their devices and on the web. This article discusses how to work with the QSB framework to add new search results for an installed application.' - } - }, - { - tags: ['article', 'input', 'search', 'ui'], - path: 'articles/speech-input.html', - title: { - en: 'Speech Input' - }, - description: { - en: 'This articles describes the basics of integrating speech recognition into Android applications.' - } - }, - { - tags: ['article', 'compatibility', 'multitasking'], - path: 'articles/service-api-changes-starting-with.html', - title: { - en: 'Service API changes starting with Android 2.0' - }, - description: { - en: 'This article describes the changes and improvements to services introduced in Android 2.0, as well as strategies for compatibility with older versions of the platform.' - } - }, - { - tags: ['article', 'input', 'ui'], - path: 'articles/spell-checker-framework.html', - title: { - en: 'The Android Spell Checker Framework' - }, - description: { - en: 'This article describes the Android spell checker framework and how to use to implement spell checking in applications.' - } - }, - - { - tags: ['article', 'ui'], - path: 'articles/touch-mode.html', - title: { - en: 'Touch Mode' - }, - description: { - en: 'This article explains the touch mode, one of the most important principles of Android\'s UI toolkit. Whenever a user interacts with a device\'s touch screen, the system enters touch mode. While simple in concept, there are important implications touch mode that are often overlooked.' - } - }, - { - tags: ['article', 'performance', 'bestpractice'], - path: 'articles/track-mem.html', - title: { - en: 'Tracking Memory Allocations' - }, - description: { - en: 'This article discusses how to use the Allocation Tracker tool to observe memory allocations and avoid performance problems that would otherwise be caused by ignoring the effect of Dalvik\'s garbage collector.' - } - }, - { - tags: ['article'], - path: 'articles/ui-1.5.html', - title: { - en: 'UI Framework Changes in Android 1.5' - }, - description: { - en: 'Explore the UI changes that were introduced in Android 1.5, compared with the UI provided in Android 1.0 and 1.1.' - } - }, - { - tags: ['article'], - path: 'articles/ui-1.6.html', - title: { - en: 'UI Framework Changes in Android 1.6' - }, - description: { - en: 'Explore the UI changes that were introduced in Android 1.6, compared with the UI provided in Android 1.5. In particular, this article discusses changes to RelativeLayouts and click listeners.' - } - }, - { - tags: ['article', 'ui', 'bestpractice'], - path: 'articles/timed-ui-updates.html', - title: { - en: 'Updating the UI from a Timer' - }, - description: { - en: 'Learn about how to use Handlers as a more efficient replacement for java.util.Timer on the Android platform.' - } - }, - { - tags: ['article', 'ui', 'accessibility'], - path: 'articles/tts.html', - title: { - en: 'Using Text-to-Speech' - }, - description: { - en: 'The text-to-speech API lets your application "speak" to users, in any of several languages. This article provides an overview of the TTS API and how you use to add speech capabilities to your application.' - } - }, - { - tags: ['article', 'accountsync', 'data'], - path: 'articles/contacts.html', - title: { - en: 'Using the Contacts API' - }, - description: { - en: 'Android provides a Contacts API for managing and integrating contacts from multiple accounts and data sources and allows apps to read various information about individual contacts.' - } - }, - { - tags: ['article', 'ui', 'web'], - path: 'articles/using-webviews.html', - title: { - en: 'Using WebViews' - }, - description: { - en: 'WebViews allow an application to dynamically display HTML and execute JavaScript, without relinquishing control to a separate browser application. This article introduces the WebView classes and provides a sample application that demonstrates its use.' - } - }, - { - tags: ['article', 'ui'], - path: 'articles/wikinotes-linkify.html', - title: { - en: 'WikiNotes: Linkify your Text!' - }, - description: { - en: 'This article introduces WikiNotes for Android, part of the Apps for Android project. It covers the use of Linkify to turn ordinary text views into richer, link-oriented content that causes Android intents to fire when a link is selected.' - } - }, - { - tags: ['article', 'intent'], - path: 'articles/wikinotes-intents.html', - title: { - en: 'WikiNotes: Routing Intents' - }, - description: { - en: 'This article illustrates how an application, in this case the WikiNotes sample app, can use intents to route various types of linked text to the application that handles that type of data. For example, an app can use intents to route a linked telephone number to a dialer app and a web URL to a browser.' - } - }, - { - tags: ['article', 'ui', 'performance'], - path: 'articles/window-bg-speed.html', - title: { - en: 'Window Backgrounds & UI Speed' - }, - description: { - en: 'Some Android applications need to squeeze every bit of performance out of the UI toolkit and there are many ways to do so. In this article, you will discover how to speed up the drawing and the perceived startup time of your activities. Both of these techniques rely on a single feature, the window\'s background drawable.' - } - }, - { - tags: ['article', 'performance', 'bestpractice'], - path: 'articles/zipalign.html', - title: { - en: 'Zipalign: an Easy Optimization' - }, - description: { - en: 'The Android SDK includes a tool called zipalign that optimizes the way an application is packaged. Running zipalign against your application enables Android to interact with it more efficiently at run time and thus has the potential to make it and the overall system run faster. This article provides a high-level overview of the zipalign tool and its use.' - } - }, - -/////////////////// -/// SAMPLE CODE /// -/////////////////// - - { - tags: ['sample'], - path: 'samples/AccelerometerPlay/index.html', - title: { - en: 'Accelerometer Play' - }, - description: { - en: 'An example of using the accelerometer to integrate the device\'s acceleration to a position using the Verlet method. This is illustrated with a very simple particle system comprised of a few iron balls freely moving on an inclined wooden table. The inclination of the virtual table is controlled by the device\'s accelerometer.' - } - }, - { - tags: ['sample', 'new', 'ui', 'compatibility', 'newfeature'], - path: 'samples/ActionBarCompat/index.html', - title: { - en: 'Action Bar Compatibility' - }, - description: { - en: 'Shows how to use the action bar on both pre-API 11 and API 11+ devices, maximizing code re-use.' - } - }, - { - tags: ['sample', 'new'], - path: 'samples/AndroidBeamDemo/index.html', - title: { - en: 'Android Beam Demo' - }, - description: { - en: 'An example of how to use the Android Beam feature to send messages between two Android-powered devices (API level 14 or later) that support NFC.' - } - }, - { - tags: ['sample', 'layout', 'ui', 'updated'], - path: 'samples/ApiDemos/index.html', - title: { - en: 'API Demos' - }, - description: { - en: 'A variety of small applications that demonstrate an extensive collection of framework topics.' - } - }, - { - tags: ['sample', 'layout', 'ui', 'fragment', 'loader'], - path: 'samples/Support4Demos/index.html', - title: { - en: 'API 4+ Support Demos' - }, - description: { - en: 'A variety of small applications that demonstrate the use of the helper classes in the Android API 4+ Support Library (classes which work down to API level 4 or version 1.6 of the platform).' - } - }, - { - tags: ['sample', 'layout', 'ui'], - path: 'samples/Support13Demos/index.html', - title: { - en: 'API 13+ Support Demos' - }, - description: { - en: 'A variety of small applications that demonstrate the use of the helper classes in the Android API 13+ Support Library (classes which work down to API level 13 or version 3.2 of the platform).' - } - }, - { - tags: ['sample', 'data', 'newfeature', 'accountsync'], - path: 'samples/BackupRestore/index.html', - title: { - en: 'Backup and Restore' - }, - description: { - en: 'Illustrates a few different approaches that an application developer can take when integrating with the Android Backup Manager using the BackupAgent API introduced in Android 2.2.' - } - }, - { - tags: ['sample', 'communication'], - path: 'samples/BluetoothChat/index.html', - title: { - en: 'Bluetooth Chat' - }, - description: { - en: 'An application for two-way text messaging over Bluetooth.' - } - }, - { - tags: ['sample', 'communication', 'new'], - path: 'samples/BluetoothHDP/index.html', - title: { - en: 'Bluetooth HDP Demo' - }, - description: { - en: 'A sample application that demonstrates how to communicate with a Bluetooth Health Device Profile (HDP) device.' - } - }, - { - tags: ['sample', 'accountsync'], - path: 'samples/BusinessCard/index.html', - title: { - en: 'BusinessCard' - }, - description: { - en: 'An application that demonstrates how to launch the built-in contact picker from within an activity. This sample also uses reflection to ensure that the correct version of the contacts API is used, depending on which API level the application is running under.' - } - }, - { - tags: ['sample', 'accountsync'], - path: 'samples/ContactManager/index.html', - title: { - en: 'Contact Manager' - }, - description: { - en: 'An application that demonstrates how to query the system contacts provider using the ContactsContract API, as well as insert contacts into a specific account.' - } - }, - { - tags: ['sample', 'ui'], - path: 'samples/CubeLiveWallpaper/index.html', - title: { - en: 'Cube Live Wallpaper' - }, - description: { - en: 'An application that demonstrates how to create a live wallpaper and bundle it in an application that users can install on their devices.' - } - }, - { - tags: ['sample', 'new'], - path: 'samples/training/device-management-policy/index.html', - title: { - en: 'Device Policy Management' - }, - description: { - en: 'This is a security-aware sample application that demonstrates the enforcement of device administration policies on Android 2.2 or above platforms.' - } - }, - { - tags: ['sample'], - path: 'samples/Home/index.html', - title: { - en: 'Home' - }, - description: { - en: 'A home screen replacement application.' - } - }, - { - tags: ['sample', 'updated', 'newfeature', 'ui'], - path: 'samples/HoneycombGallery/index.html', - title: { - en: 'Honeycomb Gallery' - }, - description: { - en: 'An image gallery application that demonstrates a variety of new APIs in Android 3.0 (Honeycomb). In addition to providing a tablet-optimized design, it also supports handsets running Android 4.0 (Ice Cream Sandwich) and beyond, so is a good example of how to reuse Fragments to support different screen sizes.' - } - }, - { - tags: ['sample', 'gamedev', 'media'], - path: 'samples/JetBoy/index.html', - title: { - en: 'JetBoy' - }, - description: { - en: 'A game that demonstrates the SONiVOX JET interactive music technology, with JetPlayer.' - } - }, - { - tags: ['sample', 'new'], - path: 'samples/KeyChainDemo/index.html', - title: { - en: 'KeyChain Demo' - }, - description: { - en: 'A demo application to demonstrate how to use KeyChain APIs.' - } - }, - { - tags: ['sample', 'gamedev', 'media'], - path: 'samples/LunarLander/index.html', - title: { - en: 'Lunar Lander' - }, - description: { - en: 'A classic Lunar Lander game.' - } - }, - { - tags: ['sample', 'new'], - path: 'samples/training/ads-and-ux/index.html', - title: { - en: 'Mobile Advertisement Integration' - }, - description: { - en: 'This sample demonstrates the integration of a mobile ad SDK with your application.' - } - }, - { - tags: ['sample', 'ui', 'bestpractice', 'layout'], - path: 'samples/MultiResolution/index.html', - title: { - en: 'Multiple Resolutions' - }, - description: { - en: 'A sample application that shows how to use resource directory qualifiers to provide different resources for different screen configurations.' - } - }, - { - tags: ['sample', 'new', 'bestpractices'], - path: 'samples/newsreader/index.html', - title: { - en: 'News Reader' - }, - description: { - en: 'A sample app demonstrating best practices to support multiple screen sizes and densities.' - } - }, - { - tags: ['sample', 'data'], - path: 'samples/NFCDemo/index.html', - title: { - en: 'NFC Demo' - }, - description: { - en: 'An application for reading NFC Forum Type 2 Tags using the NFC APIs' - } - }, - { - tags: ['sample', 'data'], - path: 'samples/NotePad/index.html', - title: { - en: 'Note Pad' - }, - description: { - en: 'An application for saving notes. Similar (but not identical) to the Notepad tutorial.' - } - }, - { - tags: ['sample', 'media', 'updated'], - path: 'samples/RandomMusicPlayer/index.html', - title: { - en: 'Random Music Player' - }, - description: { - en: 'Demonstrates how to write a multimedia application that plays music from the device and from URLs. It manages media playback from a service and can play music in the background, respecting audio focus changes. Also shows how to use the new Remote Control APIs in API level 14.' - } - }, - { - tags: ['sample', 'newfeature', 'performance', 'gamedev', 'gl', 'updated'], - path: 'samples/RenderScript/index.html', - title: { - en: 'RenderScript' - }, - description: { - en: 'A set of samples that demonstrate how to use various features of the RenderScript APIs.' - } - }, - { - tags: ['sample', 'input', 'new'], - path: 'samples/SpellChecker/SampleSpellCheckerService/index.html', - title: { - en: 'Spell Checker Service' - }, - description: { - en: 'An example spell checker service, using the SpellCheckerService.' - } - }, - { - tags: ['sample', 'input', 'new'], - path: 'samples/SpellChecker/HelloSpellChecker/index.html', - title: { - en: 'Spell Checker Client' - }, - description: { - en: 'An example spell checker client, using the TextServicesManager and SpellCheckerSession.' - } - }, - { - tags: ['sample', 'accountsync', 'updated'], - path: 'samples/SampleSyncAdapter/index.html', - title: { - en: 'SampleSyncAdapter' - }, - description: { - en: 'Demonstrates how an application can communicate with a cloud-based service and synchronize its data with data stored locally in a content provider. The sample uses two related parts of the Android framework — the account manager and the synchronization manager (through a sync adapter).' - } - }, - { - tags: ['sample', 'ui', 'search'], - path: 'samples/SearchableDictionary/index.html', - title: { - en: 'Searchable Dictionary v2' - }, - description: { - en: 'A sample application that demonstrates Android\'s search framework, including how to provide search suggestions for Quick Search Box.' - } - }, - { - tags: ['sample'], - path: 'samples/SipDemo/index.html', - title: { - en: 'SIP Demo' - }, - description: { - en: 'A demo application highlighting how to make internet-based calls with the SIP API.' - } - }, - { - tags: ['sample', 'layout', 'ui'], - path: 'samples/Snake/index.html', - title: { - en: 'Snake' - }, - description: { - en: 'An implementation of the classic game "Snake."' - } - }, - { - tags: ['sample', 'input'], - path: 'samples/SoftKeyboard/index.html', - title: { - en: 'Soft Keyboard' - }, - description: { - en: 'An example of writing an input method for a software keyboard.' - } - }, - { - tags: ['sample', 'testing'], - path: 'samples/Spinner/index.html', - title: { - en: 'Spinner' - }, - description: { - en: 'A simple application that serves as an application under test for the SpinnerTest example.' - } - }, - { - tags: ['sample', 'testing'], - path: 'samples/SpinnerTest/index.html', - title: { - en: 'SpinnerTest' - }, - description: { - en: 'The test application for the Activity Testing tutorial. It tests the Spinner example application.' - } - }, - { - tags: ['sample', 'newfeature', 'widgets'], - path: 'samples/StackWidget/index.html', - title: { - en: 'StackView Widget' - }, - description: { - en: 'Demonstrates how to create a simple collection widget containing a StackView.' - } - }, - { - tags: ['sample', 'newfeature'], - path: 'samples/TicTacToeLib/index.html', - title: { - en: 'TicTacToeLib' - }, - description: { - en: 'An example of an Android library project, a type of project that lets you store and manage shared code and resources in one place, then make them available to your other Android applications.' - } - }, - { - tags: ['sample', 'newfeature',], - path: 'samples/TicTacToeMain/index.html', - title: { - en: 'TicTacToeMain' - }, - description: { - en: 'Demonstrates how an application can make use of shared code and resources stored in an Android library project.' - } - }, - { - tags: ['sample', 'communication', 'new'], - path: 'samples/ToyVpn/index.html', - title: { - en: 'Toy VPN Client' - }, - description: { - en: 'A sample application that illustrates the creation of a custom VPN client.' - } - }, - { - tags: ['sample', 'newfeature'], - path: 'samples/USB/index.html', - title: { - en: 'USB' - }, - description: { - en: 'A set of samples that demonstrate how to use various features of the USB APIs.' - } - }, - { - tags: ['sample', 'data', 'new'], - path: 'samples/VoicemailProviderDemo/index.html', - title: { - en: 'Voicemail Provider' - }, - description: { - en: 'A sample application to demonstrate how to use voicemail content provider APIs in Android 4.0.' - } - }, - { - tags: ['sample','newfeature', 'new'], - path: 'samples/WiFiDirectDemo/index.html', - title: { - en: 'Wi-Fi Direct Demo' - }, - description: { - en: 'A demo application to demonstrate how to use Wi-Fi Direct APIs.' - } - }, - { - tags: ['sample', 'ui', 'widgets'], - path: 'samples/Wiktionary/index.html', - title: { - en: 'Wiktionary' - }, - description: { - en: 'An example of creating interactive widgets for display on the Android home screen.' - } - }, - { - tags: ['sample', 'ui', 'widgets'], - path: 'samples/WiktionarySimple/index.html', - title: { - en: 'Wiktionary (Simplified)' - }, - description: { - en: 'A simple Android home screen widgets example.' - } - }, - { - tags: ['sample', 'widgets', 'newfeature'], - path: 'samples/WeatherListWidget/index.html', - title: { - en: 'Weather List Widget' - }, - description: { - en: 'A more complex collection-widget example which uses a ContentProvider as its data source.' - } - }, - { - tags: ['sample', 'layout'], - path: 'samples/XmlAdapters/index.html', - title: { - en: 'XML Adapters' - }, - description: { - en: 'Binding data to views using XML Adapters examples.' - } - }, - { - tags: ['sample', 'new', 'accessibility'], - path: 'samples/TtsEngine/index.html', - title: { - en: 'Text To Speech Engine' - }, - description: { - en: 'An example Text To Speech engine written using the Android text to speech engine API in Android 4.0.' - } - }, - -///////////////// -/// TUTORIALS /// -///////////////// - - { - tags: ['tutorial'], - path: 'tutorials/hello-world.html', - title: { - en: 'Hello World' - }, - description: { - en: 'Beginning basic application development with the Android SDK.' - } - }, - { - tags: ['tutorial', 'ui', 'layout'], - path: 'tutorials/views/index.html', - title: { - en: 'Hello Views' - }, - description: { - en: 'A walk-through of the various types of layouts and views available in the Android SDK.' - } - }, - { - tags: ['tutorial', 'ui', 'bestpractice'], - path: 'tutorials/localization/index.html', - title: { - en: 'Hello Localization' - }, - description: { - en: 'The basics of localizing your applications for multiple languages and locales.' - } - }, - { - tags: ['tutorial', 'data'], - path: 'tutorials/notepad/index.html', - title: { - en: 'Notepad Tutorial' - }, - description: { - en: 'A multi-part tutorial discussing intermediate-level concepts such as data access.' - } - }, - { - tags: ['tutorial', 'gl'], - path: 'tutorials/opengl/opengl-es10.html', - title: { - en: 'OpenGL ES 1.0' - }, - description: { - en: 'The basics of implementing an application using the OpenGL ES 1.0 APIs.' - } - }, - { - tags: ['tutorial', 'gl'], - path: 'tutorials/opengl/opengl-es20.html', - title: { - en: 'OpenGL ES 2.0' - }, - description: { - en: 'The basics of implementing an application using the OpenGL ES 2.0 APIs.' - } - }, - { - tags: ['tutorial', 'testing'], - path: 'tutorials/testing/helloandroid_test.html', - title: { - en: 'Hello Testing' - }, - description: { - en: 'A basic introduction to the Android testing framework.' - } - }, - { - tags: ['tutorial', 'testing'], - path: 'tutorials/testing/activity_test.html', - title: { - en: 'Activity Testing' - }, - description: { - en: 'A more advanced demonstration of the Android testing framework and tools.' - } - } -]; diff --git a/docs/html/resources/resources_toc.cs b/docs/html/resources/resources_toc.cs deleted file mode 100644 index 9752d994b318..000000000000 --- a/docs/html/resources/resources_toc.cs +++ /dev/null @@ -1,687 +0,0 @@ - - - diff --git a/docs/html/resources/samples/get.jd b/docs/html/resources/samples/get.jd deleted file mode 100644 index 751965ff5b99..000000000000 --- a/docs/html/resources/samples/get.jd +++ /dev/null @@ -1,92 +0,0 @@ -page.title=Getting the Samples -parent.title=Sample Code -parent.link=../browser.html?tag=sample - -@jd:body - -

    Sometimes, the best way to learn how things are done is to look at some -code.

    - -

    To help you get started quickly, the Android SDK includes a variety of sample -code and tutorials that illustrate key concepts and techniques of Android -application development. For example, the samples show the structure of the -manifest file and the use of activities, services, resources, -intents, content providers, and permissions. They also show how to add -specialized capabilities to your apps, such as Bluetooth and Contacts -integration, multiple screens support, Live Wallpaper, and more.

    - -

    The SDK provides the samples both as source code and as browseable HTML, as -described in the sections below. All of the samples included in the SDK are -licensed under the Apache -2.0 license, so feel free to use any of the code in your own applications as -needed!

    - -

    Downloading the Sample Code

    - -

    The SDK sample code is available to you as a set of downloadable SDK -components, each of which contains the samples for a specific Android platform -version. Once you have installed the SDK, you can download one or more samples -component(s) into your SDK environment using the Android SDK Manager -tool, which is pre-installed in the SDK.

    - -

    To download the samples, launch the Android SDK Manager tool and -select one of the samples components from the Available -Packages panel, for example "Samples for SDK API 7". Select -Install Selected, verify and accept the download, then select -Install Accepted to download the component into your SDK. If -you aren't familiar with the Android SDK Manager and how to launch or -use it, please read the Adding -SDK Components document.

    - -

    When the download is complete, you can find the samples sources on your -computer in this location:

    - -

    -<sdk>/samples/android-<level>/ -

    - -

    You can easily create new Android projects with the downloaded samples, modify them -if you'd like, and then run them on an emulator or device.

    - -

    For example, if you are developing in Eclipse with the ADT Plugin, you can -create a project for the "API Demos" sample app by starting a new Android -Project, selecting "Create project from existing source", and then browsing to -the <sdk>/samples/android-<level>/ApiDemos -directory (the samples directory for the platform version you are -using).

    - -

    If you are not working in Eclipse, you can create a project for the API Demos -sample using the android tool, by executing this command:

    - -
    -android update project -s -n API Demos -t <target_ID> -p <path>samples/android-<level>/ApiDemos/
    -
    - -

    Browsing the Sample Code

    - -

    For your convenience, the SDK provides browseable source code for the latest -versions of the samples. You can use your browser to navigate through the -structure of each sample and look at the source code in each of its files.

    - -

    To browse the samples, go to the List of Sample Apps first. -From there you can read a short summary of each sample application and what -types of concepts, features, or APIs it includes. Then, use the links provided -to move through the directories and files of each sample. The browseable source -is generated from the same source code that is downloadable through the Android -SDK Manager, as described above.

    - -

    The browseable samples files are available online, at the Android Developers -site only and are not included in the downloadable offline documentation. -Note that, although samples for several platform versions are available for -download, only the samples for the latest platform version are browseable online. -

    - - -

    More Sample Code

    - -

    If you are looking for more sample code, check out -apps-for-android, a -collection of open source applications that demonstrate various Android APIs.

    - - diff --git a/docs/html/resources/samples/images/ActionBarCompat1.png b/docs/html/resources/samples/images/ActionBarCompat1.png deleted file mode 100644 index 64d3e66f621b..000000000000 Binary files a/docs/html/resources/samples/images/ActionBarCompat1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/ActionBarCompat2.png b/docs/html/resources/samples/images/ActionBarCompat2.png deleted file mode 100644 index 04a7e6c5feca..000000000000 Binary files a/docs/html/resources/samples/images/ActionBarCompat2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/BluetoothChat1.png b/docs/html/resources/samples/images/BluetoothChat1.png deleted file mode 100644 index f87da6a952b1..000000000000 Binary files a/docs/html/resources/samples/images/BluetoothChat1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/BluetoothChat2.png b/docs/html/resources/samples/images/BluetoothChat2.png deleted file mode 100644 index 6218eff5ffea..000000000000 Binary files a/docs/html/resources/samples/images/BluetoothChat2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/BluetoothHDP.png b/docs/html/resources/samples/images/BluetoothHDP.png deleted file mode 100644 index c04cfde46681..000000000000 Binary files a/docs/html/resources/samples/images/BluetoothHDP.png and /dev/null differ diff --git a/docs/html/resources/samples/images/BusinessCard1.png b/docs/html/resources/samples/images/BusinessCard1.png deleted file mode 100644 index 55ff7e565c8d..000000000000 Binary files a/docs/html/resources/samples/images/BusinessCard1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/BusinessCard2.png b/docs/html/resources/samples/images/BusinessCard2.png deleted file mode 100644 index 347c317f185f..000000000000 Binary files a/docs/html/resources/samples/images/BusinessCard2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/ContactManager1.png b/docs/html/resources/samples/images/ContactManager1.png deleted file mode 100644 index d787ffd17d23..000000000000 Binary files a/docs/html/resources/samples/images/ContactManager1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/ContactManager2.png b/docs/html/resources/samples/images/ContactManager2.png deleted file mode 100644 index f7837498ebb2..000000000000 Binary files a/docs/html/resources/samples/images/ContactManager2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/CubeLiveWallpaper1.png b/docs/html/resources/samples/images/CubeLiveWallpaper1.png deleted file mode 100644 index 55bc1e9ed004..000000000000 Binary files a/docs/html/resources/samples/images/CubeLiveWallpaper1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/CubeLiveWallpaper3.png b/docs/html/resources/samples/images/CubeLiveWallpaper3.png deleted file mode 100644 index 2747a88e5750..000000000000 Binary files a/docs/html/resources/samples/images/CubeLiveWallpaper3.png and /dev/null differ diff --git a/docs/html/resources/samples/images/HomeSample.png b/docs/html/resources/samples/images/HomeSample.png deleted file mode 100644 index 990bebbdb485..000000000000 Binary files a/docs/html/resources/samples/images/HomeSample.png and /dev/null differ diff --git a/docs/html/resources/samples/images/JetBoy.png b/docs/html/resources/samples/images/JetBoy.png deleted file mode 100644 index 3da044827d7a..000000000000 Binary files a/docs/html/resources/samples/images/JetBoy.png and /dev/null differ diff --git a/docs/html/resources/samples/images/KeyChainDemo1.png b/docs/html/resources/samples/images/KeyChainDemo1.png deleted file mode 100644 index d426c225a45e..000000000000 Binary files a/docs/html/resources/samples/images/KeyChainDemo1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/KeyChainDemo2.png b/docs/html/resources/samples/images/KeyChainDemo2.png deleted file mode 100755 index e181e5877a5e..000000000000 Binary files a/docs/html/resources/samples/images/KeyChainDemo2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/KeyChainDemo3.png b/docs/html/resources/samples/images/KeyChainDemo3.png deleted file mode 100755 index acfdd89f1a07..000000000000 Binary files a/docs/html/resources/samples/images/KeyChainDemo3.png and /dev/null differ diff --git a/docs/html/resources/samples/images/KeyChainDemo4.png b/docs/html/resources/samples/images/KeyChainDemo4.png deleted file mode 100755 index a9101abaee61..000000000000 Binary files a/docs/html/resources/samples/images/KeyChainDemo4.png and /dev/null differ diff --git a/docs/html/resources/samples/images/MultiResolution.png b/docs/html/resources/samples/images/MultiResolution.png deleted file mode 100644 index 8b245d99532a..000000000000 Binary files a/docs/html/resources/samples/images/MultiResolution.png and /dev/null differ diff --git a/docs/html/resources/samples/images/NewsReader.png b/docs/html/resources/samples/images/NewsReader.png deleted file mode 100644 index f44c6494f09d..000000000000 Binary files a/docs/html/resources/samples/images/NewsReader.png and /dev/null differ diff --git a/docs/html/resources/samples/images/NfcDemo.png b/docs/html/resources/samples/images/NfcDemo.png deleted file mode 100644 index c175d12b5d7e..000000000000 Binary files a/docs/html/resources/samples/images/NfcDemo.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SampleSyncAdapter1.png b/docs/html/resources/samples/images/SampleSyncAdapter1.png deleted file mode 100644 index 242fd3672a6f..000000000000 Binary files a/docs/html/resources/samples/images/SampleSyncAdapter1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SampleSyncAdapter2.png b/docs/html/resources/samples/images/SampleSyncAdapter2.png deleted file mode 100644 index 055beafb55df..000000000000 Binary files a/docs/html/resources/samples/images/SampleSyncAdapter2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SampleSyncAdapter3.png b/docs/html/resources/samples/images/SampleSyncAdapter3.png deleted file mode 100644 index 8ec468e308aa..000000000000 Binary files a/docs/html/resources/samples/images/SampleSyncAdapter3.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SearchableDictionary1.png b/docs/html/resources/samples/images/SearchableDictionary1.png deleted file mode 100644 index ebb4604f8607..000000000000 Binary files a/docs/html/resources/samples/images/SearchableDictionary1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SearchableDictionary2.png b/docs/html/resources/samples/images/SearchableDictionary2.png deleted file mode 100644 index 34746cd15563..000000000000 Binary files a/docs/html/resources/samples/images/SearchableDictionary2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SipDemo.png b/docs/html/resources/samples/images/SipDemo.png deleted file mode 100755 index 999bea944719..000000000000 Binary files a/docs/html/resources/samples/images/SipDemo.png and /dev/null differ diff --git a/docs/html/resources/samples/images/Snake.png b/docs/html/resources/samples/images/Snake.png deleted file mode 100644 index c5211d8835dd..000000000000 Binary files a/docs/html/resources/samples/images/Snake.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SoftKeyboard.png b/docs/html/resources/samples/images/SoftKeyboard.png deleted file mode 100644 index 8a4ec6322cc8..000000000000 Binary files a/docs/html/resources/samples/images/SoftKeyboard.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SpinnerTest1.png b/docs/html/resources/samples/images/SpinnerTest1.png deleted file mode 100644 index 21442f20b983..000000000000 Binary files a/docs/html/resources/samples/images/SpinnerTest1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/SpinnerTest2.png b/docs/html/resources/samples/images/SpinnerTest2.png deleted file mode 100644 index 79ffeb6a929f..000000000000 Binary files a/docs/html/resources/samples/images/SpinnerTest2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/StackWidget.png b/docs/html/resources/samples/images/StackWidget.png deleted file mode 100644 index f2f83a0adcb0..000000000000 Binary files a/docs/html/resources/samples/images/StackWidget.png and /dev/null differ diff --git a/docs/html/resources/samples/images/TicTacToeLib.png b/docs/html/resources/samples/images/TicTacToeLib.png deleted file mode 100644 index 398eff38ffb4..000000000000 Binary files a/docs/html/resources/samples/images/TicTacToeLib.png and /dev/null differ diff --git a/docs/html/resources/samples/images/TicTacToeMain.png b/docs/html/resources/samples/images/TicTacToeMain.png deleted file mode 100644 index 44cee11b9519..000000000000 Binary files a/docs/html/resources/samples/images/TicTacToeMain.png and /dev/null differ diff --git a/docs/html/resources/samples/images/VoicemailProviderDemo.png b/docs/html/resources/samples/images/VoicemailProviderDemo.png deleted file mode 100644 index 1a45d7aa440a..000000000000 Binary files a/docs/html/resources/samples/images/VoicemailProviderDemo.png and /dev/null differ diff --git a/docs/html/resources/samples/images/WeatherListWidget.png b/docs/html/resources/samples/images/WeatherListWidget.png deleted file mode 100644 index f0cbdaff095f..000000000000 Binary files a/docs/html/resources/samples/images/WeatherListWidget.png and /dev/null differ diff --git a/docs/html/resources/samples/images/WifiDirect.png b/docs/html/resources/samples/images/WifiDirect.png deleted file mode 100644 index 86f7f2f2e946..000000000000 Binary files a/docs/html/resources/samples/images/WifiDirect.png and /dev/null differ diff --git a/docs/html/resources/samples/images/Wiktionary.png b/docs/html/resources/samples/images/Wiktionary.png deleted file mode 100644 index 78fee7c4494c..000000000000 Binary files a/docs/html/resources/samples/images/Wiktionary.png and /dev/null differ diff --git a/docs/html/resources/samples/images/WiktionarySimple.png b/docs/html/resources/samples/images/WiktionarySimple.png deleted file mode 100644 index 57cd11d9a5a9..000000000000 Binary files a/docs/html/resources/samples/images/WiktionarySimple.png and /dev/null differ diff --git a/docs/html/resources/samples/images/XmlPhotosAdapter.png b/docs/html/resources/samples/images/XmlPhotosAdapter.png deleted file mode 100644 index c018d54c83ec..000000000000 Binary files a/docs/html/resources/samples/images/XmlPhotosAdapter.png and /dev/null differ diff --git a/docs/html/resources/samples/images/XmlRssReader.png b/docs/html/resources/samples/images/XmlRssReader.png deleted file mode 100644 index 00f841b3482b..000000000000 Binary files a/docs/html/resources/samples/images/XmlRssReader.png and /dev/null differ diff --git a/docs/html/resources/samples/images/hcgallery-phone1.png b/docs/html/resources/samples/images/hcgallery-phone1.png deleted file mode 100644 index 9f0c2805581d..000000000000 Binary files a/docs/html/resources/samples/images/hcgallery-phone1.png and /dev/null differ diff --git a/docs/html/resources/samples/images/hcgallery-phone2.png b/docs/html/resources/samples/images/hcgallery-phone2.png deleted file mode 100644 index b049a6559ab8..000000000000 Binary files a/docs/html/resources/samples/images/hcgallery-phone2.png and /dev/null differ diff --git a/docs/html/resources/samples/images/hcgallery.png b/docs/html/resources/samples/images/hcgallery.png deleted file mode 100644 index 42b018341fc2..000000000000 Binary files a/docs/html/resources/samples/images/hcgallery.png and /dev/null differ diff --git a/docs/html/resources/samples/images/randommusicplayer.png b/docs/html/resources/samples/images/randommusicplayer.png deleted file mode 100644 index e16e0677da00..000000000000 Binary files a/docs/html/resources/samples/images/randommusicplayer.png and /dev/null differ diff --git a/docs/html/resources/samples/images/sample_lunarlander.png b/docs/html/resources/samples/images/sample_lunarlander.png deleted file mode 100644 index a2ff75ab6467..000000000000 Binary files a/docs/html/resources/samples/images/sample_lunarlander.png and /dev/null differ diff --git a/docs/html/resources/samples/images/sample_note.png b/docs/html/resources/samples/images/sample_note.png deleted file mode 100644 index 8fc9dcc0e627..000000000000 Binary files a/docs/html/resources/samples/images/sample_note.png and /dev/null differ diff --git a/docs/html/resources/samples/images/sample_notepad.png b/docs/html/resources/samples/images/sample_notepad.png deleted file mode 100644 index 46f221104b20..000000000000 Binary files a/docs/html/resources/samples/images/sample_notepad.png and /dev/null differ diff --git a/docs/html/resources/samples/images/sample_notepadtest_junit.png b/docs/html/resources/samples/images/sample_notepadtest_junit.png deleted file mode 100644 index 4cda54e94eae..000000000000 Binary files a/docs/html/resources/samples/images/sample_notepadtest_junit.png and /dev/null differ diff --git a/docs/html/resources/samples/images/vpn-confirmation.png b/docs/html/resources/samples/images/vpn-confirmation.png deleted file mode 100755 index ae2e58332089..000000000000 Binary files a/docs/html/resources/samples/images/vpn-confirmation.png and /dev/null differ diff --git a/docs/html/resources/samples/index.jd b/docs/html/resources/samples/index.jd deleted file mode 100644 index acb80e826781..000000000000 --- a/docs/html/resources/samples/index.jd +++ /dev/null @@ -1,11 +0,0 @@ -page.title=List of Sample Apps -@jd:body - - - -

    This document has moved. Please go to List of Sample -Apps.

    - diff --git a/docs/html/resources/topics.jd b/docs/html/resources/topics.jd deleted file mode 100644 index b5960ffcbebf..000000000000 --- a/docs/html/resources/topics.jd +++ /dev/null @@ -1,72 +0,0 @@ -page.title=Technical Resource Topics -@jd:body - - - -

    -You can browse the list of technical resources by topic by clicking on the -links below. Over time, as more topics are added, they will be added to the -list below. -

    - - - - - -
    - - \ No newline at end of file diff --git a/docs/html/resources/tutorials/hello-world.jd b/docs/html/resources/tutorials/hello-world.jd deleted file mode 100644 index 70ba06c002e4..000000000000 --- a/docs/html/resources/tutorials/hello-world.jd +++ /dev/null @@ -1,607 +0,0 @@ -page.title=Hello, World -parent.title=Tutorials -parent.link=../browser.html?tag=tutorial -@jd:body - - -

    As a developer, you know that the first impression of a development framework is how easy it is -to write "Hello, World." Well, on Android, it's pretty easy. It's particularly easy if you're using -Eclipse as your IDE, because we've provided a great plugin that handles your project creation and -management to greatly speed up your development cycles.

    - -

    This tutorial assumes that you're using Eclipse. If you're using the command line, see -Building and Running from the -Command Line. You can then return to this tutorial and ignore anything about Eclipse.

    - -

    Before you start, you should already have the SDK installed, and if you're -using Eclipse, you should have installed the ADT plugin as well. If you have not -installed these, see Installing the -Android SDK and return here when you've completed the installation.

    - -

    Install a Platform

    - -

    To run the Hello World application, you need to install at least one Android -platform in your SDK environment. If you have not already performed this step, -you need to do it now.

    - -

    To install a platform in Eclipse:

    - -
      - -
    1. In the Android SDK Manager, choose Available -Packages in the left panel.
    2. - -
    3. In the right panel, expand the Android Repository list to display -the components available for installation.
    4. - -
    5. Select at least one platform to install, and click Install -Selected. If you aren't sure which platform to install, use the latest -version.
    6. -
    - -

    Create an AVD

    - - - -

    In this tutorial, you will run your application in the Android Emulator. -Before you can launch the emulator, you must create an -Android Virtual Device (AVD). An AVD defines the system image and -device settings used by the emulator.

    - - - -

    To create an AVD:

    -
      -
    1. In Eclipse, select Window > AVD Manager.
    2. -
    3. Select Virtual Devices in the left panel.
    4. - -
    5. Click New.... -

      The Create New AVD dialog appears.

      -
    6. -
    7. Type the name of the AVD, such as "my_avd".
    8. -
    9. Choose a target. -

      The target is the platform (that is, the version of the Android SDK, such as 2.3.3) you want - to run on the emulator. For this tutorial, choose the latest platform that you have installed - and ignore the rest of the fields.

      -
    10. -
    11. Click Create AVD.
    12. -
    -

    Create a New Android Project

    - -

    After you've created an AVD you can move to the next step and start a new Android project in -Eclipse.

    - -
      -
    1. In Eclipse, select File > New > Project.... -

      If the ADT - Plugin for Eclipse has been successfully installed, the resulting dialog - should have a folder labeled "Android" which should contain - "Android Project". (After you create one or more Android projects, an entry for - "Android XML File" will also be available.)

      -
    2. - -
    3. Select "Android Project" and click Next.
      - -
    4. - -
    5. Fill in the project details with the following values: -
        -
      • Project name: HelloAndroid
      • -
      • Build Target: Select a platform version that is equal to or lower than the - target you chose for your AVD.
      • -
      • Application name: Hello, Android
      • -
      • Package name: com.example.helloandroid (or your own private namespace)
      • -
      • Create Activity: HelloAndroid
      • -
      -

      Click Finish.

      - - - -

      Here is a description of each field:

      - -
      -
      Project Name
      -
      This is the Eclipse project name — the name of the directory - that contains the project files.
      -
      Build Target
      -
      This is the version of the Android SDK that you're using to build your - application. For example, if you choose Android 2.1, your application will be - compiled against the Android 2.1 platform library. The target you choose here - does not have to match the target you chose for your AVD; however, the target must - be equal to or lower than the target you chose for your AVD. Android - applications are forward-compatible, which means an application will run on the - platform against which it is built as well as all platforms that are released in the - future. For example, an application that is built against the 2.1 platform library - will run normally on an AVD or device that is running the 2.3.3. The reverse is not - true.
      -
      Application Name
      -
      This is the human-readable title for your application — the name that - appears on the Android device.
      -
      Package Name
      -
      This is the package namespace (following the same rules as for - packages in the Java programming language) that you want all your source code to - reside under. This also sets the package name under which the stub - Activity is generated. -

      Your package name must be unique across - all packages installed on the Android system; for this reason, it's - important to use a standard domain-style package for your - applications. The example above uses the "com.example" namespace, which is - a namespace reserved for example documentation — - when you develop your own applications, you should use a namespace that's - appropriate to your organization or entity.

      -
      Create Activity
      -
      This is the name for the class stub that is generated by the plugin. - This is a subclass of Android's {@link android.app.Activity} class. An - Activity is simply a class that can run and do work. It can create a UI if it - chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an - Activity is almost always used as the basis for an application.
      -
      Min SDK Version
      -
      This value specifies the minimum API Level on which your application will run. - The Min SDK Version should be the same as the Build Target you - chose. For example, if the Build Target is Android 2.1, then the Min - SDK Version should be 7 or lower (it can never be higher than 7). For more - information, see - Android API Levels. -
      -
      - -

      Other fields: The checkbox for "Use default location" allows you to change - the location on disk where the project's files are generated and stored.

      -
    6. -
    - -

    Your Android project is now ready. It should be visible in the Package Explorer on the left. Open -the HelloAndroid.java file, located inside HelloAndroid > src > -com.example.helloandroid). It should look like this:

    - -
    -package com.example.helloandroid;
    -
    -import android.app.Activity;
    -import android.os.Bundle;
    -
    -public class HelloAndroid extends Activity {
    -    /** Called when the activity is first created. */
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        setContentView(R.layout.main);
    -    }
    -}
    - -

    Notice that the class is based on the {@link android.app.Activity} class. An Activity is a -single application entity that is used to perform actions. An application may have many separate -activities, but the user interacts with them one at a time. The -{@link android.app.Activity#onCreate(Bundle) onCreate()} method -is called by the Android system when your Activity starts — -it is where you should perform all initialization and UI setup. An activity is not required to -have a user interface, but usually does.

    - -

    Now let's modify some code!

    - - -

    Construct the UI

    - -

    Take a look at the revised code below and then make the same changes to your HelloAndroid class. -The bold items are lines that have been added.

    - -
    -package com.example.helloandroid;
    -
    -import android.app.Activity;
    -import android.os.Bundle;
    -import android.widget.TextView;
    -
    -public class HelloAndroid extends Activity {
    -   /** Called when the activity is first created. */
    -   @Override
    -   public void onCreate(Bundle savedInstanceState) {
    -       super.onCreate(savedInstanceState);
    -       TextView tv = new TextView(this);
    -       tv.setText("Hello, Android");
    -       setContentView(tv);
    -   }
    -}
    - -

    Tip: An easy way to add import packages to your project is -to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse -shortcut that identifies missing packages based on your code and adds them for you. You may have -to expand the import statements in your code for this to work.

    - -

    An Android user interface is composed of hierarchies of objects called -Views. A {@link android.view.View} is a drawable object used as an element in your UI layout, -such as a button, image, or (in this case) a text label. Each of these objects is a subclass -of the View class and the subclass that handles text is {@link android.widget.TextView}.

    - -

    In this change, you create a TextView with the class constructor, which accepts -an Android {@link android.content.Context} instance as its parameter. A -Context is a handle to the system; it provides services like -resolving resources, obtaining access to databases and preferences, and so -on. The Activity class inherits from Context, and because your -HelloAndroid class is a subclass of Activity, it is also a Context. So, you can -pass this as your Context reference to the TextView.

    - -

    Next, you define the text content with -{@link android.widget.TextView#setText(CharSequence) setText()}.

    - -

    Finally, you pass the TextView to -{@link android.app.Activity#setContentView(View) setContentView()} in order to -display it as the content for the Activity UI. If your Activity doesn't -call this method, then no UI is present and the system will display a blank -screen.

    - -

    There it is — "Hello, World" in Android! The next step, of course, is -to see it running.

    - - -

    Run the Application

    - -

    The Eclipse plugin makes it easy to run your applications:

    - -
      -
    1. Select Run > Run.
    2. -
    3. Select "Android Application".
    4. -
    - - - -

    The Eclipse plugin automatically creates a new run configuration for your project -and then launches the Android Emulator. Depending on your environment, the Android -emulator might take several minutes to boot fully, so please be patient. When the -emulator is booted, the Eclipse plugin installs your application -and launches the default Activity. You should now see something like this:

    - - - -

    The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin -creates this automatically (the string is defined in the res/values/strings.xml file and referenced -by your AndroidManifest.xml file). The text below the title is the actual text that you have -created in the TextView object.

    - -

    That concludes the basic "Hello World" tutorial, but you should continue reading for some more -valuable information about developing Android applications.

    - - -

    Upgrade the UI to an XML Layout

    - -

    The "Hello, World" example you just completed uses what is called a "programmatic" -UI layout. This means that you constructed and built your application's UI -directly in source code. If you've done much UI programming, you're -probably familiar with how brittle that approach can sometimes be: small -changes in layout can result in big source-code headaches. It's also -easy to forget to properly connect Views together, which can result in errors in -your layout and wasted time debugging your code.

    - -

    That's why Android provides an alternate UI construction model: XML-based -layout files. The easiest way to explain this concept is to show an -example. Here's an XML layout file that is identical in behavior to the -programmatically-constructed example:

    - -
    <?xml version="1.0" encoding="utf-8"?>
    -<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    -  android:id="@+id/textview"
    -  android:layout_width="fill_parent"
    -  android:layout_height="fill_parent"
    -  android:text="@string/hello"/>
    - -

    The general structure of an Android XML layout file is simple: it's a tree -of XML elements, wherein each node is the name of a View class -(this example, however, is just one View element). You can use the -name of any class that extends {@link android.view.View} as an element in your XML layouts, -including custom View classes you define in your own code. This -structure makes it easy to quickly build up UIs, using a more simple -structure and syntax than you would use in a programmatic layout. This model is inspired -by the web development model, wherein you can separate the presentation of your -application (its UI) from the application logic used to fetch and fill in data.

    - -

    In the above XML example, there's just one View element: the TextView, -which has five XML attributes. Here's a summary of what they mean:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Attribute - - Meaning -
    - xmlns:android - - This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute.
    -
    - android:id - - This attribute assigns a unique identifier to the TextView element. - You can use the assigned ID to reference this View from your source code or from other - XML resource declarations. -
    - android:layout_width - - This attribute defines how much of the available width on the screen this View should consume. - In this case, it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means.
    -
    - android:layout_height - - This is just like android:layout_width, except that it refers to available screen height. -
    - android:text - - This sets the text that the TextView should display. In this example, you use a string - resource instead of a hard-coded string value. - The hello string is defined in the res/values/strings.xml file. This is the - recommended practice for inserting strings to your application, because it makes the localization - of your application to other languages graceful, without need to hard-code changes to the layout file. - For more information, see Resources - and Internationalization. -
    - - -

    These XML layout files belong in the res/layout/ directory of your project. The "res" is -short for "resources" and the directory contains all the non-code assets that -your application requires. In addition to layout files, resources also include assets -such as images, sounds, and localized strings.

    - - - -

    The Eclipse plugin automatically creates one of these layout files for you: main.xml. -In the "Hello World" application you just completed, this file was ignored and you created a -layout programmatically. This was meant to teach you more -about the Android framework, but you should almost always define your layout -in an XML file instead of in your code. -The following procedures will instruct you how to change your -existing application to use an XML layout.

    - -
      -
    1. In the Eclipse Package Explorer, expand the -/res/layout/ folder and open main.xml (once opened, you might need to click -the "main.xml" tab at the bottom of the window to see the XML source). Replace the contents with -the following XML: - -
      <?xml version="1.0" encoding="utf-8"?>
      -<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      -  android:id="@+id/textview"
      -  android:layout_width="fill_parent"
      -  android:layout_height="fill_parent"
      -  android:text="@string/hello"/>
      -

      Save the file.

      -
    2. - -
    3. Inside the res/values/ folder, open strings.xml. -This is where you should save all default text strings for your user interface. If you're using Eclipse, then -ADT will have started you with two strings, hello and app_name. -Revise hello to something else. Perhaps "Hello, Android! I am a string resource!" -The entire file should now look like this: -
      -<?xml version="1.0" encoding="utf-8"?>
      -<resources>
      -    <string name="hello">Hello, Android! I am a string resource!</string>
      -    <string name="app_name">Hello, Android</string>
      -</resources>
      -
      -
    4. - -
    5. Now open and modify your HelloAndroid class and use the -XML layout. Edit the file to look like this: -
      -package com.example.helloandroid;
      -
      -import android.app.Activity;
      -import android.os.Bundle;
      -
      -public class HelloAndroid extends Activity {
      -    /** Called when the activity is first created. */
      -    @Override
      -    public void onCreate(Bundle savedInstanceState) {
      -        super.onCreate(savedInstanceState);
      -        setContentView(R.layout.main);
      -    }
      -}
      - -

      When you make this change, type it by hand to try the -code-completion feature. As you begin typing "R.layout.main" the plugin will offer you -suggestions. You'll find that it helps in a lot of situations.

      - -

      Instead of passing setContentView() a View object, you give it a reference -to the layout resource. -The resource is identified as R.layout.main, which is actually a compiled object representation of -the layout defined in /res/layout/main.xml. The Eclipse plugin automatically creates this reference for -you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you -when you run Ant to build the application. (More about the R class in a moment.)

      -
    6. -
    - -

    Now re-run your application — because you've created a launch configuration, all -you need to do is click the green arrow icon to run, or select -Run > Run History > Android Activity. Other than the change to the TextView -string, the application looks the same. After all, the point was to show that the two different -layout approaches produce identical results.

    - -

    Note: You may have to unlock the screen on the emulator to see -your application — just as you would unlock the screen on a device. If you have problems -running the emulator, see Using the -Android Emulator.

    - -

    Continue reading for an introduction -to debugging and a little more information on using other IDEs. When you're ready to learn more, -read Application -Fundamentals for an introduction to all the elements that make Android applications work. -Also refer to the Developer's Guide -introduction page for an overview of the Dev Guide documentation.

    - - -
    -

    R class

    -

    In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder). -It should look something like this:

    - -
    -package com.example.helloandroid;
    -
    -public final class R {
    -    public static final class attr {
    -    }
    -    public static final class drawable {
    -        public static final int icon=0x7f020000;
    -    }
    -    public static final class id {
    -        public static final int textview=0x7f050000;
    -    }
    -    public static final class layout {
    -        public static final int main=0x7f030000;
    -    }
    -    public static final class string {
    -        public static final int app_name=0x7f040001;
    -        public static final int hello=0x7f040000;
    -    }
    -}
    -
    - -

    A project's R.java file is an index into all the resources defined in the -file. You use this class in your source code as a sort of short-hand -way to refer to resources you've included in your project. This is -particularly powerful with the code-completion features of IDEs like Eclipse -because it lets you quickly and interactively locate the specific reference -you're looking for.

    - -

    It's possible yours looks slightly different than this (perhaps the hexadecimal values are -different). -For now, notice the inner class named "layout", and its -member field "main". The Eclipse plugin noticed the XML -layout file named main.xml and generated a class for it here. As you add other -resources to your project (such as strings in the res/values/string.xml file or drawables inside -the res/drawable/ directory) you'll see R.java change to keep up.

    -

    When not using Eclipse, this class file will be generated for you at build time (with the Ant tool).

    -

    You should never edit this file by hand.

    -
    - -

    Debug Your Project

    - -

    The Android Plugin for Eclipse also has excellent integration with the Eclipse -debugger. To demonstrate this, introduce a bug into -your code. Change your HelloAndroid source code to look like this:

    - -
    -package com.example.helloandroid;
    -
    -import android.app.Activity;
    -import android.os.Bundle;
    -
    -public class HelloAndroid extends Activity {
    -    /** Called when the activity is first created. */
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        Object o = null;
    -        o.toString();
    -        setContentView(R.layout.main);
    -    }
    -}
    - -

    This change simply introduces a NullPointerException into your code. If -you run your application again, you'll eventually see this:

    - - - -

    Press "Force Quit" to terminate the application and close the emulator window.

    - -

    To find out more about the error, set a breakpoint in your source code -on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello, -Android from the menu to enter debug mode. Your app will restart in the -emulator, but this time it will suspend when it reaches the breakpoint you -set. You can then step through the code in Eclipse's Debug Perspective, -just as you would for any other application.

    - - - - -

    Creating the Project without Eclipse

    - -

    If you don't use Eclipse (such as if you prefer another IDE, or simply use text - editors and command line tools) then the Eclipse plugin can't help you. - Don't worry though — you don't lose any functionality just because you don't - use Eclipse.

    - -

    The Android Plugin for Eclipse is really just a wrapper around a set of tools - included with the Android SDK. (These tools, like the emulator, aapt, adb, - ddms, and others are documented elsewhere.) - Thus, it's possible to - wrap those tools with another tool, such as an 'ant' build file.

    - -

    The Android SDK includes a tool named "android" that can be - used to create all the source code and directory stubs for your project, as well - as an ant-compatible build.xml file. This allows you to build your project - from the command line, or integrate it with the IDE of your choice.

    - -

    For example, to create a HelloAndroid project similar to the one created - in Eclipse, use this command:

    - -
    -android create project \
    -    --package com.example.helloandroid \
    -    --activity HelloAndroid \
    -    --target 2 \
    -    --path <path-to-your-project>/HelloAndroid
    -
    - -

    This creates the required folders and files for the project at the location - defined by the path.

    - -

    For more information on how to use the SDK tools to create and build projects, please read -Developing in Other IDEs.

    \ No newline at end of file diff --git a/docs/html/resources/tutorials/index.html b/docs/html/resources/tutorials/index.html deleted file mode 100644 index 4881acf44581..000000000000 --- a/docs/html/resources/tutorials/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - -click here if you are not redirected. - - \ No newline at end of file diff --git a/docs/html/resources/tutorials/localization/index.jd b/docs/html/resources/tutorials/localization/index.jd deleted file mode 100755 index de4433b3092a..000000000000 --- a/docs/html/resources/tutorials/localization/index.jd +++ /dev/null @@ -1,595 +0,0 @@ -page.title=Hello, L10N -parent.title=Tutorials -parent.link=../../browser.html?tag=tutorial -@jd:body - -
    -
    -

    In this document

    -
      -
    1. Create an Unlocalized App -
        -
      1. Create the Project and Layout
      2. -
      3. Create Default Resources
      4. -
      -
    2. -
    3. Run the Unlocalized App
    4. -
    5. Plan the Localization
    6. -
    7. Localize the App -
        -
      1. Localize the Strings
      2. -
      3. Localize the Images
      4. -
      -
    8. -
    9. Run and Test the Localized App
    10. -
    -

    See also

    -
      -
    1. {@link android.widget.Button}
    2. -
    3. {@link android.widget.TextView}
    4. -
    5. {@link android.app.AlertDialog}
    6. -
    -
    -
    - -

    In this tutorial, we will create a Hello, L10N application that uses the -Android framework to selectively load resources. Then we will localize the -application by adding resources to the res/ directory.

    - -

    This tutorial uses the practices described in the Localization -document.

    - - -

    Create an Unlocalized Application

    - -

    The first version of the Hello, L10N application will use only the default -resource directories (res/drawable, res/layout, and -res/values). These resources are not localized — they are the -graphics, layout, and strings that we expect the application to use most often. -When a user runs the application in the default locale, or in a locale that the -application does not specifically support, the application will load resources -from these default directories.

    - -

    The application consists of a simple user interface that displays two -{@link android.widget.TextView} objects and a {@link android.widget.Button} image with a - background image of a national flag. When clicked, the button displays an -{@link android.app.AlertDialog} object that shows additional text.

    - -

    Create the Project and Layout

    - -

    For this application, the default language will be British English and the -default location the United Kingdom.

    - -
      -
    1. Start a new project and Activity called "HelloL10N." If you are -using Eclipse, fill out these values in the New Android Project wizard: -
        -
      • Project name: HelloL10N
      • -
      • Application name: Hello, L10N
      • -
      • Package name: com.example.hellol10n (or your own private -namespace)
      • -
      • Create Activity: HelloL10N
      • -
      • Min SDK Version: 3
      • -
      -

      The basic project contains a res/ directory with -subdirectories for the three most common types of resources: graphics -(res/drawable/), layouts (res/layout/) and strings -(res/values/). Most of the localization work you do later in this -tutorial will involve adding more subdirectories to the res/ -directory.

      - plain project -
    2. -
    3. Open the res/layout/main.xml file and replace it with the -following code: -
      <?xml version="1.0" encoding="utf-8"?>
      -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      -    android:orientation="vertical"
      -    android:layout_width="fill_parent"
      -    android:layout_height="fill_parent"
      -    >
      -<TextView
      -    android:layout_width="fill_parent" 
      -    android:layout_height="wrap_content"
      -    android:gravity="center_horizontal"
      -    android:text="@string/text_a"
      -    />
      -<TextView
      -    android:layout_width="fill_parent"
      -    android:layout_height="wrap_content"
      -    android:gravity="center_horizontal"
      -    android:text="@string/text_b"
      -    />
      -<Button
      -    android:id="@+id/flag_button"
      -    android:layout_width="wrap_content"
      -    android:layout_height="wrap_content"
      -    android:layout_gravity="center"
      -    />
      -</LinearLayout>
      -    
      - -

      The LinearLayout has two {@link android.widget.TextView} objects that will -display localized text and one {@link android.widget.Button} that shows a flag. -

      -
    4. -
    - -

    Create Default Resources

    - -

    The layout refers to resources that need to be defined.

    - -
      -
    1. Create default text strings. To do this, open the res/values/strings.xml file and replace it with the following code:
      -
      <?xml version="1.0" encoding="utf-8"?>
      -<resources>
      -    <string name="app_name">Hello, L10N</string>
      -    <string name="text_a">Shall I compare thee to a summer"'"s day?</string>
      -    <string name="text_b">Thou art more lovely and more temperate.</string>
      -    <string name="dialog_title">No Localisation</string>
      -    <string name="dialog_text">This dialog box"'"s strings are not localised. For every locale, the text here will come from values/strings.xml.</string>
      -</resources>
      - -

      This code provides British English text for each string that the application -will use. When we localize this application, we will provide alternate text in -German, French, and Japanese for some of the strings.

      -
    2. -
    3. Add a default flag graphic to the res/drawable folder by -saving flag.png as -res/drawable/flag.png. When the application is not localized, it -will show a British flag.
      - -
    4. -
    5. Open HelloL10N.java (in the src/ directory) and add the -following code inside the onCreate() method (after -setContentView). - -
      // assign flag.png to the button, loading correct flag image for current locale
      -Button b;
      -(b = (Button)findViewById(R.id.flag_button)).setBackgroundDrawable(this.getResources().getDrawable(R.drawable.flag));
      -
      -// build dialog box to display when user clicks the flag
      -AlertDialog.Builder builder = new AlertDialog.Builder(this);
      -builder.setMessage(R.string.dialog_text)
      -    .setCancelable(false)
      -    .setTitle(R.string.dialog_title)
      -    .setPositiveButton("Done", new DialogInterface.OnClickListener() {
      -        public void onClick(DialogInterface dialog, int id) {
      -        dialog.dismiss();
      -        }
      -    });
      -final AlertDialog alert = builder.create();
      -
      -// set click listener on the flag to show the dialog box 
      -b.setOnClickListener(new View.OnClickListener() {
      -    public void onClick(View v) {
      -	alert.show();
      -    }
      -    });
      - -

      Tip: In Eclipse, use -Ctrl-Shift-O (Cmd-Shift-O, on Mac) to find and -add missing import packages to your project, then save the HelloL10N.java -file.

      - -

      The code that you added does the following:

      - -
        -
      • It assigns the correct flag icon to the button. - For now, no resources are defined other than the default, so this code -will always assign the contents of res/drawable/flag.png (the -British flag) as the flag icon, no matter what the locale. Once we add more -flags for different locales, this code will sometimes assign a different flag. -
      • -
      • It creates an {@link android.app.AlertDialog} object and sets a click listener so that when the -user clicks the button, the AlertDialog will display. - We will not localize the dialog text; -the AlertDialog will always display the dialog_text that is located -within res/values/strings.xml.
      • -
      - -
    6. -
    - -

    The project structure now looks like this:

    - - nonlocalized - -

    Tip: If you will want to run the application on -a device and not just on an emulator, open AndroidManifest.xml and -add android:debuggable="true" inside the -<application> element. For information about setting up the -device itself so it can run applications from your system, see Developing on a Device.

    - - -

    Run the Unlocalized Application

    - -

    Save the project and run the application to see how it works. No matter what -locale your device or emulator is set to, the application runs the same way. It -should look something like this:

    - - - - - - - - - - -
    The unlocalized application, running in any locale:After clicking the flag, in any locale:
    nonlocalized2
    -

    Plan the Localization

    -

    The first step in localizing an application is to plan how the application -will render differently in different locales. In this application, the default -locale will be the United Kingdom. We will add some locale-specific information -for Germany, France, Canada, Japan, and the United States. Table 1 shows the -plan for how the application will appear in different locales.

    - -

    Table 1

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Region /
    - Language
    United KingdomGermanyFranceCanadaJapanUnited StatesOther Location

    - English
    British English text; British flag (default)-- British English text; Canadian flag- British English text; U.S. flag British English text; British flag (default)
    German-German text for app_name, text_a and -text_b; German flag----German text for app_name, text_a and -text_b; British flag
    French--French text for app_name, text_a and -text_b; French flagFrench text for app_name, text_a and -text_b; Canadian flag--French text for app_name, text_a and -text_b; British flag
    Japanese----Japanese text for text_a and text_b; Japanese -flag-Japanese text for text_a and text_b; British -flag
    Other Language------ British English text; British flag (default)
    - -

    Note that other behaviors are possible; for example, the -application could support Canadian English or U.S. English text. But given the -small amount of text involved, adding more versions of English would not make -this application more useful.

    - -

    As shown in the table above, the plan calls for five flag icons in addition -to the British flag that is already in the res/drawable/ folder. It -also calls for three sets of text strings other than the text that is in -res/values/strings.xml.

    - -

    Table 2 shows where the needed text strings and flag icons will go, and -specifies which ones will be loaded for which locales. (For more about the -locale codes, see -Alternate Resources.)

    -

    Table 2

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Locale CodeLanguage / CountryLocation of strings.xmlLocation of flag.png
    DefaultEnglish / United Kingdomres/values/res/drawable/
    de-rDEGerman / Germanyres/values-de/res/drawable-de-rDE/
    fr-rFRFrench / Franceres/values-fr/res/drawable-fr-rFR/
    fr-rCAFrench / Canadares/values-fr/res/drawable-fr-rCA/
    en-rCAEnglish / Canada(res/values/)res/drawable-en-rCA/
    ja-rJPJapanese / Japanres/values-ja/res/drawable-ja-rJP/
    en-rUSEnglish / United States(res/values/)res/drawable-en-rUS/
    - -

    Tip: A folder qualifer cannot specify a region -without a language. Having a folder named res/drawable-rCA/, -for example, will prevent the application from compiling.

    - -

    At run time, the application will select a set of resources to load based on the locale -that is set in the user's device. In cases where no locale-specific resources -are available, the application will fall back on the defaults.

    - -

    For example, assume that the device's language is set to German and its -location to Switzerland. Because this application does not have a -res/drawable-de-rCH/ directory with a flag.png file in it, the system -will fall back on the default, which is the UK flag located in -res/drawable/flag.png. The language used will be German. Showing a -British flag to German speakers in Switzerland is not ideal, but for now we will -just leave the behavior as it is. There are several ways you could improve this -application's behavior if you wanted to:

    - -
      -
    • Use a generic default icon. In this application, it might be something -that represents Shakespeare.
    • -
    • Create a res/drawable-de/ folder that includes an icon that -the application will use whenever the language is set to German but the location -is not Germany.
    • -
    - - -

    Localize the Application

    - -

    Localize the Strings

    - -

    The application requires three more strings.xml files, one -each for German, French, and Japanese. To create these resource files within -Eclipse:

    - -
      -
    1. Select File > New > Android -XML File to open the New Android XML File wizard. You can also open -the wizard by clicking its icon in the toolbar:
      -
    2. -
    3. Select L10N for the Project field, and type strings.xml into -the File field. In the left-hand list, select Language, then click the right arrow.
      -res_file_copy
    4. -
    5. Type de in the Language box and click Finish.
      - res_file_copy -

      A new file, res/values-de/strings.xml, now appears among the project -files.

    6. -
    7. Repeat the steps twice more, for the language codes fr and - ja. -Now the project includes these new skeleton files:
      - res/values-de/strings.xml
      - res/values-fr/strings.xml
      - res/values-ja/strings.xml
      -
    8. -
    9. Add localized text to the new files. To do -this, open the res/values-<qualifier>/strings.xml files and -replace the code as follows:
    10. -
    - - - - - - - - - - - - - - - - - - -
    FileReplace the contents with the following code:
    res/values-de/strings.xml
    <?xml version="1.0" encoding="utf-8"?>
    -<resources>
    -    <string name="app_name">Hallo, Lokalisierung</string>
    -    <string name="text_a">Soll ich dich einem Sommertag vergleichen,</string>
    -    <string name="text_b">Der du viel lieblicher und sanfter bist?</string>
    -</resources>
    res/values-fr/strings.xml
    <?xml version="1.0" encoding="utf-8"?>
    -<resources>
    -    <string name="app_name">Bonjour, Localisation</string>
    -    <string name="text_a">Irai-je te comparer au jour d'été?</string>
    -    <string name="text_b">Tu es plus tendre et bien plus tempéré.</string>
    -</resources> 
    res/values-ja/strings.xml -
    <?xml version="1.0" encoding="utf-8"?>
    -<resources>
    -    <string name="text_a">あなたをなにかにたとえるとしたら夏の一日でしょうか?</string>
    -    <string name="text_b">だがあなたはもっと美しく、もっとおだやかです。</string>
    -</resources>
    - -

    Tip: In the -values-<qualifier>/strings.xml files, you only need to -include text for strings that are different from the default strings. For -example, when the application runs on a device that is configured for Japanese, -the plan is for text_a and text_b to be in Japanese -while all the other text is in English, so -res/values-ja/strings.xml only needs to include text_a -and text_b.

    - -

    Localize the Images

    - -

    As shown in Table 2, the application needs six more -drawable folders, each containing a flag.png icon. Add the needed -icons and folders to your project:

    - -
      -
    1. Save this German flag icon -as res/drawable-de-rDE/flag.png in the application's project -workspace. -

      For example:

      -
        -
      1. Click the link to open the flag image.
      2. -
      3. Save the image in -your-workspace/HelloL10N/res/drawable-de-rDE/ .
      4. -
      -
    2. -
    3. Save this French flag icon -as res/drawable-fr-rFR/flag.png in the application's project -workspace.
    4. -
    5. Save this Canadian flag icon -as res/drawable-fr-rCA/flag.png in the project workspace.
    6. -
    7. Save the Canadian flag icon -again, this time as res/drawable-en-rCA/flag.png in the project -workspace. (Why not have just one folder that contains the Canadian -flag? Because a folder qualifer cannot specify a region without a language. -You cannot have a folder named drawable-rCA/; instead you must -create two separate folders, one for each of the Canadian languages represented -in the application.)
    8. -
    9. Save this Japanese flag icon -as res/drawable-ja-rJP/flag.png in the project workspace.
    10. -
    11. Save this United States flag -icon as res/drawable-en-rUS/flag.png in the project workspace. -
    12. -
    - -

    If you are using Eclipse, refresh the project (F5). The new -res/drawable-<qualifier>/ folders should appear in the -project view.

    - - -

    Run and Test the Localized Application

    - -

    Once you've added the localized string and image resources, you are ready to - run the application and test its handling of them. To change the locale - on a device or in the emulator, use the Settings -application (Home > Menu > Settings > Locale & text > Select -locale). Depending on how a device was configured, it might not offer any -alternate locales via the Settings application, or might offer only a few. The -emulator, on the other hand, will offer a selection of all the locales that are -available in the Android system image.

    - -

    To set the emulator to a locale that is not available in the system image, -use the Custom Locale application, which is available in the Application -tab:

    - -

    custom locale app

    - -

    To switch to a new locale, long-press a locale name:

    - -

    using custom locale

    - -

    For a list of locales available on different versions of the Android platform, -refer to the platform notes documents, listed under "Downloadable SDK Components" -in the "SDK" tab. For example, Android 2.0 locales.

    - -

    Run the application for each of the expected locales, plus one unexpected -locale. Here are some of the results you should see:

    - - - - - - - - - - - - - - - - - - - - - - - - - - -
    LocaleOpening screen of application
    German / Germany -
    Specifically supported by the Hello, L10N application.
    custom locale app
    French / Canada -
    Specifically supported by the Hello, L10N application.
    custom locale app
    German / Switzerland -
    Only the language is specifically supported by -the Hello, L10N application.
    custom locale app`
    Japanese -
    Specifically supported by the Hello, L10N application. -
    custom locale app`
    Romansh / Switzerland (custom locale rm_CH) -
    Not specifically supported by the Hello, L10N -application, so the application uses the default resources.
    custom locale app
    diff --git a/docs/html/resources/tutorials/notepad/index.jd b/docs/html/resources/tutorials/notepad/index.jd index dd9218451a0c..1f37c410a55a 100644 --- a/docs/html/resources/tutorials/notepad/index.jd +++ b/docs/html/resources/tutorials/notepad/index.jd @@ -44,11 +44,11 @@ steps in your environment.

    The tutorial assumes that you have some familiarity with basic Android application concepts and terminology. If you are not, you -should read Application +should read Application Fundamentals before continuing.

    This tutorial also builds on the introductory information provided in the -Hello World +Building Your First App tutorial, which explains how to set up your Eclipse environment for building Android applications. We recommend you complete the Hello World tutorial before starting this one.

    diff --git a/docs/html/resources/tutorials/notepad/notepad-ex1.jd b/docs/html/resources/tutorials/notepad/notepad-ex1.jd index cf7765e1693a..13ab0a6ac331 100644 --- a/docs/html/resources/tutorials/notepad/notepad-ex1.jd +++ b/docs/html/resources/tutorials/notepad/notepad-ex1.jd @@ -33,7 +33,7 @@ selections.

    Notepadv1 is a project that is provided as a starting point. It takes care of some of the boilerplate work that you have already seen if you - followed the Hello, + followed the Hello, World tutorial.

      diff --git a/docs/html/resources/tutorials/notepad/notepad-ex3.jd b/docs/html/resources/tutorials/notepad/notepad-ex3.jd index 557738e4c105..e31ecda2e20b 100644 --- a/docs/html/resources/tutorials/notepad/notepad-ex3.jd +++ b/docs/html/resources/tutorials/notepad/notepad-ex3.jd @@ -204,7 +204,7 @@ and populate the View elements with them.

      state it was in when it was killed.

      Activities have a well-defined life +href="{@docRoot}guide/components/activities.html#Lifecycle">well-defined life cycle. Lifecycle events can happen even if you are not handing off control to another Activity explicitly. For example, perhaps a call comes in to the diff --git a/docs/html/resources/tutorials/notepad/notepad-extra-credit.jd b/docs/html/resources/tutorials/notepad/notepad-extra-credit.jd index 0d59b56b7a7b..d5fd7716d262 100644 --- a/docs/html/resources/tutorials/notepad/notepad-extra-credit.jd +++ b/docs/html/resources/tutorials/notepad/notepad-extra-credit.jd @@ -65,6 +65,6 @@ when.

      The Android Eclipse plugin not only offers excellent debugging support for your application development, but also superb profiling support. You can also -try using Traceview to profile your application. If your application is running too slow, this can help you +try using Traceview to profile your application. If your application is running too slow, this can help you find the bottlenecks and fix them.

      diff --git a/docs/html/resources/tutorials/opengl/opengl-es10.jd b/docs/html/resources/tutorials/opengl/opengl-es10.jd deleted file mode 100644 index 2b4462059217..000000000000 --- a/docs/html/resources/tutorials/opengl/opengl-es10.jd +++ /dev/null @@ -1,532 +0,0 @@ -page.title=OpenGL ES 1.0 -parent.title=Tutorials -parent.link=../../browser.html?tag=tutorial -@jd:body - - - - -

      This tutorial shows you how to create a simple Android application that uses the OpenGL ES 1.0 -API to perform some basic graphics operations. You'll learn how to:

      - -
        -
      • Create an activity using {@link android.opengl.GLSurfaceView} and {@link -android.opengl.GLSurfaceView.Renderer}
      • -
      • Create and draw a graphic object
      • -
      • Define a projection to correct for screen geometry
      • -
      • Define a camera view
      • -
      • Rotate a graphic object
      • -
      • Make graphics touch-interactive
      • -
      - -

      The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should -carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your -needs. For more information, see -Choosing an OpenGL API -Version. If you would prefer to use OpenGL ES 2.0, see the OpenGL ES 2.0 tutorial.

      - -

      Before you start, you should understand how to create a basic Android application. If you do not -know how to create an app, follow the Hello -World Tutorial to familiarize yourself with the process.

      - -

      Create an Activity with GLSurfaceView

      - -

      To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a -{@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main -view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer} -controls what is drawn within that view. (For more information about these classes, see the 3D with OpenGL document.)

      - -

      To create an activity using {@code GLSurfaceView}:

      - -
        -
      1. Start a new Android project that targets Android 1.6 (API Level 4) or higher. -
      2. -
      3. Name the project HelloOpenGLES10 and make sure it includes an activity called -{@code HelloOpenGLES10}. -
      4. -
      5. Modify the {@code HelloOpenGLES10} class as follows: -
        -package com.example.android.apis.graphics;
        -
        -import android.app.Activity;
        -import android.content.Context;
        -import android.opengl.GLSurfaceView;
        -import android.os.Bundle;
        -
        -public class HelloOpenGLES10 extends Activity {
        -  
        -    private GLSurfaceView mGLView;
        -  
        -    @Override
        -    public void onCreate(Bundle savedInstanceState) {
        -        super.onCreate(savedInstanceState);
        -        
        -        // Create a GLSurfaceView instance and set it
        -        // as the ContentView for this Activity.
        -        mGLView = new HelloOpenGLES10SurfaceView(this);
        -        setContentView(mGLView);
        -    }
        -    
        -    @Override
        -    protected void onPause() {
        -        super.onPause();
        -        // The following call pauses the rendering thread.
        -        // If your OpenGL application is memory intensive,
        -        // you should consider de-allocating objects that
        -        // consume significant memory here.
        -        mGLView.onPause();
        -    }
        -    
        -    @Override
        -    protected void onResume() {
        -        super.onResume();
        -        // The following call resumes a paused rendering thread.
        -        // If you de-allocated graphic objects for onPause()
        -        // this is a good place to re-allocate them.
        -        mGLView.onResume();
        -    }
        -}
        -  
        -class HelloOpenGLES10SurfaceView extends GLSurfaceView {
        -
        -    public HelloOpenGLES10SurfaceView(Context context){
        -        super(context);
        -        
        -        // Set the Renderer for drawing on the GLSurfaceView
        -        setRenderer(new HelloOpenGLES10Renderer());
        -    }
        -}
        -
        -

        Note: You will get a compile error for the {@code -HelloOpenGLES10Renderer} class reference. That's expected; you will fix this error in the next step. -

        - -

        As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its -view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its -work.

        - -

        The {@code HelloOpenGLES10SurfaceView} class in this example code above is just a thin wrapper -for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this -example. However, if you want your application to monitor and respond to touch screen -events—and we are guessing you do—you must extend {@link android.opengl.GLSurfaceView} -to add touch event listeners, which you will learn how to do in the Reponding to -Touch Events section.

        - -

        In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an -implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create -a renderer class to complete this OpenGL application.

        -
      6. - -
      7. Create a new file for the following class {@code HelloOpenGLES10Renderer}, which implements -the {@link android.opengl.GLSurfaceView.Renderer} interface: - -
        -package com.example.android.apis.graphics;
        -
        -import javax.microedition.khronos.egl.EGLConfig;
        -import javax.microedition.khronos.opengles.GL10;
        -
        -import android.opengl.GLSurfaceView;
        -
        -public class HelloOpenGLES10Renderer implements GLSurfaceView.Renderer {
        -
        -    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        -        // Set the background frame color
        -        gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        -    }
        -    
        -    public void onDrawFrame(GL10 gl) {
        -        // Redraw background color
        -        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        -    }
        -    
        -    public void onSurfaceChanged(GL10 gl, int width, int height) {
        -        gl.glViewport(0, 0, width, height);
        -    }
        -  
        -}
        -
        -

        This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the -code structure needed to use OpenGL drawing methods: -

          -
        • {@link - android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, - javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the -{@link android.opengl.GLSurfaceView} -environment.
        • -
        • {@link - android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10) - onDrawFrame()} is called for each redraw of the {@link -android.opengl.GLSurfaceView}.
        • -
        • {@link - android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10, - int, int) onSurfaceChanged()} is called if the geometry of the {@link -android.opengl.GLSurfaceView} changes, for example when the device's screen orientation -changes.
        • -
        -

        -

        For more information about these methods, see the 3D with OpenGL document. -

        -
      8. -
      - -

      The code example above creates a simple Android application that displays a grey screen using -OpenGL ES 1.0 calls. While this application does not do anything very interesting, by creating these -classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES -1.0.

      - -

      If you are familiar with the OpenGL ES APIs, these classes should give you enough information -to use the OpenGL ES 1.0 API and create graphics. However, if you need a bit more help getting -started with OpenGL, head on to the next sections for a few more hints.

      - -

      Draw a Shape on GLSurfaceView

      - -

      Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to -draw something with it. This section shows you how to define and draw a triangle.

      - -

      Define a Triangle

      - -

      OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you - can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to - define a vertex array for the coordinates.

      - -

      By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of - the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top right corner of the frame and -[-1,-1,0] is bottom left corner of the frame.

      - -

      To define a vertex array for a triangle:

      - -
        -
      1. In your {@code HelloOpenGLES10Renderer} class, add new member variable to contain the -vertices of a triangle shape: -
        -    private FloatBuffer triangleVB;
        -
        -
      2. - -
      3. Create a method, {@code initShapes()} which populates this member variable: -
        -    private void initShapes(){
        -    
        -        float triangleCoords[] = {
        -            // X, Y, Z
        -            -0.5f, -0.25f, 0,
        -             0.5f, -0.25f, 0,
        -             0.0f,  0.559016994f, 0
        -        }; 
        -        
        -        // initialize vertex Buffer for triangle  
        -        ByteBuffer vbb = ByteBuffer.allocateDirect(
        -                // (# of coordinate values * 4 bytes per float)
        -                triangleCoords.length * 4); 
        -        vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
        -        triangleVB = vbb.asFloatBuffer();  // create a floating point buffer from the ByteBuffer
        -        triangleVB.put(triangleCoords);    // add the coordinates to the FloatBuffer
        -        triangleVB.position(0);            // set the buffer to read the first coordinate
        -    
        -    }
        -
        -

        This method defines a two-dimensional triangle with three equal sides.

        -
      4. -
      5. Modify your {@code onSurfaceCreated()} method to initialize your triangle: -
        -    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        -    
        -        // Set the background frame color
        -        gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        -        
        -        // initialize the triangle vertex array
        -        initShapes();
        -    }
        -
        -

        Caution: Shapes and other static objects should be initialized - once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the - new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects - for every frame redraw and slows down your application. -

        -
      6. - -
      - -

      You have now defined a triangle shape, but if you run the application, nothing appears. What?! -You also have to tell OpenGL to draw the triangle, which you'll do in the next section. -

      - - -

      Draw the Triangle

      - -

      Before you can draw your triangle, you must tell OpenGL that you are using vertex arrays. After -that setup step, you can call the drawing APIs to display the triangle.

      - -

      To draw the triangle:

      - -
        -
      1. Add the {@code glEnableClientState()} method to the end of {@code onSurfaceCreated()} to -enable vertex arrays. -
        -        // Enable use of vertex arrays
        -        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        -
        -

        At this point, you are ready to draw the triangle object in the OpenGL view.

        -
      2. - -
      3. Add the following code to the end of your {@code onDrawFrame()} method to draw the triangle. -
        -        // Draw the triangle
        -        gl.glColor4f(0.63671875f, 0.76953125f, 0.22265625f, 0.0f);
        -        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVB);
        -        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
        -
        -
      4. -
      5. Run the app! Your application should look something like this: -
      6. -
      - - -

      - Figure 1. Triangle drawn without a projection or camera view. -

      - -

      There are a few problems with this example. First of all, it is not going to impress your -friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen -orientation of the device. The reason the shape is skewed is due to the fact that the object is -being rendered in a frame which is not perfectly square. You'll fix that problem using a projection -and camera view in the next section.

      - -

      Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in -exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the -Add Motion section, you'll make this shape rotate and justify -this use of processing power.

      - -

      Apply Projection and Camera View

      - -

      One of the basic problems in displaying graphics is that Android device displays are typically -not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate -system onto your typically non-square screen. To solve this problem, you can apply an OpenGL -projection mode and camera view (eye point) to transform the coordinates of your graphic objects -so they have the correct proportions on any display. For more information about OpenGL coordinate -mapping, see Mapping -Coordinates for Drawn Objects.

      - -

      To apply projection and camera view transformations to your triangle: -

      -
        -
      1. Modify your {@code onSurfaceChanged()} method to enable {@link - javax.microedition.khronos.opengles.GL10#GL_PROJECTION GL10.GL_PROJECTION} mode, calculate the - screen ratio and apply the ratio as a transformation of the object coordinates. -
        -  public void onSurfaceChanged(GL10 gl, int width, int height) {
        -      gl.glViewport(0, 0, width, height);
        -      
        -      // make adjustments for screen ratio
        -      float ratio = (float) width / height;
        -      gl.glMatrixMode(GL10.GL_PROJECTION);        // set matrix to projection mode
        -      gl.glLoadIdentity();                        // reset the matrix to its default state
        -      gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);  // apply the projection matrix
        -  }  
        -
        -
      2. - -
      3. Next, modify your {@code onDrawFrame()} method to apply the {@link -javax.microedition.khronos.opengles.GL10#GL_MODELVIEW GL_MODELVIEW} mode and set -a view point using {@link android.opengl.GLU#gluLookAt(javax.microedition.khronos.opengles.GL10, -float, float, float, float, float, float, float, float, float) GLU.gluLookAt()}. -
        -    public void onDrawFrame(GL10 gl) {
        -        // Redraw background color
        -        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        -        
        -        // Set GL_MODELVIEW transformation mode
        -        gl.glMatrixMode(GL10.GL_MODELVIEW);
        -        gl.glLoadIdentity();   // reset the matrix to its default state
        -        
        -        // When using GL_MODELVIEW, you must set the view point
        -        GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);        
        -        
        -        // Draw the triangle
        -        ...
        -    }
        -
        -
      4. -
      5. Run the updated application and you should see something like this:
      6. -
      - - -

      - Figure 2. Triangle drawn with a projection and camera view applied. -

      - -

      Now that you have applied this transformation, the triangle has three equal sides, instead of the -squashed triangle in the earlier version.

      - -

      Add Motion

      - -

      While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances -are you want at least some of your objects to move. In this section, you'll add motion to -your triangle by rotating it.

      - -

      To add rotation to your triangle:

      -
        -
      1. Modify your {@code onDrawFrame()} method to rotate the triangle object: -
        -    public void onDrawFrame(GL10 gl) {
        -        ...    
        -        // When using GL_MODELVIEW, you must set the view point
        -        GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);        
        -    
        -        // Create a rotation for the triangle
        -        long time = SystemClock.uptimeMillis() % 4000L;
        -        float angle = 0.090f * ((int) time);
        -        gl.glRotatef(angle, 0.0f, 0.0f, 1.0f);        
        -        
        -        // Draw the triangle
        -        ...
        -    }
        -
        -
      2. -
      3. Run the application and your triangle should rotate around its center.
      4. -
      - - -

      Respond to Touch Events

      -

      Making objects move according to a preset program like the rotating triangle is useful for -getting some attention, but what if you want to have users interact with your OpenGL graphics? In -this section, you'll learn how listen for touch events to let users interact with objects in your -{@code HelloOpenGLES10SurfaceView}.

      - -

      The key to making your OpenGL application touch interactive is expanding your implementation of -{@link android.opengl.GLSurfaceView} to override the {@link -android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events. -Before you do that, however, you'll modify the renderer class to expose the rotation angle of the -triangle. Afterwards, you'll modify the {@code HelloOpenGLES10SurfaceView} to process touch events -and pass that data to your renderer.

      - -

      To make your triangle rotate in response to touch events:

      - -
        -
      1. Modify your {@code HelloOpenGLES10Renderer} class to include a new, public member so that -your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer: -
        -    public float mAngle;
        -
        -
      2. -
      3. In your {@code onDrawFrame()} method, comment out the code that generates an angle and -replace the {@code angle} variable with {@code mAngle}. -
        -        // Create a rotation for the triangle (Boring! Comment this out:)
        -        // long time = SystemClock.uptimeMillis() % 4000L;
        -        // float angle = 0.090f * ((int) time);
        -
        -        // Use the mAngle member as the rotation value
        -        gl.glRotatef(mAngle, 0.0f, 0.0f, 1.0f); 
        -
        -
      4. -
      5. In your {@code HelloOpenGLES10SurfaceView} class, add the following member variables. -
        -    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
        -    private HelloOpenGLES10Renderer mRenderer;
        -    private float mPreviousX;
        -    private float mPreviousY;
        -
        -
      6. -
      7. In the constructor method for {@code HelloOpenGLES10SurfaceView}, set the {@code mRenderer} -member so you have a handle to pass in rotation input and set the render mode to {@link -android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}. -
        -    public HelloOpenGLES10SurfaceView(Context context){
        -        super(context);
        -        // set the mRenderer member
        -        mRenderer = new HelloOpenGLES10Renderer();
        -        setRenderer(mRenderer);
        -        
        -        // Render the view only when there is a change
        -        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        -    }
        -
        -
      8. -
      9. In your {@code HelloOpenGLES10SurfaceView} class, override the {@link -android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch -events and pass them to your renderer. -
        -    @Override 
        -    public boolean onTouchEvent(MotionEvent e) {
        -        // MotionEvent reports input details from the touch screen
        -        // and other input controls. In this case, you are only
        -        // interested in events where the touch position changed.
        -
        -        float x = e.getX();
        -        float y = e.getY();
        -        
        -        switch (e.getAction()) {
        -            case MotionEvent.ACTION_MOVE:
        -    
        -                float dx = x - mPreviousX;
        -                float dy = y - mPreviousY;
        -    
        -                // reverse direction of rotation above the mid-line
        -                if (y > getHeight() / 2) {
        -                  dx = dx * -1 ;
        -                }
        -    
        -                // reverse direction of rotation to left of the mid-line
        -                if (x < getWidth() / 2) {
        -                  dy = dy * -1 ;
        -                }
        -              
        -                mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;
        -                requestRender();
        -        }
        -
        -        mPreviousX = x;
        -        mPreviousY = y;
        -        return true;
        -    } 
        -
        -

        Note: Touch events return pixel coordinates which are not the -same as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the -highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL -graphic objects, you must translate touch coordinates into OpenGL coordinates.

        -
      10. -
      11. Run the application and drag your finger or cursor around the screen to rotate the -triangle.
      12. -
      -

      For another example of OpenGL touch event functionality, see TouchRotateActivity.

      \ No newline at end of file diff --git a/docs/html/resources/tutorials/opengl/opengl-es20.jd b/docs/html/resources/tutorials/opengl/opengl-es20.jd deleted file mode 100644 index dd23dbf2051c..000000000000 --- a/docs/html/resources/tutorials/opengl/opengl-es20.jd +++ /dev/null @@ -1,652 +0,0 @@ -page.title=OpenGL ES 2.0 -parent.title=Tutorials -parent.link=../../browser.html?tag=tutorial -@jd:body - - - - -

      This tutorial shows you how to create a simple Android application that uses the OpenGL ES 2.0 -API to perform some basic graphics operations. You'll learn how to:

      - -
        -
      • Create an activity using {@link android.opengl.GLSurfaceView} and {@link -android.opengl.GLSurfaceView.Renderer}
      • -
      • Create and draw a graphic object
      • -
      • Define a projection to correct for screen geometry
      • -
      • Define a camera view
      • -
      • Rotate a graphic object
      • -
      • Make graphics touch interactive
      • -
      - -

      The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should -carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your -needs. For more information, see -Choosing an OpenGL API -Version. If you would prefer to use OpenGL ES 1.0, see the OpenGL ES 1.0 tutorial.

      - -

      Before you start, you should understand how to create a basic Android application. If you do not -know how to create an app, follow the Hello -World Tutorial to familiarize yourself with the process.

      - -

      Caution: OpenGL ES 2.0 is currently not supported by -the Android Emulator. You must have a physical test device running Android 2.2 (API Level 8) or -higher in order to run and test the example code in this tutorial.

      - -

      Create an Activity with GLSurfaceView

      - -

      To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a -{@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main -view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer} -controls what is drawn within that view. (For more information about these classes, see the 3D with OpenGL document.)

      - -

      To create an activity using {@code GLSurfaceView}:

      - -
        -
      1. Start a new Android project that targets Android 2.2 (API Level 8) or higher. -
      2. -
      3. Name the project HelloOpenGLES20 and make sure it includes an activity called -{@code HelloOpenGLES20}. -
      4. -
      5. Modify the {@code HelloOpenGLES20} class as follows: -
        -package com.example.android.apis.graphics;
        -
        -import android.app.Activity;
        -import android.content.Context;
        -import android.opengl.GLSurfaceView;
        -import android.os.Bundle;
        -
        -public class HelloOpenGLES20 extends Activity {
        -  
        -    private GLSurfaceView mGLView;
        -  
        -    @Override
        -    public void onCreate(Bundle savedInstanceState) {
        -        super.onCreate(savedInstanceState);
        -        
        -        // Create a GLSurfaceView instance and set it
        -        // as the ContentView for this Activity
        -        mGLView = new HelloOpenGLES20SurfaceView(this);
        -        setContentView(mGLView);
        -    }
        -    
        -    @Override
        -    protected void onPause() {
        -        super.onPause();
        -        // The following call pauses the rendering thread.
        -        // If your OpenGL application is memory intensive,
        -        // you should consider de-allocating objects that
        -        // consume significant memory here.
        -        mGLView.onPause();
        -    }
        -    
        -    @Override
        -    protected void onResume() {
        -        super.onResume();
        -        // The following call resumes a paused rendering thread.
        -        // If you de-allocated graphic objects for onPause()
        -        // this is a good place to re-allocate them.
        -        mGLView.onResume();
        -    }
        -}
        -  
        -class HelloOpenGLES20SurfaceView extends GLSurfaceView {
        -
        -    public HelloOpenGLES20SurfaceView(Context context){
        -        super(context);
        -        
        -        // Create an OpenGL ES 2.0 context.
        -        setEGLContextClientVersion(2);
        -        // Set the Renderer for drawing on the GLSurfaceView
        -        setRenderer(new HelloOpenGLES20Renderer());
        -    }
        -}
        -
        -

        Note: You will get a compile error for the {@code -HelloOpenGLES20Renderer} class reference. That's expected; you will fix this error in the next step. -

        - -

        As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its -view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its -work.

        - -

        The {@code HelloOpenGLES20SurfaceView} class in this example code above is just a thin wrapper -for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this -example. However, if you want your application to monitor and respond to touch screen -events—and we are guessing you do—you must extend {@link android.opengl.GLSurfaceView} -to add touch event listeners, which you will learn how to do in the Reponding to -Touch Events section.

        - -

        In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an -implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create -a renderer class to complete this OpenGL application.

        -
      6. - -
      7. Create a new file for the following class {@code HelloOpenGLES20Renderer}, which implements -the {@link android.opengl.GLSurfaceView.Renderer} interface: - -
        -package com.example.android.apis.graphics;
        -
        -import javax.microedition.khronos.egl.EGLConfig;
        -import javax.microedition.khronos.opengles.GL10;
        -
        -import android.opengl.GLES20;
        -import android.opengl.GLSurfaceView;
        -
        -public class HelloOpenGLES20Renderer implements GLSurfaceView.Renderer {
        -  
        -    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        -    
        -        // Set the background frame color
        -        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        -    }
        -    
        -    public void onDrawFrame(GL10 unused) {
        -    
        -        // Redraw background color
        -        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
        -    }
        -    
        -    public void onSurfaceChanged(GL10 unused, int width, int height) {
        -        GLES20.glViewport(0, 0, width, height);
        -    }
        -  
        -}
        -
        -

        This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the -code structure needed to use OpenGL drawing methods: -

          -
        • {@link - android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, - javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the -{@link android.opengl.GLSurfaceView} -environment.
        • -
        • {@link - android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10) - onDrawFrame()} is called for each redraw of the {@link -android.opengl.GLSurfaceView}.
        • -
        • {@link - android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10, - int, int) onSurfaceChanged()} is called if the geometry of the {@link -android.opengl.GLSurfaceView} changes, for example when the device's screen orientation -changes.
        • -
        -

        -

        For more information about these methods, see the 3D with OpenGL document. -

        -
      8. -
      - -

      The code example above creates a simple Android application that displays a grey screen using -OpenGL ES 2.0 calls. While this application does not do anything very interesting, by creating these -classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES -2.0.

      - -

      If you are familiar with the OpenGL ES APIs, these classes should give you enough information -to use the OpenGL ES 2.0 API and create graphics. However, if you need a bit more help getting -started with OpenGL, head on to the next sections for a few more hints.

      - -

      Note: If your application requires OpenGL 2.0, make sure you -declare this in your manifest:

      -
      -    <!-- Tell the system this app requires OpenGL ES 2.0. -->
      -    <uses-feature android:glEsVersion="0x00020000" android:required="true" />
      -
      -

      For more information, see OpenGL manifest declarations in the -3D with OpenGL document.

      - - -

      Draw a Shape on GLSurfaceView

      - -

      Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to -draw something with it. This section shows you how to define and draw a triangle.

      - -

      Define a Triangle

      - -

      OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you - can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to - define a vertex array for the coordinates.

      - -

      By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of - the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top-right corner of the frame and -[-1,-1,0] is bottom-left corner of the frame.

      - -

      To define a vertex array for a triangle:

      - -
        -
      1. In your {@code HelloOpenGLES20Renderer} class, add new member variable to contain the -vertices of a triangle shape: -
        -    private FloatBuffer triangleVB;
        -
        -
      2. - -
      3. Create a method, {@code initShapes()} which populates this member variable: -
        -    private void initShapes(){
        -    
        -        float triangleCoords[] = {
        -            // X, Y, Z
        -            -0.5f, -0.25f, 0,
        -             0.5f, -0.25f, 0,
        -             0.0f,  0.559016994f, 0
        -        }; 
        -        
        -        // initialize vertex Buffer for triangle  
        -        ByteBuffer vbb = ByteBuffer.allocateDirect(
        -                // (# of coordinate values * 4 bytes per float)
        -                triangleCoords.length * 4); 
        -        vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
        -        triangleVB = vbb.asFloatBuffer();  // create a floating point buffer from the ByteBuffer
        -        triangleVB.put(triangleCoords);    // add the coordinates to the FloatBuffer
        -        triangleVB.position(0);            // set the buffer to read the first coordinate
        -    
        -    }
        -
        -

        This method defines a two-dimensional triangle shape with three equal sides.

        -
      4. -
      5. Modify your {@code onSurfaceCreated()} method to initialize your triangle: -
        -    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        -    
        -        // Set the background frame color
        -        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        -        
        -        // initialize the triangle vertex array
        -        initShapes();
        -    }
        -
        -

        Caution: Shapes and other static objects should be initialized - once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the - new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects - for every frame redraw and slows down your application. -

        -
      6. - -
      - -

      You have now defined a triangle shape, but if you run the application, nothing appears. What?! -You also have to tell OpenGL to draw the triangle, which you'll do in the next section. -

      - - -

      Draw the Triangle

      - -

      The OpenGL ES 2.0 requires a bit more code than OpenGL ES 1.0/1.1 in order to draw objects. In -this section, you'll create vertex and fragment shaders, a shader loader, apply the shaders, enable -the use of vertex arrays for your triangle and, finally, draw it on screen.

      - -

      To draw the triangle:

      - -
        -
      1. In your {@code HelloOpenGLES20Renderer} class, define a vertex shader and a fragment -shader. Shader code is defined as a string which is compiled and run by the OpenGL ES 2.0 rendering -engine. -
        -    private final String vertexShaderCode = 
        -        "attribute vec4 vPosition; \n" +
        -        "void main(){              \n" +
        -        " gl_Position = vPosition; \n" +
        -        "}                         \n";
        -    
        -    private final String fragmentShaderCode = 
        -        "precision mediump float;  \n" +
        -        "void main(){              \n" +
        -        " gl_FragColor = vec4 (0.63671875, 0.76953125, 0.22265625, 1.0); \n" +
        -        "}                         \n";
        -
        -

        The vertex shader controls how OpenGL positions and draws the vertices of shapes in space. -The fragment shader controls what OpenGL draws between the vertices of shapes.

        -
      2. -
      3. In your {@code HelloOpenGLES20Renderer} class, create a method for loading the shaders. -
        -    private int loadShader(int type, String shaderCode){
        -    
        -        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
        -        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
        -        int shader = GLES20.glCreateShader(type); 
        -        
        -        // add the source code to the shader and compile it
        -        GLES20.glShaderSource(shader, shaderCode);
        -        GLES20.glCompileShader(shader);
        -        
        -        return shader;
        -    }
        -
        -
      4. - -
      5. Add the following members to your {@code HelloOpenGLES20Renderer} class for an OpenGL -Program and the positioning control for your triangle. -
        -    private int mProgram;
        -    private int maPositionHandle;
        -
        -

        In OpenGL ES 2.0, you attach vertex and fragment shaders to a Program and then -apply the program to the OpenGL graphics pipeline.

        -
      6. - -
      7. Add the following code to the end of your {@code onSurfaceCreated()} method to load the -shaders and attach them to an OpenGL Program. -
        -        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
        -        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
        -        
        -        mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program
        -        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
        -        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
        -        GLES20.glLinkProgram(mProgram);                  // creates OpenGL program executables
        -        
        -        // get handle to the vertex shader's vPosition member
        -        maPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        -
        -

        At this point, you are ready to draw the triangle object in the OpenGL view.

        -
      8. - -
      9. Add the following code to the end of your {@code onDrawFrame()} method apply the OpenGL -program you created, load the triangle object and draw the triangle. -
        -        // Add program to OpenGL environment
        -        GLES20.glUseProgram(mProgram);
        -        
        -        // Prepare the triangle data
        -        GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 12, triangleVB);
        -        GLES20.glEnableVertexAttribArray(maPositionHandle);
        -        
        -        // Draw the triangle
        -        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
        -
        -
      10. -
      11. Run the app! Your application should look something like this: -
      12. -
      - - -

      - Figure 1. Triangle drawn without a projection or camera view. -

      - -

      There are a few problems with this example. First of all, it is not going to impress your -friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen -orientation of the device. The reason the shape is skewed is due to the fact that the object is -being rendered in a frame which is not perfectly square. You'll fix that problem using a projection -and camera view in the next section.

      - -

      Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in -exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the -Add Motion section, you'll make this shape rotate and justify -this use of processing power.

      - -

      Apply Projection and Camera View

      - -

      One of the basic problems in displaying graphics is that Android device displays are typically -not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate -system onto your typically non-square screen. To solve this problem, you can apply an OpenGL -projection mode and camera view (eye point) to transform the coordinates of your graphic objects -so they have the correct proportions on any display. For more information about OpenGL coordinate -mapping, see Mapping -Coordinates for Drawn Objects.

      - -

      To apply projection and camera view transformations to your triangle: -

      -
        -
      1. Add the following members to your {@code HelloOpenGLES20Renderer} class. -
        -    private int muMVPMatrixHandle;
        -    private float[] mMVPMatrix = new float[16];
        -    private float[] mMMatrix = new float[16];
        -    private float[] mVMatrix = new float[16];
        -    private float[] mProjMatrix = new float[16];
        -
        -
      2. -
      3. Modify your {@code vertexShaderCode} string to add a variable for a model view -projection matrix. -
        -    private final String vertexShaderCode = 
        -        // This matrix member variable provides a hook to manipulate
        -        // the coordinates of the objects that use this vertex shader
        -        "uniform mat4 uMVPMatrix;   \n" +
        -        
        -        "attribute vec4 vPosition;  \n" +
        -        "void main(){               \n" +
        -        
        -        // the matrix must be included as a modifier of gl_Position
        -        " gl_Position = uMVPMatrix * vPosition; \n" +
        -        
        -        "}  \n";
        -
        -
      4. -
      5. Modify the {@code onSurfaceChanged()} method to calculate the device screen ratio and -create a projection matrix. -
        -    public void onSurfaceChanged(GL10 unused, int width, int height) {
        -        GLES20.glViewport(0, 0, width, height);
        -        
        -        float ratio = (float) width / height;
        -        
        -        // this projection matrix is applied to object coodinates
        -        // in the onDrawFrame() method
        -        Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
        -    }  
        -
        -
      6. -
      7. Add the following code to the end of your {@code onSurfaceChanged()} method to -reference the {@code uMVPMatrix} shader matrix variable you added in step 2. -
        -        muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
        -
        -
      8. -
      9. Add the following code to the end of your {@code onSurfaceChanged()} method to define -a camera view matrix. -
        -        Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
        -
        -
      10. -
      11. Finally, modify your {@code onDrawFrame()} method to combine the projection and -camera view matrices and then apply the combined transformation to the OpenGL rendering pipeline. -
        -    public void onDrawFrame(GL10 unused) {
        -        ...
        -        // Apply a ModelView Projection transformation
        -        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
        -        GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
        -        
        -        // Draw the triangle
        -        ...
        -    }
        -
        -
      12. -
      13. Run the updated application and you should see something like this:
      14. -
      - - -

      - Figure 2. Triangle drawn with a projection and camera view applied. -

      - -

      Now that you have applied this transformation, the triangle has three equal sides, instead of the -squashed triangle in the earlier version.

      - -

      Add Motion

      - -

      While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances -are you want at least some of your objects to move. In this section, you'll add motion to -your triangle by rotating it.

      - -

      To add rotation to your triangle:

      -
        -
      1. Add an additional tranformation matrix member to your {@code HelloOpenGLES20Renderer} -class. -
        -      private float[] mMMatrix = new float[16];
        -    
        -
      2. -
      3. Modify your {@code onDrawFrame()} method to rotate the triangle object. -
        -    public void onDrawFrame(GL10 gl) {
        -        ...
        -    
        -        // Create a rotation for the triangle
        -        long time = SystemClock.uptimeMillis() % 4000L;
        -        float angle = 0.090f * ((int) time);
        -        Matrix.setRotateM(mMMatrix, 0, angle, 0, 0, 1.0f);
        -        Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0);
        -        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
        -        
        -        // Apply a ModelView Projection transformation
        -        GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
        -        
        -        // Draw the triangle
        -        ...
        -    }
        -
        -
      4. -
      5. Run the application and your triangle should rotate around its center.
      6. -
      - - -

      Respond to Touch Events

      -

      Making objects move according to a preset program like the rotating triangle is useful for -getting some attention, but what if you want to have users interact with your OpenGL graphics? In -this section, you'll learn how listen for touch events to let users interact with objects in your -{@code HelloOpenGLES20SurfaceView}.

      - -

      The key to making your OpenGL application touch interactive is expanding your implementation of -{@link android.opengl.GLSurfaceView} to override the {@link -android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events. -Before you do that, however, you'll modify the renderer class to expose the rotation angle of the -triangle. Afterwards, you'll modify the {@code HelloOpenGLES20SurfaceView} to process touch events -and pass that data to your renderer.

      - -

      To make your triangle rotate in response to touch events:

      - -
        -
      1. Modify your {@code HelloOpenGLES20Renderer} class to include a new, public member so that -your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer: -
        -    public float mAngle;
        -
        -
      2. -
      3. In your {@code onDrawFrame()} method, comment out the code that generates an angle and -replace the {@code angle} variable with {@code mAngle}. -
        -        // Create a rotation for the triangle (Boring! Comment this out:)
        -        // long time = SystemClock.uptimeMillis() % 4000L;
        -        // float angle = 0.090f * ((int) time);
        -
        -        // Use the mAngle member as the rotation value
        -        Matrix.setRotateM(mMMatrix, 0, mAngle, 0, 0, 1.0f);
        -
        -
      4. -
      5. In your {@code HelloOpenGLES20SurfaceView} class, add the following member variables. -
        -    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
        -    private HelloOpenGLES20Renderer mRenderer;
        -    private float mPreviousX;
        -    private float mPreviousY;
        -
        -
      6. -
      7. In the constructor method for {@code HelloOpenGLES20SurfaceView}, set the {@code mRenderer} -member so you have a handle to pass in rotation input and set the render mode to {@link -android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}.
        -    public HelloOpenGLES20SurfaceView(Context context){
        -        super(context);
        -        // Create an OpenGL ES 2.0 context.
        -        setEGLContextClientVersion(2);
        -            
        -        // set the mRenderer member
        -        mRenderer = new HelloOpenGLES20Renderer();
        -        setRenderer(mRenderer);
        -        
        -        // Render the view only when there is a change
        -        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        -    }
        -
        -
      8. -
      9. In your {@code HelloOpenGLES20SurfaceView} class, override the {@link -android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch -events and pass them to your renderer. -
        -    @Override 
        -    public boolean onTouchEvent(MotionEvent e) {
        -        // MotionEvent reports input details from the touch screen
        -        // and other input controls. In this case, you are only
        -        // interested in events where the touch position changed.
        -
        -        float x = e.getX();
        -        float y = e.getY();
        -        
        -        switch (e.getAction()) {
        -            case MotionEvent.ACTION_MOVE:
        -    
        -                float dx = x - mPreviousX;
        -                float dy = y - mPreviousY;
        -    
        -                // reverse direction of rotation above the mid-line
        -                if (y > getHeight() / 2) {
        -                  dx = dx * -1 ;
        -                }
        -    
        -                // reverse direction of rotation to left of the mid-line
        -                if (x < getWidth() / 2) {
        -                  dy = dy * -1 ;
        -                }
        -              
        -                mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;
        -                requestRender();
        -        }
        -
        -        mPreviousX = x;
        -        mPreviousY = y;
        -        return true;
        -    } 
        -
        -

        Note: Touch events return pixel coordinates which are not the -same as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the -highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL -graphic objects, you must translate touch coordinates into OpenGL coordinates.

        -
      10. -
      11. Run the application and drag your finger or cursor around the screen to rotate the -triangle.
      12. -
      -

      For another example of OpenGL touch event functionality, see TouchRotateActivity.

      \ No newline at end of file diff --git a/docs/html/resources/tutorials/testing/activity_test.jd b/docs/html/resources/tutorials/testing/activity_test.jd deleted file mode 100644 index f88b7687be1a..000000000000 --- a/docs/html/resources/tutorials/testing/activity_test.jd +++ /dev/null @@ -1,1381 +0,0 @@ -page.title=Activity Testing -parent.title=Tutorials -parent.link=../../browser.html?tag=tutorial -@jd:body -
      -
      -

      In this document

      -
        -
      1. - Prerequisites -
      2. -
      3. - Installing the Tutorial Sample Code -
      4. -
      5. - Setting Up the Emulator -
      6. -
      7. - Setting Up the Projects -
      8. -
      9. - Creating the Test Case Class -
          -
        1. - Adding the test case class file -
        2. -
        3. - Adding the test case constructor -
        4. -
        5. - Adding the setup method -
        6. -
        7. - Adding an initial conditions test -
        8. -
        9. - Adding a UI test -
        10. -
        11. - Adding state management tests -
        12. -
        -
      10. -
      11. - Running the Tests and Seeing the Results -
      12. -
      13. - Forcing Some Tests to Fail -
      14. -
      15. - Next Steps -
      16. -
      -

      Appendix

      -
        -
      1. - Installing the Completed Test Application Java File -
      2. -
      3. - For Users Not Developing In Eclipse -
      4. -
      -

      Related Tutorials

      -
        -
      1. - Hello, Testing -
      2. -
      -

      See Also

      -
        -
      1. - Testing Android Applications -
      2. -
      3. - {@link android.test.ActivityInstrumentationTestCase2} -
      4. -
      5. - {@link junit.framework.Assert} -
      6. -
      7. - {@link android.test.InstrumentationTestRunner} -
      8. -
      -
      -
      -

      - Android includes powerful tools for testing applications. The tools extend JUnit with additional features, provide convenience classes for mock Android system objects, and use - instrumentation to give you control over your main application while you are testing it. The entire Android testing environment is discussed in the document - Testing Android Applications. -

      -

      - This tutorial demonstrates the Android testing tools by presenting a simple Android application and then leading you step-by-step through the creation of a test application for it. - The test application demonstrates these key points: -

      -
        -
      • - An Android test is itself an Android application that is linked to the application under test by entries in its AndroidManifest.xml file. -
      • -
      • - Instead of Android components, an Android test application contains one or more test cases. Each of these is a separate class definition. -
      • -
      • - Android test case classes extend the JUnit {@link junit.framework.TestCase} class. -
      • -
      • - Android test case classes for activities extend JUnit and also connect you to the application under test with instrumentation. You can send keystroke or touch events directly to the UI. -
      • -
      • - You choose an Android test case class based on the type of component (application, activity, content provider, or service) you are testing. -
      • -
      • - Additional test tools in Eclipse/ADT provide integrated support for creating test applications, running them, and viewing the results. -
      • -
      -

      - The test application contains methods that perform the following tests: -

      -
        -
      • - Initial conditions test. Tests that the application under test initializes correctly. This is also a unit test of the application's - {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method. Testing initial conditions also provides a confidence measure for subsequent tests. -
      • -
      • - UI test. Tests that the main UI operation works correctly. This test demonstrates the instrumentation features available in activity testing. - It shows that you can automate UI tests by sending key events from the test application to the main application. -
      • -
      • - State management tests. Test the application's code for saving state. This test demonstrates the instrumentation features of the test runner, which - are available for testing any component. -
      • -
      -

      Prerequisites

      -

      - The instructions and code in this tutorial depend on the following: -

      -
        -
      • - Basic knowledge of Android programming. If you haven't yet written an Android application, do the - Hello, World tutorial. If you - want to learn more about Spinner, the application under test, then you might want to visit the - Hello Views > Spinner example. -
      • -
      • - Some familiarity with the Android testing framework and concepts. If you haven't explored - Android testing yet, start by reading the Developer Guide topic Testing Android Applications - or following the - Hello, Testing tutorial. -
      • -
      • - Eclipse with ADT. This tutorial describes how to set up and run a test application using - Eclipse with ADT. If you haven't yet installed Eclipse and the ADT plugin, - follow the steps in Installing the SDK - to install them before continuing. If you are not developing in Eclipse, you will - find instructions for setting up and running the test application in the - appendix of this document. -
      • -
      • - Android 1.5 platform (API Level 3) or higher. You must have the Android 1.5 platform - (API Level 3) or higher installed in your SDK, because this tutorial uses APIs that - were introduced in that version. -

        - If you are not sure which platforms are installed in your SDK, - open the Android SDK and AVD Manager and check in the - Installed Packages panel. - If aren't sure how to download a platform into your SDK, - read Adding SDK Packages. -

        -
      • -
      -

      Installing the Tutorial Sample Code

      -

      - During this tutorial, you will be working with sample code that is provided as part - of the downloadable Samples component of the SDK. Specifically, you will be working - with a pair of related sample applications — an application under test and a test - application: -

      -
        -
      • - Spinner is the application under test. This tutorial focuses on the - common situation of writing tests for an application that already exists, so the main - application is provided to you. -
      • -
      • - SpinnerTest is the test application. In the tutorial, you create this application - step-by-step. If you want to run quickly through the tutorial, - you can install the completed SpinnerTest application first, and then follow the - text. You may get more from the tutorial, however, if you create the test application - as you go. The instructions for installing the completed test application are in the - section Installing the Completed Test Application Java File. -
      • -
      -

      - The sample applications are provided in the SDK component named - "Samples for SDK API 8" and in later versions of the Samples. -

      -

      - To get started with the tutorial, first use the Android SDK and AVD manager to install an - appropriate version of the Samples: -

      -
        -
      1. - In Eclipse, select Window > Android SDK and AVD Manager. -
      2. -
      3. - Open the Installed Packages panel and check whether - "Samples for SDK API 8" (or higher version) is listed. - If so, skip to the next section, - Setting Up the Projects, to get started with the tutorial. - Otherwise, continue with the next step. -
      4. -
      5. - Open the Available Packages panel. -
      6. -
      7. - Select the "Samples for SDK API 8" component and click Install Selected. -
      8. -
      9. - Verify and accept the component and then click Install Accepted. - The Samples component will now be installed into your SDK. -
      10. -
      -

      - When the installation is complete, the applications in the - Samples component are stored at this location on your computer: -

      -

      - <sdk>/samples/android-8/ -

      -

      - For general information about the Samples, see - Getting the Samples -

      -

      - Note: Although the sample code for this tutorial is provided in the - "Samples for SDK API 8" component, that does not imply that you need to build or - run the application against the corresponding platform (Android 2.2). - The API level referenced in the Samples component name indicates only the origin branch from - which the samples were built. -

      -

      Setting Up the Emulator

      -

      - In this tutorial, you will use the Android emulator to run applications. The emulator needs - an Android Virtual Device (AVD) with an API level equal to or higher than the one you set for the projects in the previous step. - To find out how to check this and create the right AVD if necessary, - see Creating an AVD. -

      -

      - As a test of the AVD and emulator, run the SpinnerActivity application in Eclipse with ADT. When it starts, - click the large downward-pointing arrow to the right of the spinner text. You see the spinner expand and display the title "Select a planet" at the top. - Click one of the other planets. The spinner closes, and your selection appears below it on the screen. -

      -

      Setting Up the Projects

      -

      - When you are ready to get started with the tutorial, begin by setting up Eclipse projects for - both Spinner (the application under test) and SpinnerTest (the test application). -

      -

      - You'll be using the Spinner application as-is, without modification, so you'll be loading it - into Eclipse as a new Android project from existing source. In the process, you'll be - creating a new test project associated with Spinner that will contain the SpinnerTest - application. The SpinnerTest application will be completely new and you'll be - using the code examples in this tutorial to add test classes and tests to it. -

      -

      - To install the Spinner app in a new Android project from existing source, following these steps: -

      -
        -
      1. - In Eclipse, select File > New > Project > Android > Android Project, - then click Next. The New Android Project dialog appears. -
      2. -
      3. - In the Project name text box, enter "SpinnerActivity". The Properties area is filled in automatically. -
      4. -
      5. - In the Contents area, set "Create project from existing source". -
      6. -
      7. - For Location, click Browse, navigate to the directory <SDK_path>/samples/android-8/Spinner, - then click Open. The directory name <SDK_path>/samples/android-8/Spinner now appears in the Location text box. -
      8. -
      9. - In the Build Target area, set a API level of 3 or higher. If you are already developing with a particular target, and it is API level 3 or higher, then use that target. -
      10. -
      11. - In the Properties area, in the Min SDK Version:, enter "3". -
      12. -
      13. - You should now see these values: -
          -
        • Project Name: "SpinnerActivity"
        • -
        • Create project from existing source: set
        • -
        • Location: "<SDK_path>/samples/android-8/Spinner"
        • -
        • Build Target: "API level of 3 or higher" (Target Name "Android 1.5 or higher")
        • -
        • Package name: (disabled, set to "com.android.example.spinner")
        • -
        • Create Activity: (disabled, set to ".SpinnerActivity")
        • -
        • Min SDK Version: "3"
        • -
        -

        - The following screenshot summarizes these values: -

        - - New Android Project dialog with filled-in values - - -
      14. -
      -

      - To create a new test project for the SpinnerTest application, follow these steps: -

      -
        -
      1. - Click Next. The New Android Test Project dialog appears. -
      2. -
      3. - Set "Create a Test Project". -
      4. -
      5. - Leave the other values unchanged. The result should be: -
          -
        • Create a Test Project: checked
        • -
        • Test Project Name: "SpinnerActivityTest"
        • -
        • Use default location: checked (this should contain the directory name "workspace/SpinnerActivityTest").
        • -
        • Build Target: Use the same API level you used in the previous step.
        • -
        • Application name: "SpinnerActivityTest"
        • -
        • Package name: "com.android.example.spinner.test"
        • -
        • Min SDK Version: "3"
        • -
        -

        - The following screenshot summarizes these values: -

        - - New Android Test Project dialog with filled-in values - -
      6. -
      7. - Click Finish. Entries for SpinnerActivity and SpinnerActivityTest should appear in the - Package Explorer. -

        - Note: If you set Build Target to an API level higher than "3", you will see the warning - "The API level for the selected SDK target does not match the Min SDK version". You do not need to change the API level or the Min SDK version. - The message tells you that you are building the projects with one particular API level, but specifying that a lower API level is required. This may - occur if you have chosen not to install the optional earlier API levels. -

        -

        - If you see errors listed in the Problems pane at the bottom of the Eclipse window, or if a red error marker appears next to - the entry for SpinnerActivity in the Package Explorer, highlight the SpinnerActivity entry and then select - Project > Clean. This should fix any errors. -

        -
      8. -
      -

      - You now have the application under test in the SpinnerActivity project, - and an empty test project in SpinnerActivityTest. You may - notice that the two projects are in different directories, but Eclipse with - ADT handles this automatically. You should have no problem in either building or running them. -

      -

      - Notice that Eclipse and ADT have already done some initial setup for your test application. - Expand the SpinnerActivityTest project, and notice that it already has an - Android manifest file AndroidManifest.xml. - Eclipse with ADT created this when you added the test project. - Also, the test application is already set up to use instrumentation. You can see this - by examining AndroidManifest.xml. - Open it, then at the bottom of the center pane click AndroidManifest.xml - to display the XML contents: -

      -
      -<?xml version="1.0" encoding="utf-8"?>
      -<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      -      package="com.android.example.spinner.test"
      -      android:versionCode="1"
      -      android:versionName="1.0">
      -    <uses-sdk android:minSdkVersion="3" />
      -    <instrumentation
      -        android:targetPackage="com.android.example.spinner"
      -        android:name="android.test.InstrumentationTestRunner" />
      -    <application android:icon="@drawable/icon" android:label="@string/app_name">
      -        <uses-library android:name="android.test.runner" />
      -        ...
      -    </application>
      -</manifest>
      -
      -

      - Notice the <instrumentation> element. The attribute - android:targetPackage="com.android.example.spinner" tells Android that the - application under test is defined in the Android package - com.android.example.spinner. Android now knows to use that - package's AndroidManifest.xml file to launch the application under test. - The <instrumentation> element also contains the attribute - android:name="android.test.InstrumentationTestRunner", which tells Android - instrumentation to run the test application with Android's instrumentation-enabled test runner. -

      -

      Creating the Test Case Class

      - -

      - You now have a test project SpinnerActivityTest, and the basic structure of a test - application also called SpinnerActivityTest. The basic structure includes all the files and - directories you need to build and run a test application, except for the class that - contains your tests (the test case class). -

      -

      - The next step is to define the test case class. In this tutorial, you'll be creating a - test case class that includes: -

      -
        -
      • - Test setup. This use of the JUnit {@link junit.framework.TestCase#setUp() setUp()} - method demonstrates some of the tasks you might perform before running an Android test. -
      • -
      • - Testing initial conditions. This test demonstrates a good testing technique. - It also demonstrates that with Android instrumentation you can look at the application - under test before the main activity starts. The test checks that the application's - important objects have been initialized. - If the test fails, you then know that any other tests against the application are - unreliable, since the application was running in an incorrect state. -

        - Note: The purpose of testing initial conditions is not the same as - using setUp(). The JUnit {@link junit.framework.TestCase#setUp()} runs once - before each test method, and its purpose is to create a clean test - environment. The initial conditions test runs once, and its purpose is to verify that the - application under test is ready to be tested. -

        -
      • -
      • - Testing the UI. This test shows how to control the main application's UI - with instrumentation, a powerful automation feature of Android testing. -
      • -
      • - Testing state management. This test shows some techniques for testing how - well the application maintains state in the Android environment. Remember that to - provide a satisfactory user experience, your application must never lose its current state, - even if it's interrupted by a phone call or destroyed because of memory constraints. - The Android activity lifecycle provides ways to maintain state, and the - SpinnerActivity application uses them. The test shows the techniques for - verifying that they work. -
      • -
      -

      - Android tests are contained in a special type of Android application that contains one or more test class definitions. Each of these contains - one or more test methods that do the actual tests. In this tutorial, you will first add a test case class, and then add tests to it. -

      -

      - You first choose an Android test case class to extend. You choose from the base test case classes according to the Android component you are testing and the types of tests you are doing. - In this tutorial, the application under test has a single simple activity, so the test case class will be for an Activity component. Android offers several, but the one that tests in - the most realistic environment is {@link android.test.ActivityInstrumentationTestCase2}, so you will use it as the base class. Like all activity test case classes, - ActivityInstrumentationTestCase2 offers convenience methods for interacting directly with the UI of the application under test. -

      -

      Adding the test case class file

      -

      - To add ActivityInstrumentationTestCase2 as the base test case class, follow these steps: -

      -
        -
      1. - In the Package Explorer, expand the test project SpinnerActivityTest if it is not open already. -
      2. -
      3. - Within SpinnerActivityTest, expand the src/ folder and then the package marker for - com.android.example.spinner.test. Right-click on the package name and select New > Class:
        - - Menu for creating a new class in the test application - -

        - The New Java Class wizard appears: -

        - - New Java Class wizard dialog - -
      4. -
      5. - In the wizard, enter the following: -
          -
        • - Name: "SpinnerActivityTest". This becomes the name of your test class. -
        • -
        • - Superclass: "android.test.ActivityInstrumentationTestCase2<SpinnerActivity>". The superclass is parameterized, so - you have to provide it your main application's class name. -
        • -
        -

        - Do not change any of the other settings. Click Finish. -

        -
      6. -
      7. - You now have a new file SpinnerActivityTest.java in the project. -
      8. -
      9. - To resolve the reference to SpinnerActivity, add the following import: -
        -import com.android.example.spinner.SpinnerActivity;
        -
        -
      10. -
      -

      Adding the test case constructor

      -

      - To ensure that the test application is instantiated correctly, you must set up a constructor that the test - runner will call when it instantiates your test class. This constructor has no parameters, and its sole - purpose is to pass information to the superclass's default constructor. To set up this constructor, enter the - following code in the class: -

      -
      -  public SpinnerActivityTest() {
      -    super("com.android.example.spinner", SpinnerActivity.class);
      -  } // end of SpinnerActivityTest constructor definition
      -
      -

      - This calls the superclass constructor with the Android package name (com.android.example.spinner)and main activity's class - (SpinnerActivity.class) for the application under test. Android uses this information to find the application and activity to test. -

      -

      - You are now ready to add tests, by adding test methods to the class. -

      -

      Adding the setup method

      -

      - The setUp() method is invoked before every test. You use it to initialize variables and clean up from previous tests. You can also use - the JUnit {@link junit.framework.TestCase#tearDown() tearDown()} method, which runs after every test method. The tutorial does not use it. -

      -

      - The method you are going to add does the following: -

      -
        -
      • - super.setUp(). Invokes the superclass constructor for setUp(), which is required by JUnit. -
      • -
      • - Calls {@link android.test.ActivityInstrumentationTestCase2#setActivityInitialTouchMode(boolean) setActivityInitialTouchMode(false)}. - This turns off touch mode in the device or emulator. If any of your test methods send key events to the application, - you must turn off touch mode before you start any activities; otherwise, the call is ignored. -
      • -
      • - Stores references to system objects. Retrieves and stores a reference to the activity under test, the Spinner - widget used by the activity, the SpinnerAdapter that backs the widget, and the string value of the selection that is - set when the application is first installed. These objects are used in the state management test. The methods invoked are: -
          -
        • - {@link android.test.ActivityInstrumentationTestCase2#getActivity()}. Gets a reference to the activity under test (SpinnerActivity). - This call also starts the activity if it is not already running. -
        • -
        • - {@link android.app.Activity#findViewById(int)}. Gets a reference to the Spinner widget of the application under test. -
        • -
        • - {@link android.widget.AbsSpinner#getAdapter()}. Gets a reference to the adapter (an array of strings) backing the spinner. -
        • -
        -
      • -
      -

      - Add this code to the definition of SpinnerActivityTest, after the constructor definition: -

      -
      -  @Override
      -  protected void setUp() throws Exception {
      -    super.setUp();
      -
      -    setActivityInitialTouchMode(false);
      -
      -    mActivity = getActivity();
      -
      -    mSpinner =
      -      (Spinner) mActivity.findViewById(
      -        com.android.example.spinner.R.id.Spinner01
      -      );
      -
      -      mPlanetData = mSpinner.getAdapter();
      -
      -  } // end of setUp() method definition
      -
      -

      - Add these members to the test case class: -

      -
      -  private SpinnerActivity mActivity;
      -  private Spinner mSpinner;
      -  private SpinnerAdapter mPlanetData;
      -
      -

      - Add these imports: -

      -
      -import android.widget.Spinner;
      -import android.widget.SpinnerAdapter;
      -
      -

      - You now have the the complete setUp() method. -

      -

      Adding an initial conditions test

      -

      - The initial conditions test verifies that the application under test is initialized correctly. It is an illustration of the types of tests you can run, so it is not comprehensive. - It verifies the following: -

      -
        -
      • - The item select listener is initialized. This listener is called when a selection is made from the spinner. -
      • -
      • - The adapter that provides values to the spinner is initialized. -
      • -
      • - The adapter contains the right number of entries. -
      • -
      -

      - The actual initialization of the application under test is done in setUp(), which the test runner calls automatically before every test. The verifications are - done with JUnit {@link junit.framework.Assert} calls. As a useful convention, the method name is testPreConditions(): -

      -
      -  public void testPreConditions() {
      -    assertTrue(mSpinner.getOnItemSelectedListener() != null);
      -    assertTrue(mPlanetData != null);
      -    assertEquals(mPlanetData.getCount(),ADAPTER_COUNT);
      -  } // end of testPreConditions() method definition
      -
      -

      - Add this member: -

      -
      -  public static final int ADAPTER_COUNT = 9;
      -
      -

      Adding a UI test

      -

      - Now create a UI test that selects an item from the Spinner widget. The test sends key events to the UI with key events. - The test confirms that the selection matches the result you expect. -

      -

      - This test demonstrates the power of using instrumentation in Android testing. Only an instrumentation-based test class allows you to send key events (or touch events) - to the application under test. With instrumentation, you can test your UI without having to take screenshots, record the screen, or do human-controlled testing. -

      -

      - To work with the spinner, the test has to request focus for it and then set it to a known position. The test uses {@link android.view.View#requestFocus() requestFocus()} and - {@link android.widget.AbsSpinner#setSelection(int) setSelection()} to do this. Both of these methods interact with a View in the application under test, so you have to call them - in a special way. -

      -

      - Code in a test application that interacts with a View of the application under test must run in the main application's thread, also - known as the UI thread. To do this, you use the {@link android.app.Activity#runOnUiThread(java.lang.Runnable) Activity.runOnUiThread()} - method. You pass the code to runOnUiThread()in an anonymous {@link java.lang.Runnable Runnable} object. To set - the Java statements in the Runnable object, you override the object's {@link java.lang.Runnable#run()} method. -

      -

      - To send key events to the UI of the application under test, you use the sendKeys() method. - This method does not have to run on the UI thread, since Android uses instrumentation to pass the key events to the application under test. -

      -

      - The last part of the test compares the selection made by sending the key events to a pre-determined value. This tests that the spinner is working as intended. -

      -

      - The following sections show you how to add the code for this test. -

      -
        -
      1. - Get focus and set selection. Create a new method public void testSpinnerUI(). Add - code to to request focus for the spinner and set its position to default or initial position, "Earth". This code is run on the UI thread of - the application under test: -
        -  public void testSpinnerUI() {
        -
        -    mActivity.runOnUiThread(
        -      new Runnable() {
        -        public void run() {
        -          mSpinner.requestFocus();
        -          mSpinner.setSelection(INITIAL_POSITION);
        -        } // end of run() method definition
        -      } // end of anonymous Runnable object instantiation
        -    ); // end of invocation of runOnUiThread
        -
        -

        - Add the following member to the test case class. -

        -
        -  public static final int INITIAL_POSITION = 0;
        -
        -
      2. -
      3. - Make a selection. Send key events to the spinner to select one of the items. To do this, open the spinner by - "clicking" the center keypad button (sending a DPAD_CENTER key event) and then clicking (sending) the down arrow keypad button five times. Finally, - click the center keypad button again to highlight the desired item. Add the following code: -
        -    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
        -    for (int i = 1; i <= TEST_POSITION; i++) {
        -      this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
        -    } // end of for loop
        -
        -    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
        -
        -

        - Add the following member to the test case class: -

        -
        -  public static final int TEST_POSITION = 5;
        -
        -

        - This sets the final position of the spinner to "Saturn" (the spinner's backing adapter is 0-based). -

        -
      4. -
      5. - Check the result. Query the current state of the spinner, and compare its current selection to the expected value. - Call the method {@link android.widget.AdapterView#getSelectedItemPosition() getSelectedItemPosition()} to find out the current selection position, and then - {@link android.widget.AdapterView#getItemAtPosition(int) getItemAtPosition()} to get the object corresponding to that position (casting it to a String). Assert that - this string value matches the expected value of "Saturn": -
        -    mPos = mSpinner.getSelectedItemPosition();
        -    mSelection = (String)mSpinner.getItemAtPosition(mPos);
        -    TextView resultView =
        -      (TextView) mActivity.findViewById(
        -        com.android.example.spinner.R.id.SpinnerResult
        -      );
        -
        -    String resultText = (String) resultView.getText();
        -
        -    assertEquals(resultText,mSelection);
        -
        -  } // end of testSpinnerUI() method definition
        -
        -

        - Add the following members to the test case class: -

        -
        -  private String mSelection;
        -  private int mPos;
        -
        -

        - Add the following imports to the test case class: -

        -
        -  import android.view.KeyEvent;
        -  import android.widget.TextView;
        -
        -
      6. -
      -

      - Pause here to run the tests you have. The procedure for running a test application is different - from running a regular Android application. You run a test application as an Android JUnit - application. To see how to do this, see Running the Tests and Seeing the Results. -

      -

      - Eventually, you will see the SpinnerActivity application start, and the test - application controlling it by sending it key events. You will also see a new - JUnit view in the Explorer pane, showing the results of the - test. The JUnit view is documented in a following section, - Running the Test and Seeing the Results. -

      -

      Adding state management tests

      -

      - You now write two tests that verify that SpinnerActivity maintains its state when it is paused or terminated. - The state, in this case, is the current selection in the spinner. When users make a selection, - pause or terminate the application, and then resume or restart it, they should see - the same selection. -

      -

      - Maintaining state is an important feature of an application. Users may switch from the current - application temporarily to answer the phone, and then switch back. Android may decide to - terminate and restart an activity to change the screen orientation, or terminate an unused - activity to regain storage. In each case, users are best served by having the UI return to its - previous state (except where the logic of the application dictates otherwise). -

      -

      - SpinnerActivity manages its state in these ways: -

      -
        -
      • - Activity is hidden. When the spinner screen (the activity) is running but hidden by some other screen, it - stores the spinner's position and value in a form that persists while the application is running. -
      • -
      • - Application is terminated. When the activity is terminated, it stores the spinner's position and value in - a permanent form. The activity can read the position and value when it restarts, and restore the spinner to its previous state. -
      • -
      • - Activity re-appears. When the user returns to the spinner screen, the previous selection is restored. -
      • -
      • - Application is restarted. When the user starts the application again, the previous selection is restored. -
      • -
      -

      - Note: An application can manage its state in other ways as well, but these are - not covered in this tutorial. -

      -

      - When an activity is hidden, it is paused. When it re-appears, it - resumes. Recognizing that these are key points in an activity's life cycle, - the Activity class provides two callback methods {@link android.app.Activity#onPause()} and - {@link android.app.Activity#onResume()} for handling pauses and resumes. - SpinnerActivity uses them for code that saves and restores state. -

      -

      - Note: If you would like to learn more about the difference between losing - focus/pausing and killing an application, - read about the activity -lifecycle. -

      -

      - The first test verifies that the spinner selection is maintained after the entire application is shut down and then restarted. The test uses instrumentation to - set the spinner's variables outside of the UI. It then terminates the activity by calling {@link android.app.Activity#finish() Activity.finish()}, and restarts it - using the instrumentation method {@link android.test.ActivityInstrumentationTestCase2#getActivity()}. The test then asserts that the current spinner state matches - the test values. -

      -

      - The second test verifies that the spinner selection is maintained after the activity is paused and then resumed. The test uses instrumentation to - set the spinner's variables outside of the UI and then force calls to the onPause() and onResume() methods. The test then - asserts that the current spinner state matches the test values. -

      -

      - Notice that these tests make limited assumptions about the mechanism by which the activity manages state. The tests use the activity's getters and - setters to control the spinner. The first test also knows that hiding an activity calls onPause(), and bringing it back to the foreground - calls onResume(). Other than this, the tests treat the activity as a "black box". -

      -

      - To add the code for testing state management across shutdown and restart, follow these steps: -

      -
        -
      1. - Add the test method testStateDestroy(), then - set the spinner selection to a test value: -
        -  public void testStateDestroy() {
        -    mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
        -    mActivity.setSpinnerSelection(TEST_STATE_DESTROY_SELECTION);
        -
        -
      2. -
      3. - Terminate the activity and restart it: -
        -    mActivity.finish();
        -    mActivity = this.getActivity();
        -
        -
      4. -
      5. - Get the current spinner settings from the activity: -
        -    int currentPosition = mActivity.getSpinnerPosition();
        -    String currentSelection = mActivity.getSpinnerSelection();
        -
        -
      6. -
      7. - Test the current settings against the test values: -
        -    assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
        -    assertEquals(TEST_STATE_DESTROY_SELECTION, currentSelection);
        -  } // end of testStateDestroy() method definition
        -
        -

        - Add the following members to the test case class: -

        -  public static final int TEST_STATE_DESTROY_POSITION = 2;
        -  public static final String TEST_STATE_DESTROY_SELECTION = "Earth";
        -
        -
      8. -
      -

      - To add the code for testing state management across a pause and resume, follow these steps: -

      -
        -
      1. - Add the test method testStatePause(): -
        -    @UiThreadTest
        -    public void testStatePause() {
        -
        -

        - The @UiThreadTest annotation tells Android to build this method so that it runs - on the UI thread. This allows the method to change the state of the spinner widget in the - application under test. This use of @UiThreadTest shows that, if necessary, you - can run an entire method on the UI thread. -

        -
      2. -
      3. - Set up instrumentation. Get the instrumentation object - that is controlling the application under test. This is used later to - invoke the onPause() and onResume() methods: -
        -    Instrumentation mInstr = this.getInstrumentation();
        -
        -
      4. -
      5. - Set the spinner selection to a test value: -
        -    mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION);
        -    mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION);
        -
        -
      6. -
      7. - Use instrumentation to call the Activity's onPause(): -
        -    mInstr.callActivityOnPause(mActivity);
        -
        -

        - Under test, the activity is waiting for input. The invocation of - {@link android.app.Instrumentation#callActivityOnPause(android.app.Activity)} - performs a call directly to the activity's onPause() instead - of manipulating the activity's UI to force it into a paused state. -

        -
      8. -
      9. - Force the spinner to a different selection: -
        -    mActivity.setSpinnerPosition(0);
        -    mActivity.setSpinnerSelection("");
        -
        -

        - This ensures that resuming the activity actually restores the - spinner's state rather than simply leaving it as it was. -

        -
      10. -
      11. - Use instrumentation to call the Activity's onResume(): -
        -    mInstr.callActivityOnResume(mActivity);
        -
        -

        - Invoking {@link android.app.Instrumentation#callActivityOnResume(android.app.Activity)} - affects the activity in a way similar to callActivityOnPause. The - activity's onResume() method is invoked instead of manipulating the - activity's UI to force it to resume. -

        -
      12. -
      13. - Get the current state of the spinner: -
        -    int currentPosition = mActivity.getSpinnerPosition();
        -    String currentSelection = mActivity.getSpinnerSelection();
        -
        -
      14. -
      15. - Test the current spinner state against the test values: -
        -    assertEquals(TEST_STATE_PAUSE_POSITION,currentPosition);
        -    assertEquals(TEST_STATE_PAUSE_SELECTION,currentSelection);
        -  } // end of testStatePause() method definition
        -
        -

        - Add the following members to the test case class: -

        -
        -  public static final int TEST_STATE_PAUSE_POSITION = 4;
        -  public static final String TEST_STATE_PAUSE_SELECTION = "Jupiter";
        -
        -
      16. -
      17. - Add the following imports: -
        -  import android.app.Instrumentation;
        -  import android.test.UiThreadTest;
        -
        -
      18. -
      -

      Running the Tests and Seeing the Results

      -

      - The most simple way to run the SpinnerActivityTest test case is to run it directly from the Package Explorer. -

      -

      - To run the SpinnerActivityTest test, follow these steps: -

      -
        -
      1. - In the Package Explorer, right-click the project SpinnerActivityTest at the top level, and then - select Run As > Android JUnit Test:
        - - Menu to run a test as an Android JUnit test - -
      2. -
      3. - You will see the emulator start. When the unlock option is displayed (its appearance depends on the API level you specified for the AVD), - unlock the home screen. -
      4. -
      5. - The test application starts. You see a new tab for the JUnit view, next to the Package Explorer tab:
        - - The JUnit window - -
      6. -
      -

      - This view contains two sub-panes. The top pane summarizes the tests that were run, and the bottom pane shows failure traces for - highlighted tests. -

      -

      - At the conclusion of a successful test run, this is the view's appearance:
      - - JUnit test run success - -

      -

      - The upper pane summarizes the test: -

      -
        -
      • - Total time elapsed for the test application(labeled Finished after <x> seconds). -
      • -
      • - Number of runs (Runs:) - the number of tests in the entire test class. -
      • -
      • - Number of errors (Errors:) - the number of program errors and exceptions encountered during - the test run. -
      • -
      • - Number of failures (Failures:) - the number of test failures encountered during the test - run. This is the number of assertion failures. A test can fail even if the program does not encounter an error. -
      • -
      • - A progress bar. The progress bar extends from left to right as the tests run. -

        - If all the tests succeed, the bar remains green. If a test fails, the bar turns from green to red. -

        -
      • -
      • - A test method summary. Below the bar, you see a line for each class in the test application. To look at the results for the individual - methods in a test, click the arrow at the left to expand the line. You see the name of each test method. To the - right of the name, you see the time taken by the test. You can look at the test's code - by double-clicking its name. -
      • -
      -

      - The lower pane contains the failure trace. If all the tests are successful, this pane is empty. If some tests fail, - then if you highlight a failed test in the upper pane, the lower view contains a stack trace for the test. This is - demonstrated in the next section. -

      -

      - Note: If you run the test application and nothing seems to happen, look for - the JUnit view. If you do not see it, you may have run the test application - as a regular Android application. - Remember that you need to run it as an Android JUnit - application. -

      -

      Forcing Some Tests to Fail

      -

      - A test is as useful when it fails as when it succeeds. This section shows what happens in Eclipse with ADT when a test fails. You - can quickly see that a test class has failed, find the method or methods that failed, and then use a failure trace to find - the exact problem. -

      -

      - The example application SpinnerActivity that you downloaded passes all the tests in the test application SpinnerActivityTest. - To force the test to fail, you must modify the example application. You change a line of setup code in the application under test. This - causes the testPreConditions() and testTextView() test methods to fail. -

      -

      - To force the tests to fail, follow these steps: -

      -
        -
      1. - In Eclipse with ADT, go to the SpinnerActivity project and open the file SpinnerActivity.java. -
      2. -
      3. - At the top of SpinnerActivity.java, at the end of the onCreate() method, find the following line: -
        -    // mySpinner.setOnItemSelectedListener(null);
        -
        -

        Remove the forward slash characters at the beginning of the line to - uncomment the line. This sets the listener callback to null: -

        -
        -    mySpinner.setOnItemSelectedListener(null);
        -
        -
      4. -
      5. - The testPreConditions() method in SpinnerActivityTest contains the following test: - assertTrue(mSpinner.getOnItemSelectedListener() != null);. This test asserts that the listener callback is not null. - Since you have modified the application under test, this assertion now fails. -
      6. -
      7. - Run the test, as described in the previous section Running the Tests and Seeing the Results. -
      8. -
      -

      - The JUnit view is either created or updated with the results of the test. Now, however, the progress bar is red, - the number of failures is 2, and small "x" icons appear in the list icons next to the testPreConditions and - TestSpinnerUI tests. This indicates that the tests have failed. The display is similar to this:
      - - The JUnit Failure window - -

      -

      - You now want to look at the failures to see exactly where they occurred. -

      -

      - To examine the failures, follow these steps: -

      -
        -
      1. - Click the testPreconditions entry. In the lower pane entitled Failure Trace, - you see a stack trace of the calls that led to the failure. This trace is similar to the following screenshot:
        - - The JUnit failure trace - -
      2. -
      3. - The first line of the trace tells you the error. In this case, a JUnit assertion failed. To look at the - assertion in the test code, double-click the next line (the first line of the trace). In the center pane - a new tabbed window opens, containing the code for the test application SpinnerActivityTest. The failed assertion - is highlighted in the middle of the window. -
      4. -
      -

      - The assertion failed because you modified the main application to set the getOnItemSelectedListener callback to null. -

      -

      - You can look at the failure in testTextView if you want. Remember, though, that testPreConditions is meant to verify the - initial setup of the application under test. If testPreConditions() fails, then succeeding tests can't be trusted. The best strategy to follow is to - fix the problem and re-run all the tests. -

      -

      - Remember to go back to SpinnerActivity.java and re-comment the line you uncommented in an earlier step. -

      -

      - You have now completed the tutorial. -

      -

      Next Steps

      -

      - This example test application has shown you how to create a test project and link it to - the application you want to test, how to choose and add a test case class, how to write - UI and state management tests, and how to run the tests against the application under - test. Now that you are familiar with the basics of testing Android applications, here - are some suggested next steps: -

      -

      - Learn more about testing on Android -

      -
        -
      • - If you haven't done so already, read the - Testing Android Applications - document in the Dev Guide. It provides an overview of how testing on Android - works. If you are just getting started with Android testing, reading that document will - help you understand the tools available to you, so that you can develop effective - tests. -
      • -
      -

      - Review the main Android test case classes -

      -
        -
      • - {@link android.test.ActivityInstrumentationTestCase2} -
      • -
      • - {@link android.test.ActivityUnitTestCase} -
      • -
      • - {@link android.test.ProviderTestCase2} -
      • -
      • - {@link android.test.ServiceTestCase} -
      • -
      -

      - Learn more about the assert and utility classes -

      -
        -
      • - {@link junit.framework.Assert}, the JUnit Assert class. -
      • -
      • - {@link android.test.MoreAsserts}, additional Android assert methods. -
      • -
      • - {@link android.test.ViewAsserts}, useful assertion methods for testing Views. -
      • -
      • - {@link android.test.TouchUtils}, utility methods for simulating touch events in an Activity. -
      • -
      -

      - Learn about instrumentation and the instrumented test runner -

      -
        -
      • - {@link android.app.Instrumentation}, the base instrumentation class. -
      • -
      • - {@link android.test.InstrumentationTestCase}, the base instrumentation test case. -
      • -
      • - {@link android.test.InstrumentationTestRunner}, the standard Android test runner. -
      • -
      -

      Appendix

      -

      Installing the Completed Test Application Java File

      -

      - The recommended approach to this tutorial is to follow the instructions step-by-step and - write the test code as you go. However, if you want to do this tutorial quickly, - you can install the entire Java file for the test application into the test project. -

      -

      - To do this, you first create a test project with the necessary structure and files by using - the automated tools in Eclipse. Then you exit Eclipse and copy the test application's Java file - from the SpinnerTest sample project into your test project. The SpinnerTest sample project is - part of the Samples component of the SDK. -

      -

      - The result is a complete test application, ready to run against the Spinner sample application. -

      -

      - To install the test application Java file, follow these steps: -

      -
        -
      1. - Set up the projects for the application under test and the test application, as described - in the section section Setting Up the Projects. -
      2. -
      3. - Set up the emulator, as described in the section Setting Up the Emulator. -
      4. -
      5. - Add the test case class, as described in the section Adding the test case class file. -
      6. -
      7. - Close Eclipse with ADT. -
      8. -
      9. - Copy the file <SDK_path>/samples/android-8/SpinnerTest/src/com/android/example/spinner/test/SpinnerActivityTest.java - to the directory workspace/SpinnerActivityTest/src/com/android/example/spinner/test/. -
      10. -
      11. - Restart Eclipse with ADT. -
      12. -
      13. - In Eclipse with ADT, re-build the project SpinnerActivityTest by selecting it in the Package Explorer, right-clicking, - and selecting Project > Clean. -
      14. -
      15. - The complete, working test application should now be in the SpinnerActivityTest project. -
      16. -
      -

      - You can now continue with the tutorial, starting at the section Adding the test case constructor and - following along in the text. -

      -

      For Users Not Developing In Eclipse

      -

      - If you are not developing in Eclipse, you can still do this tutorial. Android provides tools for - creating test applications using a code editor and command-line tools. You use the following tools: -

      -
        -
      • - adb - Installs and uninstalls applications and test applications to a device or the emulator. You - also use this tool to run the test application from the command line. -
      • -
      • - android - Manages projects and test projects. This tool also manages AVDs and Android platforms. -
      • -
      -

      - You use the emulator tool to run the emulator from the command line. -

      -

      - Here are the general steps for doing this tutorial using an editor and the command line: -

      -
        -
      1. - As described in the section Installing the Tutorial Sample Code, get the sample code. You will then - have a directory <SDK_path>/samples/android-8, containing (among others) the directories Spinner - and SpinnerTest: -
          -
        • - Spinner contains the main application, also known as the application under test. This tutorial focuses on the - common situation of writing tests for an application that already exists, so the main application is provided to you. -
        • -
        • - SpinnerTest contains all the code for the test application. If you want to run quickly through the tutorial, you can - install the test code and then follow the text. You may get more from the tutorial, however, if you write the code as you go. The instructions - for installing the test code are in the section Appendix: Installing the Completed Test Application. -
        • -
        -
      2. -
      3. - Navigate to the directory <SDK_path>/samples/android-8. -
      4. -
      5. - Create a new Android application project using android create project: -
        -$ android create project -t <APItarget> -k com.android.example.spinner -a SpinnerActivity -n SpinnerActivity -p Spinner
        -
        -

        - The value of <APItarget> should be "3" (API level 3) or higher. If you are already developing with a particular API level, and it is - higher than 3, then use that API level. -

        -

        - This a new Android project SpinnerActivity in the existing Spinner directory. The existing source and - resource files are not touched, but the android tool adds the necessary build files. -

        -
      6. -
      7. - Create a new Android test project using android create test-project: -
        -$ android create test-project -m ../Spinner -n SpinnerActivityTest -p SpinnerActivityTest
        -
        -

        - This will create a new Android test project in the new directory SpinnerActivityTest. You do this - so that the solution to the tutorial that is in SpinnerTest is left untouched. If you want to use the solution - code instead of entering it as you read through the tutorial, refer to the section - Appendix: Installing the Completed Test Application. -

        -

        - Note: Running android create test-project will automatically create - the file AndroidManifest.xml with the correct <instrumentation> element. -

        -
      8. -
      9. - Build the sample application. If you are building with Ant, then it is easiest to use the command ant debug to build a debug version, since the SDK comes - with a debug signing key. The result will be the file Spinner/bin/SpinnerActivity-debug.apk. - You can install this to your device or emulator. Attach your device or start the emulator if you haven't already, and run the command: -
        -$ adb install Spinner/bin/SpinnerActivity-debug.apk
        -
        -
      10. -
      11. - To create the test application, create a file SpinnerActivityTest.java in the directory - SpinnerActivityTest/src/com/android/example/spinner/test/. -
      12. -
      13. - Follow the tutorial, starting with the section Creating the Test Case Class. When you are prompted to - run the sample application, go the the Launcher screen in your device or emulator and select SpinnerActivity. - When you are prompted to run the test application, return here to continue with the following instructions. -
      14. -
      15. - Build the test application. If you are building with Ant, then it is easiest to use the command ant debug to build a - debug version, since the SDK comes with a debug signing key. The result will be the Android file - SpinnerActivityTest/bin/SpinnerActivityTest-debug.apk. You can install this to your device or emulator. - Attach your device or start the emulator if you haven't already, and run the command: -
        -$ adb install SpinnerActivityTest/bin/SpinnerActivityTest-debug.apk
        -
        -
      16. -
      17. - In your device or emulator, check that both the main application SpinnerActivity and the test application - SpinnerActivityTest are installed. -
      18. -
      19. - To run the test application, enter the following at the command line: -
        -$ adb shell am instrument -w com.android.example.spinner.test/android.test.InstrumentationTestRunner
        - 
        -
      20. -
      -

      - The result of a successful test looks like this: -

      -
      -com.android.example.spinner.test.SpinnerActivityTest:....
      -Test results for InstrumentationTestRunner=....
      -Time: 10.098
      -OK (4 tests)
      -
      -

      - If you force the test to fail, as described in the previous section Forcing Some Tests to Fail, then - the output looks like this: -

      -
      -com.android.example.spinner.test.SpinnerActivityTest:
      -Failure in testPreConditions:
      -junit.framework.AssertionFailedError
      -  at com.android.example.spinner.test.SpinnerActivityTest.testPreConditions(SpinnerActivityTest.java:104)
      -  at java.lang.reflect.Method.invokeNative(Native Method)
      -  at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)
      -  at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)
      -  at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:175)
      -  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
      -  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
      -  at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
      -  at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
      -Failure in testSpinnerUI:
      -junit.framework.ComparisonFailure: expected:<Result> but was:<Saturn>
      -  at com.android.example.spinner.test.SpinnerActivityTest.testSpinnerUI(SpinnerActivityTest.java:153)
      -  at java.lang.reflect.Method.invokeNative(Native Method)
      -  at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)
      -  at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)
      -  at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:175)
      -  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
      -  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
      -  at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
      -  at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
      -..
      -Test results for InstrumentationTestRunner=.F.F..
      -Time: 9.377
      -FAILURES!!!
      -Tests run: 4,  Failures: 2,  Errors: 0
      -
      diff --git a/docs/html/resources/tutorials/testing/helloandroid_test.jd b/docs/html/resources/tutorials/testing/helloandroid_test.jd deleted file mode 100644 index 4d949c86b079..000000000000 --- a/docs/html/resources/tutorials/testing/helloandroid_test.jd +++ /dev/null @@ -1,508 +0,0 @@ -page.title=Hello, Testing -parent.title=Tutorials -parent.link=../../browser.html?tag=tutorial -@jd:body -
      -
      -

      In this document

      -
        -
      1. - Creating the Test Project -
      2. -
      3. - Creating the Test Case Class -
          -
        1. - Adding the test case class file -
        2. -
        3. - Adding the test case constructor -
        4. -
        5. - Adding a setup method -
        6. -
        7. - Adding a preconditions test -
        8. -
        9. - Adding a unit test -
        10. -
        11. - The finished test case class -
        12. -
        -
      4. -
      5. - Running the Tests and Seeing the Results -
      6. -
      7. - Next Steps -
      8. -
      -

      Related Tutorials

      -
        -
      1. - Hello, World -
      2. -
      3. - Activity Testing -
      4. -
      -

      See Also

      -
        -
      1. - Testing Android Applications -
      2. -
      3. - {@link android.test.ActivityInstrumentationTestCase2} -
      4. -
      5. - {@link android.test.InstrumentationTestRunner} -
      6. -
      - -
      -
      -

      - Android offers a powerful but easy-to-use testing framework that is well integrated with the SDK tools. Because writing - tests is an important part of any development effort, this tutorial introduces the basics of testing and helps you get started testing quickly. - - To keep things simple, this tutorial builds on the Hello World tutorial, which you may have already completed. - It guides you through the process of setting up a test project, adding a test, and running the test against the Hello World application, all from inside the Eclipse environment. - Of course, when you are done with this tutorial, you will want to create a test project for your own app and add various types of tests to it. -

      -

      - If you'd like to read an overview of the test and instrumentation framework and the core test case classes available, look at - the Testing Android Applications topic. - If you prefer a more advanced testing tutorial, try the - Activity Testing tutorial. -

      -

      Prerequisites

      -

      - This tutorial and its code depend on the Hello World tutorial. If you haven't completed that tutorial already, - do so now. You will learn the fundamentals of Android application development, and you will - have an Android application that is ready to be tested. The tutorial guides you through the - setup of an Android test project using the ADT Plugin for Eclipse and other SDK tools. - You will need an SDK development platform that is version 1.5 - (API level 3) or higher. -

      -

      - If you aren't developing in Eclipse with ADT or you would like to run tests directly from the - command line, please see the topic Testing in Other IDEs - for instructions. -

      -

      Creating the Test Project

      -

      - In the Hello World tutorial you created Android application project called - HelloAndroid. A test of an Android application is also an Android - application, and you create it within an Eclipse project. The Eclipse with ADT - New Android Test Project dialog creates a new test project and the - framework of a new test application at the same time. -

      -

      - To create the test project and test application framework in Eclipse with ADT, follow these steps -

      -
        -
      1. - In Eclipse, select New > Project > Android > Android Test Project. -

        - - New Android Test Project menu - -

        -

        - The New Android Test Project dialog appears. -

        -
      2. -
      3. - Set the following values: -
          -
        • - Test Project Name: "HelloAndroidTest" -
        • -
        • - Test Target: Set "An existing Android project", click Browse, and then - select "HelloAndroid" from the list of projects. -
        • -
        • - Build Target: Set a target whose platform is Android 1.5 or above. -
        • -
        • - Application name: "HelloAndroidTest" -
        • -
        • - Package name: "com.example.helloandroid.test" -
        • -
        -

        - The dialog should now look like this: -

        - - New Android Test Project dialog with entries - -
      4. -
      5. - Click Finish. The new project appears in the Package Explorer. -
      6. -
      -

      Creating the Test Case Class

      -

      - You now have a test project HelloAndroidTest, and the basic structure of a test application - also called HelloAndroidTest. The basic structure includes all the files and directories you - need to build and run a test application, except for the class that contains - your tests (the test case class). -

      -

      - The next step is to define the test case class. In this tutorial, you define a test case class - that extends one of Android's test case classes designed for Activities. The class contains - definitions for four methods: -

      -
        -
      1. - HelloAndroidTest: This defines the constructor for the class. It is - required by the Android testing framework. -
      2. -
      3. - setUp(): This overrides the JUnit setUp() method. You use - it to initialize the environment before each test runs. -
      4. -
      5. - testPreconditions(): This defines a small test that ensures the Hello, Android - application starts up correctly. -
      6. -
      7. - testText(): This tests that what is displayed on the screen is the - same as what is contained in the application's string resources. It is an example of - a real unit test you would perform against an application's UI. -
      8. -
      -

      - The following sections contain the code for the test case class and its methods. -

      - -

      Adding the test case class file

      -

      - To add the Java file for the test case class, follow these steps -

      -
        -
      1. - In Eclipse, open the HelloAndroidTest project if it is not already open. -
      2. -
      3. - Within HelloAndroidTest, expand the src/ folder and - then find the package icon for com.example.helloandroid.test. - Right-click on the package icon and select New > Class: -

        - - Menu for creating a new class in the test application - -

        -

        - The New Java Class dialog appears. -

        -
      4. -
      5. - In the dialog, enter the following: -
          -
        • - Name: "HelloAndroidTest". This becomes the name of your test class. -
        • -
        • - Superclass: "android.test.ActivityInstrumentationTestCase2<HelloAndroid>". - The superclass is parameterized by an Activity class name. -

          - The dialog should now look like this: -

          - - New Java Class dialog with entries - -
        • -
        -

        - Do not change any of the other settings. Click Finish. -

        -
      6. -
      7. - You now have a new file HelloAndroidTest.java in the project. - This file contains the class HelloAndroidTest, - which extends the Activity test case class - ActivityInstrumentationTestCase2<T>. You parameterize the - class with HelloAndroid, which is the class name of the activity under test. -
      8. -
      9. - Open HelloAndroidTest.java. It should look like this: -
        -package com.example.helloandroid.test;
        -
        -import android.test.ActivityInstrumentationTestCase2;
        -
        -public class HelloAndroidTest extends ActivityInstrumentationTestCase2<HelloAndroid> {
        -}
        -
        -
      10. -
      11. - The test case class depends on the HelloAndroid class, which is not - yet imported. To import the class, add the following line just before the current - import statement: -
        -import com.example.helloandroid.HelloAndroid;
        -
        -
      12. -
      -

      Adding the test case constructor

      -

      - The test case class constructor is used by the Android testing framework when you run the test. - It calls the super constructor with parameters that tell the framework what Android application - should be tested. -

      -

      - Add the following constructor method immediately after the class definition: -

      -
      -    public HelloAndroidTest() {
      -      super("com.example.helloandroid", HelloAndroid.class);
      -    }
      -
      -

      - Save the file HelloAndroidTest.java. -

      -

      Adding a setup method

      -

      - The setUp() method overrides the JUnit {@link junit.framework.TestCase#setUp() setUp()} - method, which the Android testing framework calls prior to running each test method. You use - setUp() to initialize variables and prepare the test environment. For this - test case, the setUp() method starts the Hello, Android application, - retrieves the text being displayed on the screen, and retrieves the text string in the - resource file. -

      -

      - First, add the following code immediately after the constructor method: -

      -
      -    @Override
      -    protected void setUp() throws Exception {
      -        super.setUp();
      -        mActivity = this.getActivity();
      -        mView = (TextView) mActivity.findViewById(com.example.helloandroid.R.id.textview);
      -        resourceString = mActivity.getString(com.example.helloandroid.R.string.hello);
      -    }
      -
      -

      - For this code to work, you must also add some class members and another import statement. To - add the class members, add the following code immediately after the class definition: -

      -
      -    private HelloAndroid mActivity;
      -    private TextView mView;
      -    private String resourceString;
      -
      -

      - To add the import statement, add the following statement just after the import for - android.test.ActivityInstrumentationTestCase2: -

      -
      -  import android.widget.TextView;
      -
      -

      Adding a preconditions test

      -

      - A preconditions test checks the initial application conditions prior to executing other tests. - It's similar to setUp(), but with less overhead, since it only runs once. -

      -

      - Although a preconditions test can check for a variety of different conditions, - in this application it only needs to check whether the application under test is - initialized properly and the target TextView exists. - To do this, it calls the inherited - {@link junit.framework.Assert#assertNotNull(Object) assertNotNull()} - method, passing a reference to the TextView. - The test succeeds only if the object reference is not null. -

      -
      -    public void testPreconditions() {
      -      assertNotNull(mView);
      -    }
      -
      -

      Adding a unit test

      -

      - Now add a simple unit test to the test case class. - The method testText() will call a - {@link junit.framework.Assert JUnit Assert} - method to check whether the target TextView is displaying the expected text. -

      -

      - For this example, the test expects that the TextView is - displaying the string resource that was originally declared for it in HelloAndroid's - main.xml file, referred to by the resource ID hello. - The call to - {@link junit.framework.Assert#assertEquals(String, String) assertEquals(String,String)} - compares the expected value, read directly from the hellostring resource, - to the text displayed by the TextView, obtained from the - TextView's getText() method. The test succeeds only if the strings match. -

      -

      - To add this test, add the following code - immediately after the testPreconditions() method: -

      -
      -    public void testText() {
      -      assertEquals(resourceString,(String)mView.getText());
      -    }
      -
      -

      The finished test case class

      -

      - You have now finished writing the test. This is what the complete test case class - should look like: -

      -
      -package com.example.helloandroid.test;
      -
      -import com.example.helloandroid.HelloAndroid;
      -import android.test.ActivityInstrumentationTestCase2;
      -import android.widget.TextView;
      -
      -public class HelloAndroidTest extends ActivityInstrumentationTestCase2<HelloAndroid> {
      -    private HelloAndroid mActivity;  // the activity under test
      -    private TextView mView;          // the activity's TextView (the only view)
      -    private String resourceString;
      -
      -    public HelloAndroidTest() {
      -      super("com.example.helloandroid", HelloAndroid.class);
      -    }
      -    @Override
      -    protected void setUp() throws Exception {
      -        super.setUp();
      -        mActivity = this.getActivity();
      -        mView = (TextView) mActivity.findViewById(com.example.helloandroid.R.id.textview);
      -        resourceString = mActivity.getString(com.example.helloandroid.R.string.hello);
      -    }
      -    public void testPreconditions() {
      -      assertNotNull(mView);
      -    }
      -    public void testText() {
      -      assertEquals(resourceString,(String)mView.getText());
      -    }
      -}
      -
      -

      Running the Tests and Seeing the Results

      -

      - You can now run the tests you've created against the Hello, Android application. In Eclipse with - ADT, you run a test application as an Android JUnit test rather than a regular - Android application. -

      -

      - To run the test application as an Android JUnit test, in the Package Explorer right-click - the HelloAndroidTest project and select Run As > Android JUnit Test -

      - - Menu to run Hello, World as an Android JUnit test - -

      - The ADT plugin then launches the test application and the application - under test on a the target emulator or device. When both applications are running, - the testing framework runs the tests and reports the results in the JUnit view of Eclipse, - which appears by default as a tab next to the Package Explorer. -

      -

      - As shown below, the JUnit view shows test results in two separate panes: - an upper pane summarizes the tests that were run and a lower pane reports the failure traces - for the tests. In this case, the tests in this example have run successfully, so there is no - failure reported in the view: -

      - - JUnit test run success - -

      - The upper pane summarizes the test: -

      -
        -
      • - "Finished after x seconds": How long the test took to run. -
      • -
      • - "Runs": The number of tests run. -
      • -
      • - "Errors:": The number of program errors and exceptions encountered during - the test run. -
      • -
      • - "Failures:": The number of assertion failures encountered during the - test run. -
      • -
      • - A progress bar. The progress bar extends from left to right as the tests run. -

        - If all the tests succeed, the bar remains green. - If a test fails, the bar turns from green to red. -

        -
      • -
      • - A test method summary. Below the bar, you see a line for each class in the - test application, labeled by its fully-qualified class name. - To look at the results for the individual methods in a test case class, - click the arrow at the left of the class to expand the line. - You see the name of each test method. To the right of the method name, you see the - time needed to run that method. You can look at the method's code by - double-clicking its name. -
      • -
      -

      - The lower pane contains the failure trace. If all the tests are successful, - this pane is empty. If some tests fail, then if you select a failed test in the - upper pane, the lower view contains a stack trace for the test. -

      -

      Next Steps

      -

      - This simple example test application has shown you how to create a test project, - create a test class and test cases, and then run the tests against a target application. - Now that you are familiar with these fundamentals, here are some suggested next steps: -

      -

      - Learn more about testing on Android -

      -
        -
      • - The - Testing Android Applications - document in the Dev Guide provides an overview of how testing on Android works. - If you are just getting started with Android testing, reading that document will - help you understand the tools available to you, so that you can develop effective - tests. -
      • -
      -

      - Learn more about the testing classes available in Android -

      -
        -
      • - For an overview of the types of testing classes you can use, - browse through the reference documentation for - {@link android.test.ActivityInstrumentationTestCase2}, - {@link android.test.ProviderTestCase2}, - {@link android.test.ServiceTestCase}, and - {@link junit.framework.Assert}. -
      • -
      -

      - Explore the Android instrumentation framework -

      -
        -
      • - The {@link android.test.InstrumentationTestRunner} class contains the code that Android uses - to run tests against an application. The {@link android.test.InstrumentationTestCase} class - is the base class for test case classes that use additional instrumentation features. -
      • -
      -

      - Follow the Activity Testing tutorial -

      -
        -
      • - The Activity Testing - tutorial is an excellent follow-up to this tutorial. - It guides you through a more complex testing scenario that you develop against a - more realistic application. -
      • -
      diff --git a/docs/html/resources/tutorials/views/hello-autocomplete.jd b/docs/html/resources/tutorials/views/hello-autocomplete.jd deleted file mode 100644 index e26683de19e6..000000000000 --- a/docs/html/resources/tutorials/views/hello-autocomplete.jd +++ /dev/null @@ -1,173 +0,0 @@ -page.title=Auto Complete -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      To create a text entry widget that provides auto-complete suggestions, use -the {@link android.widget.AutoCompleteTextView} widget. Suggestions are received from a -collection of strings associated with the widget through an {@link -android.widget.ArrayAdapter}.

      - -

      In this tutorial, you will create a {@link android.widget.AutoCompleteTextView} widget that -provides suggestions for a country name.

      - - -
        -
      1. Start a new project named HelloAutoComplete.
      2. -
      3. Create an XML file named list_item.xml and save it inside the -res/layout/ folder. Edit the file to look like this: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent"
        -    android:padding="10dp"
        -    android:textSize="16sp"
        -    android:textColor="#000">
        -</TextView>
        -
        -

        This file defines a simple {@link android.widget.TextView} that will be used for each -item that appears in the list of suggestions.

        -
      4. -
      5. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        -    android:orientation="horizontal"
        -    android:layout_width="fill_parent" 
        -    android:layout_height="wrap_content"
        -    android:padding="5dp">
        -    <TextView
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text="Country" />
        -    <AutoCompleteTextView android:id="@+id/autocomplete_country"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:layout_marginLeft="5dp"/>
        -</LinearLayout>
        -
        -

        The {@link android.widget.TextView} is a label that introduces the {@link -android.widget.AutoCompleteTextView} widget. -

      6. - -
      7. Open HelloAutoComplete.java and insert the following code for the {@link -android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -@Override
        -protected void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -
        -    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
        -    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);
        -    textView.setAdapter(adapter);
        -}
        -
        - -

        After the content view is set to the main.xml layout, the {@link -android.widget.AutoCompleteTextView} widget is captured from the layout with {@link -android.app.Activity#findViewById(int)}. A new {@link -android.widget.ArrayAdapter} is then initialized to bind the list_item.xml layout -to each list item in the COUNTRIES string array (defined in the next step). -Finally, {@link android.widget.AutoCompleteTextView#setAdapter(T) setAdapter()} is called to -associate the {@link android.widget.ArrayAdapter} with the -{@link android.widget.AutoCompleteTextView} widget so that the string array will populate -the list of suggestions.

        -
      8. - -
      9. Inside the HelloAutoComplete class, add the string array: -
        -static final String[] COUNTRIES = new String[] {
        -  "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
        -  "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
        -  "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
        -  "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
        -  "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        -  "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
        -  "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
        -  "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        -  "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        -  "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
        -  "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
        -  "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
        -  "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
        -  "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
        -  "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
        -  "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
        -  "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
        -  "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
        -  "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
        -  "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
        -  "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
        -  "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
        -  "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
        -  "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
        -  "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
        -  "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
        -  "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
        -  "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
        -  "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
        -  "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
        -  "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
        -  "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
        -  "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
        -  "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
        -  "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
        -  "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        -  "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
        -  "Ukraine", "United Arab Emirates", "United Kingdom",
        -  "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
        -  "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
        -  "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
        -};
        -
        -

        This is the list of suggestions that will be provided in a drop-down list when the user types into -the {@link android.widget.AutoCompleteTextView} widget.

        -
      10. - -
      11. Run the application.
      12. -
      -

      As you type, you should see something like this:

      - - - -

      More Information

      - -

      Note that using a hard-coded string array is not a recommended design practice because your -application code should focus on behavior, not content. Application content such as strings -should be externalized from the code in order to make modifications to the content easier and -facilitate localization of the content. The hard-coded strings are used in this tutorial only to -make it simple and focus on the {@link android.widget.AutoCompleteTextView} widget. -Instead, your application should declare such string arrays in an XML file. This can be done -with a {@code <string-array<} resource in your project {@code res/values/strings.xml} file. -For example:

      -
      -<?xml version="1.0" encoding="utf-8"?>
      -<resources>
      -    <string-array name="countries_array">
      -        <item>Bahrain</item>
      -        <item>Bangladesh</item>
      -        <item>Barbados</item>
      -        <item>Belarus</item>
      -        <item>Belgium</item>
      -        <item>Belize</item>
      -        <item>Benin</item>
      -    </string-array>
      -</resources>
      -
      -

      To use these resource strings for the {@link android.widget.ArrayAdapter}, replace the original -{@link android.widget.ArrayAdapter} constructor line with the following:

      -
      -String[] countries = getResources().getStringArray(R.array.countries_array);
      -ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, countries);
      -
      - - -

      References

      -
        -
      • {@link android.widget.ArrayAdapter}
      • -
      • {@link android.widget.AutoCompleteTextView}
      • -
      - - diff --git a/docs/html/resources/tutorials/views/hello-datepicker.jd b/docs/html/resources/tutorials/views/hello-datepicker.jd deleted file mode 100644 index c50d6500f58b..000000000000 --- a/docs/html/resources/tutorials/views/hello-datepicker.jd +++ /dev/null @@ -1,173 +0,0 @@ -page.title=Date Picker -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      To provide a widget for selecting a date, use the {@link android.widget.DatePicker} -widget, which allows the user to select the month, day, and year, in a familiar interface.

      - -

      In this tutorial, you'll create a {@link android.app.DatePickerDialog}, which presents the -date picker in a floating dialog box at the press of a button. When the date is set by -the user, a {@link android.widget.TextView} will update with the new date.

      - -
        -
      1. Start a new project named HelloDatePicker.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="wrap_content"
        -    android:layout_height="wrap_content"
        -    android:orientation="vertical">
        -    <TextView android:id="@+id/dateDisplay"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text=""/>
        -    <Button android:id="@+id/pickDate"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text="Change the date"/>
        -</LinearLayout>
        -
        -

        This creates a basic {@link android.widget.LinearLayout} with a {@link android.widget.TextView} - that will display the date and a {@link android.widget.Button} that will open the {@link - android.app.DatePickerDialog}.

        -
      4. - -
      5. Open HelloDatePicker.java and add the following members to the class: -
        -    private TextView mDateDisplay;
        -    private Button mPickDate;
        -    private int mYear;
        -    private int mMonth;
        -    private int mDay;
        -
        -    static final int DATE_DIALOG_ID = 0;
        -
        -

        The first group of members define variables for the layout {@link android.view.View}s and the -date items. The DATE_DIALOG_ID is a static integer that uniquely identifies the {@link -android.app.Dialog} that will display the date picker.

        -
      6. - -
      7. Now add the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} -method: -
        -    protected void onCreate(Bundle savedInstanceState) {
        -        super.onCreate(savedInstanceState);
        -        setContentView(R.layout.main);
        -
        -        // capture our View elements
        -        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        -        mPickDate = (Button) findViewById(R.id.pickDate);
        -
        -        // add a click listener to the button
        -        mPickDate.setOnClickListener(new View.OnClickListener() {
        -            public void onClick(View v) {
        -                showDialog(DATE_DIALOG_ID);
        -            }
        -        });
        -
        -        // get the current date
        -        final Calendar c = Calendar.getInstance();
        -        mYear = c.get(Calendar.YEAR);
        -        mMonth = c.get(Calendar.MONTH);
        -        mDay = c.get(Calendar.DAY_OF_MONTH);
        -
        -        // display the current date (this method is below)
        -        updateDisplay();
        -    }
        -
        - -

        First, the content is set to the main.xml layout. Then the {@link -android.widget.TextView} and {@link android.widget.Button} elements are captured from the layout -with {@link android.app.Activity#findViewById(int)}. A -new {@link android.view.View.OnClickListener} is created for the -{@link android.widget.Button}, so that when it is clicked, it -will call {@link android.app.Activity#showDialog(int)}, passing the unique integer ID for -the date picker dialog. Using {@link android.app.Activity#showDialog(int)} allows the {@link -android.app.Activity} to manage the life-cycle of the dialog and will call the {@link -android.app.Activity#onCreateDialog(int)} callback method to request the {@link android.app.Dialog} -that should be displayed (which you'll -define later). After the on-click listener is set, a new {@link java.util.Calendar} is created -and the current year, month and day are acquired. Finally, the private -updateDisplay() method is called in order to fill the {@link android.widget.TextView} -with the current date.

        -
      8. - -
      9. Add the updateDisplay() method: -
        -    // updates the date in the TextView
        -    private void updateDisplay() {
        -        mDateDisplay.setText(
        -            new StringBuilder()
        -                    // Month is 0 based so add 1
        -                    .append(mMonth + 1).append("-")
        -                    .append(mDay).append("-")
        -                    .append(mYear).append(" "));
        -    }
        -
        -

        This method uses the member date values declared for the class to write the date to the layout's -{@link android.widget.TextView}, {@code mDateDisplay}, which was also declared and initialized -above.

        -
      10. - -
      11. Initialize a new {@link android.app.DatePickerDialog.OnDateSetListener} as a member of the -HelloDatePicker class: -
        -    // the callback received when the user "sets" the date in the dialog
        -    private DatePickerDialog.OnDateSetListener mDateSetListener =
        -            new DatePickerDialog.OnDateSetListener() {
        -
        -                public void onDateSet(DatePicker view, int year, 
        -                                      int monthOfYear, int dayOfMonth) {
        -                    mYear = year;
        -                    mMonth = monthOfYear;
        -                    mDay = dayOfMonth;
        -                    updateDisplay();
        -                }
        -            };
        -
        -

        The {@link android.app.DatePickerDialog.OnDateSetListener} listens for when the user -has set the date (by clicking the "Set" button). At that time, the {@link -android.app.DatePickerDialog.OnDateSetListener#onDateSet(DatePicker,int,int,int) onDateSet()} -callback method is called, which is defined to update the {@code mYear}, {@code mMonth}, and -{@code mDay} member fields with the new date then call the private updateDisplay() -method to update the {@link android.widget.TextView}.

        -
      12. - -
      13. Now add the {@link android.app.Activity#onCreateDialog(int)} callback method to the {@code -HelloDatePicker} class: -
        -@Override
        -protected Dialog onCreateDialog(int id) {
        -    switch (id) {
        -    case DATE_DIALOG_ID:
        -        return new DatePickerDialog(this,
        -                    mDateSetListener,
        -                    mYear, mMonth, mDay);
        -    }
        -    return null;
        -}
        -
        -

        This is an {@link android.app.Activity} callback method that is passed the integer ID given to -{@link android.app.Activity#showDialog(int)} (which is called by the button's {@link -android.view.View.OnClickListener}). When the ID matches the switch case defined here, a {@link -android.app.DatePickerDialog} is instantiated with the {@link -android.app.DatePickerDialog.OnDateSetListener} created in the previous -step, along with the date variables to initialize the widget date.

        -
      14. - -
      15. Run the application.
      16. -
      -

      When you press the "Change the date" button, you should see the following:

      - - -

      References

      -
        -
      • {@link android.app.DatePickerDialog}
      • -
      • {@link android.app.DatePickerDialog.OnDateSetListener}
      • -
      • {@link android.widget.Button}
      • -
      • {@link android.widget.TextView}
      • -
      • {@link java.util.Calendar}
      • -
      - diff --git a/docs/html/resources/tutorials/views/hello-formstuff.jd b/docs/html/resources/tutorials/views/hello-formstuff.jd deleted file mode 100644 index 1ddd1df7fe84..000000000000 --- a/docs/html/resources/tutorials/views/hello-formstuff.jd +++ /dev/null @@ -1,400 +0,0 @@ -page.title=Form Stuff -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      This tutorial introduces a variety of widgets that are useful when creating forms, such as -image buttons, text fields, checkboxes and radio buttons.

      - - -
        -
      1. Start a new project named HelloFormStuff.
      2. -
      3. Your res/layout/main.xml file should already have a basic {@link -android.widget.LinearLayout}: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:orientation="vertical"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent" >
        -</LinearLayout>
        -
        -

        For each widget you want to add, just put the respective View inside this {@link -android.widget.LinearLayout}.

        -
      4. -
      -

      Each section below also assumes that your HelloFormStuff Activity has the following -default implementation of the {@link android.app.Activity#onCreate(Bundle) onCreate()} method:

      -
      -public void onCreate(Bundle savedInstanceState) {
      -    super.onCreate(savedInstanceState);
      -    setContentView(R.layout.main);
      -}
      -
      - -

      Now select which kind of form widget you'd like to create:

      - - - - -

      Custom Button

      - -

      In this section, you will create a button with a custom image instead of text, using the {@link -android.widget.Button} widget and an XML file that defines three different images to use for the -different button states. When the button is pressed, a short message will be displayed.

      - - - - -
        -
      1. Copy the images on the right into the res/drawable/ directory of -your project. These will be used for the different button states.
      2. -
      3. Create a new file in the res/drawable/ directory named -android_button.xml. -Insert the following XML: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<selector xmlns:android="http://schemas.android.com/apk/res/android">
        -    <item android:drawable="@drawable/android_pressed"
        -          android:state_pressed="true" />
        -    <item android:drawable="@drawable/android_focused"
        -          android:state_focused="true" />
        -    <item android:drawable="@drawable/android_normal" />
        -</selector>
        -
        -

        This defines a single drawable resource, which will change its image based on the current -state of the button. The first <item> defines -android_pressed.png as the image when the button is pressed (it's been -activated); the second <item> defines android_focused.png as the image -when the button is focused (when the button is highlighted using the trackball or directional -pad); and the third <item> defines android_normal.png as the image -for the normal state (when neither pressed nor focused). This XML file now represents a single -drawable resource and when referenced by a {@link android.widget.Button} for its background, -the image displayed will change based on these three states.

        -

        Note: The order of the <item> elements is -important. When this drawable is referenced, the <item>s are traversed in-order to -determine which one is appropriate for the current button state. Because the "normal" image is last, -it is only applied when the conditions android:state_pressed and -android:state_focused have both evaluated false.

      4. -
      5. Open the res/layout/main.xml file and add the {@link -android.widget.Button} element: -
        -    <Button
        -        android:id="@+id/button"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:padding="10dp"
        -        android:background="@drawable/android_button"
        -        android:onClick="onButtonClicked"/>
        -
        -

        The android:background attribute specifies the drawable resource to use for the -button background (which, when saved at res/drawable/android.xml, is -referenced as @drawable/android). This replaces the normal background image -applied by the system with the drawable created above, which changes its image based on -the button state.

        -

        The attribute android:onClick specifies the name of a method in your activity -that the system should call when the user clicks the button. You'll create that method next.

        -
      6. - -
      7. To make the button do something when pressed, add the following -method inside your {@link android.app.Activity} class: -
        -public void onButtonClicked(View v) {
        -    // Do something when the button is clicked
        -    Toast.makeText(HelloFormStuff.this, "Button clicked", Toast.LENGTH_SHORT).show();
        -}
        -
        -

        When you specify this kind of method, which is used in your layout file with the {@code -android:onClick} attribute, the method must be public, have a void return -value, and accept a single {@code android.view.View} parameter. When the system calls this method, -it passes the {@code android.view.View} that was clicked.

        -
      8. -
      9. Now run the application.
      10. -
      - - - -

      Edit Text

      - -

      In this section, you will create a text field for user input, using the {@link -android.widget.EditText} widget. Once text has been entered into the field, the "Enter" key will -display the text in a toast message.

      - -
        -
      1. Open the res/layout/main.xml file and add the {@link android.widget.EditText} -element (inside the {@link android.widget.LinearLayout}): -
        -    <EditText
        -        android:id="@+id/edittext"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"/>
        -
        -
      2. -
      3. To do something with the text that the user types, add the following code -to the end of the {@link android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -final EditText edittext = (EditText) findViewById(R.id.edittext);
        -edittext.setOnKeyListener(new OnKeyListener() {
        -    public boolean onKey(View v, int keyCode, KeyEvent event) {
        -        // If the event is a key-down event on the "enter" button
        -        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
        -            (keyCode == KeyEvent.KEYCODE_ENTER)) {
        -          // Perform action on key press
        -          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
        -          return true;
        -        }
        -        return false;
        -    }
        -});
        -
        -

        This captures the {@link android.widget.EditText} element from the layout and adds an {@link -android.view.View.OnKeyListener}. The {@link android.view.View.OnKeyListener} must implement the -{@link android.view.View.OnKeyListener#onKey(View,int,KeyEvent)} method, which -defines the action to be made when a key is pressed while the widget has focus. In this case, the -method is defined to listen for the Enter key (when pressed down), then pop up a {@link -android.widget.Toast} message with the text that has been entered. The {@link -android.view.View.OnKeyListener#onKey(View,int,KeyEvent)} method should always return -true if the event has been handled, so that the event doesn't bubble-up (which would -result in a carriage return in the text field).

        -
      4. -
      5. Run the application.
      6. -
      - - - -

      Checkbox

      - -

      In this section, you will create a checkbox for selecting items, using the {@link -android.widget.CheckBox} widget. When the checkbox is pressed, a toast message will -indicate the current state of the checkbox.

      - -
        -
      1. Open the res/layout/main.xml file and add the {@link android.widget.CheckBox} -element (inside the {@link android.widget.LinearLayout}): -
        -    <CheckBox android:id="@+id/checkbox"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text="check it out"
        -        android:onClick="onCheckboxClicked"/>
        -
        -

        The attribute android:onClick specifies the name of a method in your activity -that the system should call when the user clicks the check box. You'll create that method next.

        -
      2. -
      3. To do something when the state is changed, add the following method inside your {@link -android.app.Activity} class:

        - -
        -public void onCheckboxClicked(View v) {
        -    // Perform action on clicks, depending on whether it's now checked
        -    if (((CheckBox) v).isChecked()) {
        -        Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
        -    } else {
        -        Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
        -    }
        -}
        -
        - -

        When you specify this kind of method, which is used in your layout file with the {@code -android:onClick} -attribute, the method must be public, have a void return value, and -accept a single {@code android.view.View} parameter. When the system calls this method, it -passes the {@code android.view.View} that was clicked. In this example, the {@code -android.view.View} is cast to a {@link android.widget.CheckBox} to determine whether the widget -has been checked or unchecked. The {@link android.widget.CheckBox} widget -handles its own state changes, so you only need to query the current state.

        -
      4. -
      5. Run it.
      6. -
      -

      Tip: If you need to change the state -yourself (such as when loading a saved {@link android.preference.CheckBoxPreference}), -use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link -android.widget.CompoundButton#toggle()} method.

      - - - -

      Radio Buttons

      - -

      In this section, you will create two mutually-exclusive radio buttons (enabling one disables -the other), using the {@link android.widget.RadioGroup} and {@link android.widget.RadioButton} -widgets. When either radio button is pressed, a toast message will be displayed.

      - -
        -
      1. Open the res/layout/main.xml file and add two {@link -android.widget.RadioButton}s, nested in a {@link android.widget.RadioGroup} (inside the {@link -android.widget.LinearLayout}): -
        -    <RadioGroup
        -      android:layout_width="fill_parent"
        -      android:layout_height="wrap_content"
        -      android:orientation="vertical">
        -      <RadioButton android:id="@+id/radio_red"
        -          android:layout_width="wrap_content"
        -          android:layout_height="wrap_content"
        -          android:text="Red"
        -          android:onClick="onRadioButtonClicked"/>
        -      <RadioButton android:id="@+id/radio_blue"
        -          android:layout_width="wrap_content"
        -          android:layout_height="wrap_content"
        -          android:text="Blue"
        -          android:onClick="onRadioButtonClicked"/>
        -    </RadioGroup>
        -
        -

        It's important that the {@link android.widget.RadioButton}s are grouped together by the {@link -android.widget.RadioGroup} element so that no more than one can be selected at a time. This logic -is automatically handled by the Android system. When one {@link android.widget.RadioButton} within -a group is selected, all others are automatically deselected.

        -

        The attribute android:onClick specifies the name of a method in your activity -that the system should call when the user clicks the radio button. You'll create that method -next.

        -
      2. - -
      3. To do something when each {@link android.widget.RadioButton} is selected, add the following -method inside your {@link android.app.Activity} class:

        - -
        -public void onRadioButtonClicked(View v) {
        -    // Perform action on clicks
        -    RadioButton rb = (RadioButton) v;
        -    Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
        -}
        -
        - -

        When you specify this kind of method, which is used in your layout file with the {@code -android:onClick} -attribute, the method must be public, have a void return value, and -accept a single {@code android.view.View} parameter. When the system calls this method, it -passes the {@code android.view.View} that was clicked.

        -

        Because each {@link android.widget.RadioButton} widget is grouped into a {@link -android.widget.RadioGroup}, each widget handles its own state changes when a new button is -selected.

        -
      4. -
      5. Run the application.
      6. -
      - -

      Tip: If you need to change the state -yourself (such as when loading a saved {@link android.preference.CheckBoxPreference}), -use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link -android.widget.CompoundButton#toggle()} method.

      - - - -

      Toggle Button

      - -

      In this section, you'll create a button used specifically for toggling between two -states, using the {@link android.widget.ToggleButton} widget. This widget is an excellent -alternative to radio buttons if you have two simple states that are mutually exclusive ("on" and -"off", for example).

      - -
        -
      1. Open the res/layout/main.xml file and add the {@link android.widget.ToggleButton} -element (inside the {@link android.widget.LinearLayout}): -
        -    <ToggleButton android:id="@+id/togglebutton"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:textOn="Vibrate on"
        -        android:textOff="Vibrate off"
        -        android:onClick="onToggleClicked"/>
        -
        -

        The attributes android:textOn and android:textOff specify the text -for the button when the button has been toggled on or off. The default values are "ON" and -"OFF".

        -

        The attribute android:onClick specifies the name of a method in your activity -that the system should call when the user clicks the button. You'll create that method next.

        -
      2. -
      3. To do something when the user clicks the button, add the following -method inside your {@link android.app.Activity} class:

        - -
        -public void onToggleClicked(View v) {
        -    // Perform action on clicks
        -    if (((ToggleButton) v).isChecked()) {
        -        Toast.makeText(HelloFormStuff.this, "Toggle on", Toast.LENGTH_SHORT).show();
        -    } else {
        -        Toast.makeText(HelloFormStuff.this, "Toggle off", Toast.LENGTH_SHORT).show();
        -    }
        -}
        -
        - -

        When you specify this kind of method, which is used in your layout file with the {@code -android:onClick} -attribute, the method must be public, have a void return value, and -accept a single {@code android.view.View} parameter. When the system calls this method, it -passes the {@code android.view.View} that was clicked.

        -

        In this example, the callback -method checks the new state of the button, then shows a {@link android.widget.Toast} message that -indicates the current state.

        - -

        Notice that the {@link android.widget.ToggleButton} handles its own state change between checked -and unchecked, so you just ask which it is.

        -
      4. Run the application.
      5. -
      - -

      Tip: If you need to change the state -yourself (such as when loading a saved {@link android.preference.CheckBoxPreference}), -use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link -android.widget.CompoundButton#toggle()} method.

      - - - - -

      Rating Bar

      - -

      In this section, you'll create a widget that allows the user to provide a rating, -with the {@link android.widget.RatingBar} widget.

      - -
        -
      1. Open the res/layout/main.xml file and add the {@link android.widget.RatingBar} -element (inside the {@link android.widget.LinearLayout}): -
        -    <RatingBar android:id="@+id/ratingbar"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:numStars="5"
        -        android:stepSize="1.0"/>
        -
        -

        The android:numStars attribute defines how many stars to display for the rating -bar. The android:stepSize attribute defines the granularity for each -star (for example, a value of 0.5 would allow half-star ratings).

        -
      2. -
      3. To do something when a new rating has been set, add the following code -to the end of the {@link android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar);
        -ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
        -    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        -        Toast.makeText(HelloFormStuff.this, "New Rating: " + rating, Toast.LENGTH_SHORT).show();
        -    }
        -});
        -
        -

        This captures the {@link android.widget.RatingBar} widget from the layout with {@link -android.app.Activity#findViewById(int)} and then sets an {@link -android.widget.RatingBar.OnRatingBarChangeListener}. The {@link -android.widget.RatingBar.OnRatingBarChangeListener#onRatingChanged(RatingBar,float,boolean) -onRatingChanged()} callback method then defines the action to perform when the user sets a rating. -In this case, a simple {@link android.widget.Toast} message displays the new rating.

        - -
      4. Run the application.
      5. -
      - -

      If you've added all the form widgets above, your application should look like this:

      - - -

      References

      -
        -
      • {@link android.widget.ImageButton}
      • -
      • {@link android.widget.EditText}
      • -
      • {@link android.widget.CheckBox}
      • -
      • {@link android.widget.RadioButton}
      • -
      • {@link android.widget.ToggleButton}
      • -
      • {@link android.widget.RatingBar}
      • -
      - diff --git a/docs/html/resources/tutorials/views/hello-gallery.jd b/docs/html/resources/tutorials/views/hello-gallery.jd deleted file mode 100644 index 5f2ed32b6ff6..000000000000 --- a/docs/html/resources/tutorials/views/hello-gallery.jd +++ /dev/null @@ -1,171 +0,0 @@ -page.title=Gallery -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.widget.Gallery} is a layout widget used to display items in a -horizontally scrolling list and positions the current selection at the center of the view.

      - -

      In this tutorial, you'll create a gallery of photos and then display a toast message each time a -gallery item is selected.

      - - -
        -
      1. Start a new project named HelloGallery.
      2. -
      3. Find some photos you'd like to use, or use these sample images. Save the images into the project's -res/drawable/ directory.
      4. -
      5. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
        -    android:id="@+id/gallery"
        -    android:layout_width="fill_parent"
        -    android:layout_height="wrap_content"
        -/>
        -
        -
      6. - -
      7. Open the HelloGallery.java file and insert the following code for the -{@link android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -@Override
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -
        -    Gallery gallery = (Gallery) findViewById(R.id.gallery);
        -    gallery.setAdapter(new ImageAdapter(this));
        -
        -    gallery.setOnItemClickListener(new OnItemClickListener() {
        -        public void onItemClick(AdapterView parent, View v, int position, long id) {
        -            Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
        -        }
        -    });
        -}
        -
        -

        This starts by setting the {@code main.xml} layout as the content view and then capturing the -{@link android.widget.Gallery} from -the layout with {@link -android.app.Activity#findViewById(int)}. A custom {@link android.widget.BaseAdapter} called -ImageAdapter is -instantiated and applied to the {@link android.widget.Gallery} with {@link -android.widget.AdapterView#setAdapter(T) setAdapter()}. (The ImageAdapter class is -defined next.) -Then an anonymous {@link android.widget.AdapterView.OnItemClickListener} is instantiated. The -{@link android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long)} -callback method receives the {@link android.widget.AdapterView} where the click occurred, the -specific {@link android.view.View} that received the click, the -position of the {@link android.view.View} clicked (zero-based), and the row ID of the item clicked -(if applicable). In this example, all that's needed is the position of the click to show a {@link -android.widget.Toast} message that says the position of the item, using -{@link android.widget.Toast#makeText(Context,CharSequence,int)} and {@link -android.widget.Toast#show()} (in a real world scenario, this ID could be used to get the full sized -image for some other task). -

        -
      8. -
      9. Create a new XML file in the res/values/ directory named attrs.xml. -Insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<resources>
        -    <declare-styleable name="HelloGallery">
        -        <attr name="android:galleryItemBackground" />
        -    </declare-styleable>
        -</resources>
        -
        -

        This is a custom styleable resource that can be applied to a layout. In this case, it will be -applied to the individual items placed into the {@link android.widget.Gallery} widget. The -<attr> element defines a specific attribute for the styleable, and in this case, it -refers to an existing platform attribute, {@link android.R.attr#galleryItemBackground}, which -defines a border styling for gallery items. In the next step, you'll -see how this attribute is referenced and then later applied to each item in the gallery.

        -
      10. - -
      11. Go back to the HelloGallery.java file. After the {@link - android.app.Activity#onCreate(Bundle)} method, define the custom ImageAdapter class: -
        -public class ImageAdapter extends BaseAdapter {
        -    int mGalleryItemBackground;
        -    private Context mContext;
        -
        -    private Integer[] mImageIds = {
        -            R.drawable.sample_1,
        -            R.drawable.sample_2,
        -            R.drawable.sample_3,
        -            R.drawable.sample_4,
        -            R.drawable.sample_5,
        -            R.drawable.sample_6,
        -            R.drawable.sample_7
        -    };
        -
        -    public ImageAdapter(Context c) {
        -        mContext = c;
        -        TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery);
        -        mGalleryItemBackground = attr.getResourceId(
        -                R.styleable.HelloGallery_android_galleryItemBackground, 0);
        -        attr.recycle();
        -    }
        -
        -    public int getCount() {
        -        return mImageIds.length;
        -    }
        -
        -    public Object getItem(int position) {
        -        return position;
        -    }
        -
        -    public long getItemId(int position) {
        -        return position;
        -    }
        -
        -    public View getView(int position, View convertView, ViewGroup parent) {
        -        ImageView imageView = new ImageView(mContext);
        -
        -        imageView.setImageResource(mImageIds[position]);
        -        imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
        -        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        -        imageView.setBackgroundResource(mGalleryItemBackground);
        -
        -        return imageView;
        -    }
        -}
        -
        -

        First, there are a few member variables, including an array of IDs that reference -the images saved in the drawable resources directory ({@code res/drawable/}).

        -

        Next is the class constructor, where the {@link android.content.Context} for an {@code -ImageAdapter} instance is defined and the styleable -resource defined in the last step is acquired and saved to a local field. At the end of the -constructor, {@link android.content.res.TypedArray#recycle()} is called on the {@link -android.content.res.TypedArray} so it can be re-used by the system.

        -

        The methods {@link android.widget.Adapter#getCount()}, {@link -android.widget.Adapter#getItem(int)}, and {@link android.widget.Adapter#getItemId(int)} are methods -that must be implemented for simple queries on the {@link android.widget.Adapter}. -The {@link android.widget.Adapter#getView(int,View,ViewGroup) method does the -work to apply an image to an {@link android.widget.ImageView} that will be embedded in the -{@link android.widget.Gallery}. In this method, the member {@link android.content.Context} is used -to create a new {@link android.widget.ImageView}. The {@link android.widget.ImageView} is prepared -by applying an image from the local array of drawable resources, setting the {@link -android.widget.Gallery.LayoutParams} height and width for the image, setting the scale to fit the -{@link android.widget.ImageView} dimensions, and then finally setting the background to use the -styleable attribute acquired in the constructor.

        - -

        See {@link android.widget.ImageView.ScaleType} for other image scaling options.

        -
      12. - -
      13. Run the application.
      14. -
      - -

      You should see something like this:

      - - - -

      References

      -
        -
      • {@link android.widget.BaseAdapter}
      • -
      • {@link android.widget.Gallery}
      • -
      • {@link android.widget.ImageView}
      • -
      • {@link android.widget.AdapterView.OnItemClickListener}
      • -
      - - diff --git a/docs/html/resources/tutorials/views/hello-gridview.jd b/docs/html/resources/tutorials/views/hello-gridview.jd deleted file mode 100644 index 03bfc5449187..000000000000 --- a/docs/html/resources/tutorials/views/hello-gridview.jd +++ /dev/null @@ -1,182 +0,0 @@ -page.title=Grid View -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.widget.GridView} is a {@link android.view.ViewGroup} that displays items in a -two-dimensional, -scrollable grid. The grid items are automatically inserted to the layout using a {@link -android.widget.ListAdapter}.

      - -

      In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a -toast message will display the position of the image.

      - - -
        -
      1. Start a new project named HelloGridView.
      2. -
      3. Find some photos you'd like to use, or download these sample images. Save the image files -into the project's -res/drawable/ directory.
      4. -
      5. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
        -    android:id="@+id/gridview"
        -    android:layout_width="fill_parent" 
        -    android:layout_height="fill_parent"
        -    android:columnWidth="90dp"
        -    android:numColumns="auto_fit"
        -    android:verticalSpacing="10dp"
        -    android:horizontalSpacing="10dp"
        -    android:stretchMode="columnWidth"
        -    android:gravity="center"
        -/>
        -
        -

        This {@link android.widget.GridView} will fill the entire screen. The attributes are rather -self explanatory. For more information about valid attributes, see the {@link -android.widget.GridView} reference.

        -
      6. -
      7. Open HelloGridView.java and insert the following code for the -{@link android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -
        -    GridView gridview = (GridView) findViewById(R.id.gridview);
        -    gridview.setAdapter(new ImageAdapter(this));
        -
        -    gridview.setOnItemClickListener(new OnItemClickListener() {
        -        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        -            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        -        }
        -    });
        -}
        -
        -

        After the {@code main.xml} layout is set for the content view, the -{@link android.widget.GridView} is captured from the layout with {@link -android.app.Activity#findViewById(int)}. The {@link -android.widget.GridView#setAdapter(T) setAdapter()} method then sets a custom adapter ({@code -ImageAdapter}) as the source for all items to be displayed in the grid. The {@code ImageAdapter} is -created in the next step.

        -

        To do something when an item in the grid is clicked, the {@link -android.widget.AdapterView#setOnItemClickListener(OnItemClickListener) setOnItemClickListener()} -method is passed a new {@link android.widget.AdapterView.OnItemClickListener}. This anonymous -instance defines the {@link -android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long) -onItemClick()} callback method to show a {@link android.widget.Toast} that displays the index -position (zero-based) of the selected item (in a real world scenario, the position could be used to -get the full sized -image for some other task).

        - -
      8. -
      9. Create a new class called ImageAdapter that extends {@link -android.widget.BaseAdapter}: -
        -public class ImageAdapter extends BaseAdapter {
        -    private Context mContext;
        -
        -    public ImageAdapter(Context c) {
        -        mContext = c;
        -    }
        -
        -    public int getCount() {
        -        return mThumbIds.length;
        -    }
        -
        -    public Object getItem(int position) {
        -        return null;
        -    }
        -
        -    public long getItemId(int position) {
        -        return 0;
        -    }
        -
        -    // create a new ImageView for each item referenced by the Adapter
        -    public View getView(int position, View convertView, ViewGroup parent) {
        -        ImageView imageView;
        -        if (convertView == null) {  // if it's not recycled, initialize some attributes
        -            imageView = new ImageView(mContext);
        -            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        -            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        -            imageView.setPadding(8, 8, 8, 8);
        -        } else {
        -            imageView = (ImageView) convertView;
        -        }
        -
        -        imageView.setImageResource(mThumbIds[position]);
        -        return imageView;
        -    }
        -
        -    // references to our images
        -    private Integer[] mThumbIds = {
        -            R.drawable.sample_2, R.drawable.sample_3,
        -            R.drawable.sample_4, R.drawable.sample_5,
        -            R.drawable.sample_6, R.drawable.sample_7,
        -            R.drawable.sample_0, R.drawable.sample_1,
        -            R.drawable.sample_2, R.drawable.sample_3,
        -            R.drawable.sample_4, R.drawable.sample_5,
        -            R.drawable.sample_6, R.drawable.sample_7,
        -            R.drawable.sample_0, R.drawable.sample_1,
        -            R.drawable.sample_2, R.drawable.sample_3,
        -            R.drawable.sample_4, R.drawable.sample_5,
        -            R.drawable.sample_6, R.drawable.sample_7
        -    };
        -}
        -
        -

        First, this implements some required methods inherited from {@link -android.widget.BaseAdapter}. The constructor and {@link -android.widget.Adapter#getCount()} are self-explanatory. Normally, {@link -android.widget.Adapter#getItem(int)} should return the actual object at the specified position in -the adapter, but it's ignored for this example. Likewise, {@link -android.widget.Adapter#getItemId(int)} should return the row id of the item, but it's not -needed here.

        - -

        The first method necessary is {@link android.widget.Adapter#getView(int,View,ViewGroup) -getView()}. This method creates a new {@link android.view.View} for each image added to the {@code -ImageAdapter}. When this is called, a {@link android.view.View} is passed in, which is normally a -recycled object (at least after this has been called once), so there's a check to see if the -object is null. If it is null, an {@link android.widget.ImageView} is instantiated and -configured with desired properties for the image presentation:

        -
          -
        • {@link android.view.View#setLayoutParams(ViewGroup.LayoutParams)} sets -the height and width for the View—this ensures that, no matter the size of the drawable, each -image is resized and cropped to fit in these dimensions, as appropriate.
        • -
        • {@link android.widget.ImageView#setScaleType(ImageView.ScaleType)} declares that images should -be cropped toward the center (if necessary).
        • -
        • {@link android.widget.ImageView#setPadding(int,int,int,int)} defines the padding for all -sides. (Note that, if the images have different aspect-ratios, then less -padding will cause for more cropping of the image if it does not match -the dimensions given to the ImageView.)
        • -
        - -

        If the {@link android.view.View} passed to {@link -android.widget.Adapter#getView(int,View,ViewGroup) getView()} is not null, then the local -{@link android.widget.ImageView} is initialized with the recycled {@link android.view.View} -object.

        - -

        At the end of the {@link android.widget.Adapter#getView(int,View,ViewGroup) getView()} method, -the {@code -position} integer passed into the method is used to select an image from the {@code mThumbIds} -array, which is set as the image resource for the {@link android.widget.ImageView}.

        -

        All that's left is to define the {@code mThumbIds} array of drawable resources.

        -
      10. -
      11. Run the application.
      12. -
      -

      Your grid layout should look something like this:

      - - -

      Try experimenting with the behaviors of the {@link android.widget.GridView} and {@link -android.widget.ImageView} elements by adjusting their properties. For example, instead of using -{@link android.view.View#setLayoutParams(ViewGroup.LayoutParams)}, try using -{@link android.widget.ImageView#setAdjustViewBounds(boolean)}.

      - -

      References

      -
        -
      • {@link android.widget.GridView}
      • -
      • {@link android.widget.ImageView}
      • -
      • {@link android.widget.BaseAdapter}
      • -
      • {@link android.widget.AdapterView.OnItemClickListener}
      • -
      - diff --git a/docs/html/resources/tutorials/views/hello-linearlayout.jd b/docs/html/resources/tutorials/views/hello-linearlayout.jd deleted file mode 100644 index 8e072b14e182..000000000000 --- a/docs/html/resources/tutorials/views/hello-linearlayout.jd +++ /dev/null @@ -1,133 +0,0 @@ -page.title=Linear Layout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.widget.LinearLayout} is a {@link android.view.ViewGroup} that displays child -{@link android.view.View} elements in a linear direction, either vertically or horizontally.

      - -

      You should be careful about over-using the {@link android.widget.LinearLayout}. If you begin -nesting multiple {@link android.widget.LinearLayout}s, you may want to consider using a {@link -android.widget.RelativeLayout} instead.

      - -
        -
      1. Start a new project named HelloLinearLayout.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:orientation="vertical"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent">
        -
        -  <LinearLayout
        -      android:orientation="horizontal"
        -      android:layout_width="fill_parent"
        -      android:layout_height="fill_parent"
        -      android:layout_weight="1">
        -      <TextView
        -          android:text="red"
        -          android:gravity="center_horizontal"
        -          android:background="#aa0000"
        -          android:layout_width="wrap_content"
        -          android:layout_height="fill_parent"
        -          android:layout_weight="1"/>
        -      <TextView
        -          android:text="green"
        -          android:gravity="center_horizontal"
        -          android:background="#00aa00"
        -          android:layout_width="wrap_content"
        -          android:layout_height="fill_parent"
        -          android:layout_weight="1"/>
        -      <TextView
        -          android:text="blue"
        -          android:gravity="center_horizontal"
        -          android:background="#0000aa"
        -          android:layout_width="wrap_content"
        -          android:layout_height="fill_parent"
        -          android:layout_weight="1"/>
        -      <TextView
        -          android:text="yellow"
        -          android:gravity="center_horizontal"
        -          android:background="#aaaa00"
        -          android:layout_width="wrap_content"
        -          android:layout_height="fill_parent"
        -          android:layout_weight="1"/>
        -  </LinearLayout>
        -	
        -  <LinearLayout
        -    android:orientation="vertical"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent"
        -    android:layout_weight="1">
        -    <TextView
        -        android:text="row one"
        -        android:textSize="15pt"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:layout_weight="1"/>
        -    <TextView
        -        android:text="row two"
        -        android:textSize="15pt"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:layout_weight="1"/>
        -    <TextView
        -        android:text="row three"
        -        android:textSize="15pt"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:layout_weight="1"/>
        -    <TextView
        -        android:text="row four"
        -        android:textSize="15pt"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:layout_weight="1"/>
        -  </LinearLayout>
        -
        -</LinearLayout>
        -
        - -

        Carefully inspect this XML. There is a root {@link android.widget.LinearLayout} that defines -its orientation to be vertical—all child {@link android.view.View}s (of which it has two) will -be stacked vertically. The first child is -another {@link android.widget.LinearLayout} that uses a horizontal orientation and the second child -is a {@link android.widget.LinearLayout} that uses a vertical orientation. Each of these nested -{@link android.widget.LinearLayout}s contain several {@link android.widget.TextView} elements, which -are oriented with each other in the manner defined by their parent {@link -android.widget.LinearLayout}.

        -
      4. -
      5. Now open HelloLinearLayout.java and be sure it loads the -res/layout/main.xml layout in the -{@link android.app.Activity#onCreate(Bundle) onCreate()} method:

        -
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -}
        -
        -

        The {@link android.app.Activity#setContentView(int)} method loads the -layout file for the {@link android.app.Activity}, specified by the resource -ID — R.layout.main refers to the res/layout/main.xml layout -file.

        -
      6. -
      7. Run the application.
      8. -
      -

      You should see the following:

      - - -

      Notice how the XML attributes define each View's behavior. Try -experimenting with different values for android:layout_weight to see how the screen -real estate is distributed based on the weight of each element. See the Common Layout Objects -document for more about how {@link android.widget.LinearLayout} handles the -android:layout_weight attribute.

      - -

      References

      -
        -
      • {@link android.widget.LinearLayout}
      • -
      • {@link android.widget.TextView}
      • -
      - - diff --git a/docs/html/resources/tutorials/views/hello-listview.jd b/docs/html/resources/tutorials/views/hello-listview.jd deleted file mode 100644 index 194258ed838d..000000000000 --- a/docs/html/resources/tutorials/views/hello-listview.jd +++ /dev/null @@ -1,170 +0,0 @@ -page.title=List View -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.widget.ListView} is a {@link android.view.ViewGroup} that creates a list of -scrollable items. The list items are automatically inserted to the list using a {@link -android.widget.ListAdapter}.

      - -

      In this tutorial, you'll create a scrollable list of country names that are read from a string array. -When a list item is selected, a toast message will display the position of the item in the list.

      - -
        -
      1. Start a new project named HelloListView.
      2. -
      3. Create an XML file named list_item.xml and save it inside the -res/layout/ folder. Insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent"
        -    android:padding="10dp"
        -    android:textSize="16sp" >
        -</TextView>
        -
        -

        This file defines the layout for each item that will be placed in the {@link -android.widget.ListView}.

        -
      4. - -
      5. Open the HelloListView.java and make the class extend {@link -android.app.ListActivity} (instead of {@link android.app.Activity}): -
        public class HelloListView extends ListActivity {
        -
      6. -
      7. Insert the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} -method: -
        -@Override
        -public void onCreate(Bundle savedInstanceState) {
        -  super.onCreate(savedInstanceState);
        -
        -  setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
        -
        -  ListView lv = getListView();
        -  lv.setTextFilterEnabled(true);
        -
        -  lv.setOnItemClickListener(new OnItemClickListener() {
        -    public void onItemClick(AdapterView<?> parent, View view,
        -        int position, long id) {
        -      // When clicked, show a toast with the TextView text
        -      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
        -          Toast.LENGTH_SHORT).show();
        -    }
        -  });
        -}
        -
        -

        Notice that this does not load a layout file for the Activity (which you usually do with {@link -android.app.Activity#setContentView(int)}). Instead, {@link -android.app.ListActivity#setListAdapter(ListAdapter)} automatically -adds a {@link android.widget.ListView} to fill the entire screen of the {@link -android.app.ListActivity}. This method takes an {@link android.widget.ArrayAdapter}, which -manages the array of list items that will be placed into the {@link android.widget.ListView}. The -{@link android.widget.ArrayAdapter} constructor takes the application {@link -android.content.Context}, the -layout description for each list item (created in -the previous step), and a {@link java.util.List} of objects to insert in the {@link -android.widget.ListView} (defined next).

        - -

        The {@link android.widget.ListView#setTextFilterEnabled(boolean)} method turns on text filtering -for the {@link android.widget.ListView}, so that when the user begins typing, the list will be -filtered.

        - -

        The {@link android.widget.ListView#setOnItemClickListener(OnItemClickListener)} method defines -the on-click listener for each item. When an item in the {@link android.widget.ListView} is clicked, -the {@link android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long) -onItemClick()} method is called and a {@link android.widget.Toast} message is displayed, using the -text from the clicked item.

        - -

        Tip: You can use list item designs provided by the platform -instead of defining your own layout file for the {@link android.widget.ListAdapter}. For example, -try using android.R.layout.simple_list_item_1 instead of -R.layout.list_item.

        -
      8. - -
      9. After the {@link android.app.Activity#onCreate(Bundle) onCreate()} method, add the string -array: -
        -  static final String[] COUNTRIES = new String[] {
        -    "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
        -    "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
        -    "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
        -    "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
        -    "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        -    "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
        -    "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
        -    "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        -    "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        -    "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
        -    "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
        -    "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
        -    "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
        -    "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
        -    "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
        -    "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
        -    "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
        -    "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
        -    "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
        -    "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
        -    "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
        -    "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
        -    "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
        -    "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
        -    "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
        -    "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
        -    "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
        -    "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
        -    "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
        -    "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
        -    "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
        -    "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
        -    "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
        -    "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
        -    "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
        -    "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        -    "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
        -    "Ukraine", "United Arab Emirates", "United Kingdom",
        -    "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
        -    "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
        -    "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
        -  };
        -
        -

        This is the array of strings that will be placed into the {@link android.widget.ListView}.

        -
      10. -
      11. Run the application.
      12. -
      -

      You can scroll the list, or type to filter it, then click an item to see a message. You -should see something like this:

      - - -

      Note that using a hard-coded string array is not the best design practice. One is -used in this tutorial for simplicity, in order to demonstrate the {@link -android.widget.ListView} widget. The better practice is to reference a string array -defined by an external resource, such as with a {@code <string-array>} -resource in your project {@code res/values/strings.xml} file. For example:

      -
      -<?xml version="1.0" encoding="utf-8"?>
      -<resources>
      -    <string-array name="countries_array">
      -        <item>Bahrain</item>
      -        <item>Bangladesh</item>
      -        <item>Barbados</item>
      -        <item>Belarus</item>
      -        <item>Belgium</item>
      -        <item>Belize</item>
      -        <item>Benin</item>
      -    </string-array>
      -</resources>
      -
      -

      To use these resource strings for the {@link android.widget.ArrayAdapter}, replace the original -{@link android.app.ListActivity#setListAdapter(ListAdapter)} line with the following:

      -
      -String[] countries = getResources().getStringArray(R.array.countries_array);
      -setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
      -
      - -

      References

      -
        -
      • {@link android.widget.ListView}
      • -
      • {@link android.widget.ListAdapter}
      • -
      - diff --git a/docs/html/resources/tutorials/views/hello-mapview.jd b/docs/html/resources/tutorials/views/hello-mapview.jd deleted file mode 100644 index 7a0bedf5dd69..000000000000 --- a/docs/html/resources/tutorials/views/hello-mapview.jd +++ /dev/null @@ -1,303 +0,0 @@ -page.title=Google Map View -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      Using the Google Maps library, you can create your own map-viewing Activity. In this -tutorial, you'll create a simple map application in two parts. In Part 1, you'll create an app that -shows a map the user can pan and zoom. In Part 2, you'll add overlay items that mark -points of interest.

      - -
      -

      This tutorial requires that you have the external Google Maps library -installed in your SDK environment. The Maps library is included with the Google APIs -add-on, which you can install using the Android SDK and -AVD Manager. To learn how, see Adding SDK -Components.

      - -

      After installing the Google APIs add-on in your SDK, set your project properties to use the build -target called "Google APIs by Google Inc.". See the instructions for setting a build -target in -Creating and Managing Projects in Eclipse or -Creating and Managing Projects on the Command Line, as appropriate for your environment.

      - -

      You will also need to set up a new AVD that uses the same Google APIs deployment target. See Creating and Managing Virtual Devices for -more information.

      - -

      For reference material, see the Google Maps -library documentation.

      - -
      - -

      Part 1: Creating a Map Activity

      - -
        -
      1. Start a new project named HelloGoogleMaps.
      2. - -
      3. Because the Maps library is not a part of the standard Android library, you must - declare it in the Android Manifest. Open the AndroidManifest.xml - file and add the following as a child of the <application> element: -
        <uses-library android:name="com.google.android.maps" />
        -
      4. - -
      5. You also need access to the Internet in order to retrieve map tiles, - so you must also request the {@link android.Manifest.permission#INTERNET} permission. - In the manifest file, add the following as a child of the <manifest> element: -
        <uses-permission android:name="android.permission.INTERNET" />
        -
      6. - -
      7. While you're in the manifest, give the map some more space by getting rid of the title bar -with the "NoTitleBar" theme: -
        -<activity android:name=".HelloGoogleMaps" android:label="@string/app_name"
        -     android:theme="@android:style/Theme.NoTitleBar">
        -
        -
      8. - - -
      9. Open the res/layout/main.xml file and add a single - {@code com.google.android.maps.MapView} as the root node: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<com.google.android.maps.MapView
        -    xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:id="@+id/mapview"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent"
        -    android:clickable="true"
        -    android:apiKey="Your Maps API Key goes here"
        -/>
        -
        -

        The android:clickable attribute defines whether you want to allow - user-interaction with the map. If this is "false" then touching the map does nothing.

        - -

        The android:apiKey attribute holds the Maps API Key for your - application, which proves your application and signer certificate has been registered with the - Maps service. This is required in order to receive the map data, even while you are - developing. Registration to the service is free and it only takes a couple - minutes to register your certificate and get a Maps API Key.

        -

        Go now to get a key. For instructions, read - Obtaining a Maps API - Key. For the purpose of this tutorial, you should register - with the SDK debug certificate, which will only be valid while your application is signed - with the debug key (once you sign with your private key, you will need a new API key). - When you get your key, insert it for the value of android:apiKey.

        -
      10. - -
      11. Now open the HelloGoogleMaps.java file. For this Activity, extend - {@code MapActivity} (instead of {@code android.app.Activity}):

        - -
        public class HelloGoogleMaps extends MapActivity {
        -

        This is a special sub-class of {@link android.app.Activity}, provided by the Maps - library, which provides important map capabilities.

        - -
      12. Inside every {@code MapActivity}, the isRouteDisplayed() method is required, so - override this method: -
        -@Override
        -protected boolean isRouteDisplayed() {
        -    return false;
        -}
        -
        -

        This method is required for some accounting from the Maps service to see if you're currently -displaying any route information. In this case, you're not, so return false.

        -
      13. - -
      14. Now add the standard {@link android.app.Activity#onCreate(Bundle) onCreate()} callback method -to the class: -
        -@Override
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -}
        -
        -

        This loads the layout file created above. In fact, this is now a workable application that will -display map tiles and allow the user to pan around the map. But there's no ability to zoom. -Fortunately, there's a very simple zoom feature built into the {@code MapView} class, which you can -summon with {@code setBuiltInZoomControls(boolean)}. Do this at the end of the {@link -android.app.Activity#onCreate(Bundle) onCreate()} method:

        -
        -    MapView mapView = (MapView) findViewById(R.id.mapview);
        -    mapView.setBuiltInZoomControls(true);
        -
        -
      15. -
      16. That's all there is to it. Run the application. (Remember, you must have an AVD configured to use the Google APIs -target, or be using a development device that includes the Maps library.)
      17. -
      - -

      Part 2: Adding Overlay Items

      - -

      So, now you have a map, but in many cases you'll also want to create your own map -markers and lay-overs. That's what you'll do now. In order to do so, you must implement the -{@code ItemizedOverlay} class, which can manage a whole set of {@code Overlay} (which are the -individual items placed on the map).

      - -
        -
      1. Create a new Java class named HelloItemizedOverlay that implements - {@code ItemizedOverlay}. - -

        When using Eclipse, right-click the package name in the Eclipse Package Explorer, and - select New > Class. Fill-in - the Name field as HelloItemizedOverlay. For the Superclass, enter - "com.google.android.maps.ItemizedOverlay". Click the checkbox for Constructors from - superclass. Click Finish.

      2. - -
      3. First, you need an OverlayItem {@link java.util.ArrayList}, in which you'll put - each of the OverlayItem objects you want on the map. Add this at the top of the - HelloItemizedOverlay class: - -
        private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
        -
      4. - -
      5. Now define the HelloItemizedOverlay constructors. The constructor must - define the default marker for each of the {@code OverlayItem}s. In order for the {@link - android.graphics.drawable.Drawable} to actually get drawn, it must have its bounds defined. Most - commonly, you want the center-point at the bottom of the image to be the point at which it's - attached to the map coordinates. This is handled for you with the {@code boundCenterBottom()} - method. Wrap this around our defaultMarker, so the super constructor call looks like this: -
        -public HelloItemizedOverlay(Drawable defaultMarker) {
        -  super(boundCenterBottom(defaultMarker));
        -}
        -
        -
      6. - -
      7. In order to add new {@code OverlayItem}s to the ArrayList, you need a new method: -
        -public void addOverlay(OverlayItem overlay) {
        -    mOverlays.add(overlay);
        -    populate();
        -}
        -

        Each time you add a new {@code OverlayItem} to the ArrayList, you must call - populate() for the {@code ItemizedOverlay}, which will read each of the - {@code OverlayItem}s and prepare them to be drawn.

        -
      8. - -
      9. When the populate() method executes, it will call createItem(int) in - the {@code ItemizedOverlay} to retrieve each {@code OverlayItem}. You must override this method to - properly read from the ArrayList and return the {@code OverlayItem} from the position specified - by the given integer. Your override method should look like this: - -
        -@Override
        -protected OverlayItem createItem(int i) {
        -  return mOverlays.get(i);
        -}
        -
        -
      10. - -
      11. You must also override the size() method to return the current number of - items in the ArrayList: -
        -@Override
        -public int size() {
        -  return mOverlays.size();
        -}
        -
        -
      12. - -
      13. Now set up the ability to handle touch events on the overlay items. First, you're - going to need a reference to the application {@link android.content.Context} as a member of - this class. So add {@code Context mContext} as a class member, then initialize it with a - new class constructor: -
        -public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
        -  super(boundCenterBottom(defaultMarker));
        -  mContext = context;
        -}
        -
        -

        This passes the {@code defaultMarker} up to the default constructor to bound its coordinates - and then initialize {@code mContext} with the given {@link android.content.Context}.

        - -

        Then override the {@code onTap(int)} callback method, which will handle the event - when an item is tapped by the user:

        -
        -@Override
        -protected boolean onTap(int index) {
        -  OverlayItem item = mOverlays.get(index);
        -  AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        -  dialog.setTitle(item.getTitle());
        -  dialog.setMessage(item.getSnippet());
        -  dialog.show();
        -  return true;
        -}
        -
        -

        This uses the member {@code android.content.Context} to create a new {@link -android.app.AlertDialog.Builder} and uses the tapped {@code OverlayItem}'s title and snippet for -the dialog's title and message text. (You'll see the {@code OverlayItem} title and snippet defined -when you create it below.)

        -
      14. - -
      - -

      You're now done with the HelloItemizedOverlay class and can start using it -to add items on the map.

      - -

      Go back to the HelloGoogleMaps class. In the following procedure, you'll create an -{@code OverlayItem} and add it to an instance of the HelloItemizedOverlay class, then -add the HelloItemizedOverlay to the MapView using a {@code GeoPoint} -to define its coordinates on the map.

      - - -
        -
      1. First, you need the image for the map overlay. If you don't have one handy, use the Android on - the right. Drag this image (or your own) into the res/drawable/ directory of your - project.
      2. - -
      3. At the end of your existing {@code onCreate()} method, instantiate : - -
        -List<Overlay> mapOverlays = mapView.getOverlays();
        -Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
        -HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
        - -

        All overlay elements on a map are held by the {@code MapView}, so when you want to add some, - you have to get a list from the getOverlays() method. Then instantiate the {@link - android.graphics.drawable.Drawable} used for the map marker, which was saved in the {@code - res/drawable/} directory. The constructor for {@code HelloItemizedOverlay} (your custom {@code - ItemizedOverlay}) takes the Drawable in order to set the default marker for all overlay - items.

        -
      4. - -
      5. Now create a {@code GeoPoint} that defines the map coordinates for the first overlay item, - and pass it to a new {@code OverlayItem}: -
        -GeoPoint point = new GeoPoint(19240000,-99120000);
        -OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
        -
        - -

        {@code GeoPoint} coordinates are specified in microdegrees (degrees * 1e6). The - {@code OverlayItem} constructor accepts the {@code GeoPoint} location, a string for the - item's title, and a string for the item's snippet text, respectively.

        -
      6. - -
      7. All that's left is to add this {@code OverlayItem} to your collection in the - {@code HelloItemizedOverlay} instance, then add the {@code HelloItemizedOverlay} to the MapView: -
        -itemizedoverlay.addOverlay(overlayitem);
        -mapOverlays.add(itemizedoverlay);
        -
        -
      8. - -
      9. Now run the application.
      10. -
      - -

      You should see the following:

      - -

      When you tap the overlay item, you'll see the dialog appear.

      - -

      Because the {@code ItemizedOverlay} class uses an {@code java.util.ArrayList} for all of the -{@code OverlayItem}s, it's easy to add more. Try adding another one. Before the -addOverlay() method is called, add these lines:

      -
      -GeoPoint point2 = new GeoPoint(35410000, 139460000);
      -OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa!", "I'm in Japan!");
      -
      -

      Run the application again. (You probably need to move the map to find the new overlay item.)

      - diff --git a/docs/html/resources/tutorials/views/hello-relativelayout.jd b/docs/html/resources/tutorials/views/hello-relativelayout.jd deleted file mode 100644 index adc117946d21..000000000000 --- a/docs/html/resources/tutorials/views/hello-relativelayout.jd +++ /dev/null @@ -1,89 +0,0 @@ -page.title=Relative Layout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.widget.RelativeLayout} is a {@link android.view.ViewGroup} that displays -child {@link android.view.View} elements in relative positions. The position of a {@link -android.view.View} can be specified as relative to sibling elements (such as to the left-of or below -a given element) or in positions relative to the {@link android.widget.RelativeLayout} area (such as -aligned to the bottom, left of center).

      - -

      A {@link android.widget.RelativeLayout} is a very powerful utility for designing a user -interface because it can eliminate nested {@link android.view.ViewGroup}s. If you find -yourself using several nested {@link android.widget.LinearLayout} groups, you may be able to -replace them with a single {@link android.widget.RelativeLayout}.

      - -
        -
      1. Start a new project named HelloRelativeLayout.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent">
        -    <TextView
        -        android:id="@+id/label"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:text="Type here:"/>
        -    <EditText
        -        android:id="@+id/entry"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:background="@android:drawable/editbox_background"
        -        android:layout_below="@id/label"/>
        -    <Button
        -        android:id="@+id/ok"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:layout_below="@id/entry"
        -        android:layout_alignParentRight="true"
        -        android:layout_marginLeft="10dip"
        -        android:text="OK" />
        -    <Button
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:layout_toLeftOf="@id/ok"
        -        android:layout_alignTop="@id/ok"
        -        android:text="Cancel" />
        -</RelativeLayout>
        -
        -

        Notice each of the android:layout_* attributes, such as layout_below, -layout_alignParentRight, and layout_toLeftOf. When using a {@link -android.widget.RelativeLayout}, you can use these attributes to describe -how you want to position each {@link android.view.View}. Each one of these attributes define a -different kind -of relative position. Some attributes use the resource ID of a sibling {@link android.view.View} -to define its own relative position. For example, the last {@link android.widget.Button} is -defined to lie to the left-of and aligned-with-the-top-of the {@link android.view.View} -identified by the ID ok (which is the previous {@link android.widget.Button}).

        -

        All of the available layout attributes are defined in {@link -android.widget.RelativeLayout.LayoutParams}.

        -
      4. -
      5. Make sure you load this layout in the -{@link android.app.Activity#onCreate(Bundle) onCreate()} method:

        -
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -}
        -
        -

        The {@link android.app.Activity#setContentView(int)} method loads the -layout file for the {@link android.app.Activity}, specified by the resource -ID — R.layout.main refers to the res/layout/main.xml layout -file.

        -
      6. -
      7. Run the application.
      8. -
      -

      You should see the following layout:

      - - -

      Resources

      -
        -
      • {@link android.widget.RelativeLayout}
      • -
      • {@link android.widget.RelativeLayout.LayoutParams}
      • -
      • {@link android.widget.TextView}
      • -
      • {@link android.widget.EditText}
      • -
      • {@link android.widget.Button}
      • -
      diff --git a/docs/html/resources/tutorials/views/hello-spinner.jd b/docs/html/resources/tutorials/views/hello-spinner.jd deleted file mode 100644 index e9dc20fb7ba8..000000000000 --- a/docs/html/resources/tutorials/views/hello-spinner.jd +++ /dev/null @@ -1,149 +0,0 @@ -page.title=Spinner -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.widget.Spinner} is a widget similar to a drop-down list for selecting items.

      - -

      In this tutorial, you'll create -a simple spinner widget that displays a list of planets. When one is selected, a toast message -will display the selected item.

      - -
        -
      1. Start a new project named HelloSpinner.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:orientation="vertical"
        -    android:padding="10dip"
        -    android:layout_width="fill_parent"
        -    android:layout_height="wrap_content">
        -    <TextView
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:layout_marginTop="10dip"
        -        android:text="@string/planet_prompt"
        -    />
        -    <Spinner 
        -        android:id="@+id/spinner"
        -        android:layout_width="fill_parent"
        -        android:layout_height="wrap_content"
        -        android:prompt="@string/planet_prompt"
        -    />
        -</LinearLayout>
        -
        -

        Notice that the {@link android.widget.TextView}'s android:text attribute and the -{@link android.widget.Spinner}'s android:prompt attribute both reference the same -string resource. This text behaves as a title for the widget. When applied to the {@link -android.widget.Spinner}, the title text will appear -in the selection dialog that appears upon selecting the widget.

        -
      4. - -
      5. Create a strings.xml file in res/values/ and edit the file to look -like this: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<resources>
        -    <string name="planet_prompt">Choose a planet</string>
        -    <string-array name="planets_array">
        -        <item>Mercury</item>
        -        <item>Venus</item>
        -        <item>Earth</item>
        -        <item>Mars</item>
        -        <item>Jupiter</item>
        -        <item>Saturn</item>
        -        <item>Uranus</item>
        -        <item>Neptune</item>
        -    </string-array>
        -</resources>
        -
        -

        The {@code <string>} element defines the title string referenced by the {@link -android.widget.TextView} and {@link android.widget.Spinner} in the layout above. The {@code -<string-array} element defines the list of strings that will be displayed as the list in -the {@link android.widget.Spinner} widget.

        -
      6. - -
      7. Now open the HelloSpinner.java file and insert the following code for the {@link -android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -@Override
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -
        -    Spinner spinner = (Spinner) findViewById(R.id.spinner);
        -    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        -            this, R.array.planets_array, android.R.layout.simple_spinner_item);
        -    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        -    spinner.setAdapter(adapter);
        -}
        -
        -

        After the {@code main.xml} layout is set as the content view, the {@link -android.widget.Spinner} widget is captured from the layout with {@link -android.app.Activity#findViewById(int)}. The {@link -android.widget.ArrayAdapter#createFromResource(Context,int,int) createFromResource()} method then -creates a new {@link android.widget.ArrayAdapter}, which binds each item in the string array -to the initial appearance for the {@link android.widget.Spinner} (which is how each item will -appear in the spinner when selected). The {@code -R.array.planets_array} ID references the {@code string-array} defined above and the -{@code android.R.layout.simple_spinner_item} ID references a layout for the standard spinner -appearance, defined by the platform. Then {@link -android.widget.ArrayAdapter#setDropDownViewResource(int)} is called to define the appearance for -each item when the widget is opened ({@code simple_spinner_dropdown_item} is -another standard layout defined by the platform). Finally, the {@link android.widget.ArrayAdapter} -is set to associate all of its items with the {@link android.widget.Spinner} by calling {@link -android.widget.AdapterView#setAdapter(T)}.

        -
      8. - -
      9. Now create a nested class that implements {@link -android.widget.AdapterView.OnItemSelectedListener}. This will provide a callback method that will -notify your application when an item has been selected from the {@link -android.widget.Spinner}. Here's what this class should look like: -
        -public class MyOnItemSelectedListener implements OnItemSelectedListener {
        -
        -    public void onItemSelected(AdapterView<?> parent,
        -        View view, int pos, long id) {
        -      Toast.makeText(parent.getContext(), "The planet is " +
        -          parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
        -    }
        -
        -    public void onNothingSelected(AdapterView parent) {
        -      // Do nothing.
        -    }
        -}
        -
        -

        The {@link android.widget.AdapterView.OnItemSelectedListener} requires the {@link -android.widget.AdapterView.OnItemSelectedListener#onItemSelected(AdapterView,View,int,long) -onItemSelected()} and {@link -android.widget.AdapterView.OnItemSelectedListener#onNothingSelected(AdapterView) -onNothingSelected()} callback methods. The former is called when an item from the {@link -android.widget.AdapterView} is selected, in which case, a short {@link android.widget.Toast} -message displays the selected text; and the latter is called when a selection disappears from the -{@link android.widget.AdapterView}, which doesn't happen in this case, so it's ignored.

        -
      10. - -
      11. Now the {@code MyOnItemSelectedListener} needs to be applied to the {@link -android.widget.Spinner}. Go back to the {@link android.app.Activity#onCreate(Bundle) onCreate()} -method and add the following line to the end: -
        -    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
        -
        -

        This creates a new anonymous instance of the {@code MyOnItemSelectedListener} and sets it as the -listener for the {@link android.widget.Spinner}.

        -
      12. - -
      13. Run the application.
      14. -
      -

      It should look like this:

      - - - -

      Resources

      -
        -
      • {@link android.R.layout}
      • -
      • {@link android.widget.ArrayAdapter}
      • -
      • {@link android.widget.Spinner}
      • -
      - diff --git a/docs/html/resources/tutorials/views/hello-tablelayout.jd b/docs/html/resources/tutorials/views/hello-tablelayout.jd deleted file mode 100644 index c8c59828599c..000000000000 --- a/docs/html/resources/tutorials/views/hello-tablelayout.jd +++ /dev/null @@ -1,124 +0,0 @@ -page.title=Table Layout -parent.title=Hello, Views -parent.link=index.html -@jd:body - - -

      {@link android.widget.TableLayout} is a {@link android.view.ViewGroup} that -displays child {@link android.view.View} elements in rows and columns.

      - -
        -
      1. Start a new project named HelloTableLayout.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent"
        -    android:stretchColumns="1">
        -
        -    <TableRow>
        -        <TextView
        -            android:layout_column="1"
        -            android:text="Open..."
        -            android:padding="3dip" />
        -        <TextView
        -            android:text="Ctrl-O"
        -            android:gravity="right"
        -            android:padding="3dip" />
        -    </TableRow>
        -
        -    <TableRow>
        -        <TextView
        -            android:layout_column="1"
        -            android:text="Save..."
        -            android:padding="3dip" />
        -        <TextView
        -            android:text="Ctrl-S"
        -            android:gravity="right"
        -            android:padding="3dip" />
        -    </TableRow>
        -
        -    <TableRow>
        -        <TextView
        -            android:layout_column="1"
        -            android:text="Save As..."
        -            android:padding="3dip" />
        -        <TextView
        -            android:text="Ctrl-Shift-S"
        -            android:gravity="right"
        -            android:padding="3dip" />
        -    </TableRow>
        -
        -    <View
        -        android:layout_height="2dip"
        -        android:background="#FF909090" />
        -
        -    <TableRow>
        -        <TextView
        -            android:text="X"
        -            android:padding="3dip" />
        -        <TextView
        -            android:text="Import..."
        -            android:padding="3dip" />
        -    </TableRow>
        -
        -    <TableRow>
        -        <TextView
        -            android:text="X"
        -            android:padding="3dip" />
        -        <TextView
        -            android:text="Export..."
        -            android:padding="3dip" />
        -        <TextView
        -            android:text="Ctrl-E"
        -            android:gravity="right"
        -            android:padding="3dip" />
        -    </TableRow>
        -
        -    <View
        -        android:layout_height="2dip"
        -        android:background="#FF909090" />
        -
        -    <TableRow>
        -        <TextView
        -            android:layout_column="1"
        -            android:text="Quit"
        -            android:padding="3dip" />
        -    </TableRow>
        -</TableLayout>
        -
        -

        Notice how this resembles the structure of an HTML table. The {@link android.widget.TableLayout} -element is like the HTML <table> element; {@link android.widget.TableRow} is like -a ><tr>> element; -but for the cells, you can use any kind of {@link android.view.View} element. In this example, a -{@link android.widget.TextView} is used for each cell. In between some of the rows, there is also a -basic {@link android.view.View}, which is used to draw a horizontal line.

        - -
      4. -
      5. Make sure your HelloTableLayout Activity loads this layout in the -{@link android.app.Activity#onCreate(Bundle) onCreate()} method: -
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -}
        -
        -

        The {@link android.app.Activity#setContentView(int)} method loads the -layout file for the {@link android.app.Activity}, specified by the resource -ID — R.layout.main refers to the res/layout/main.xml layout -file.

        -
      6. -
      7. Run the application.
      8. -
      -

      You should see the following:

      - - -

      References

      -
        -
      • {@link android.widget.TableLayout}
      • -
      • {@link android.widget.TableRow}
      • -
      • {@link android.widget.TextView}
      • -
      - - diff --git a/docs/html/resources/tutorials/views/hello-tabwidget.jd b/docs/html/resources/tutorials/views/hello-tabwidget.jd deleted file mode 100644 index 9bafd84e26c1..000000000000 --- a/docs/html/resources/tutorials/views/hello-tabwidget.jd +++ /dev/null @@ -1,210 +0,0 @@ -page.title=Tab Layout -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      To create a tabbed UI, you need to use a {@link android.widget.TabHost} and a {@link -android.widget.TabWidget}. The {@link android.widget.TabHost} must be the root node for the layout, -which contains both the {@link android.widget.TabWidget} for displaying the tabs and a {@link -android.widget.FrameLayout} for displaying the tab content.

      - -

      You can implement your tab content in one of two ways: use the tabs to swap -{@link android.view.View}s within the same {@link android.app.Activity}, or use the tabs to change -between entirely separate activities. Which method you want for your application will depend on your -demands, but if each tab provides a distinct user activity, then it probably makes sense to use -a separate {@link android.app.Activity} for each tab, so that you can better manage the application -in discrete groups, rather than one massive application and layout.

      - -

      In this tutorial, you'll create a tabbed UI that uses a separate {@link -android.app.Activity} for each tab.

      - -
        -
      1. Start a new project named HelloTabWidget.
      2. -
      3. First, create three separate {@link android.app.Activity} classes in your project: -ArtistsActivity, AlbumsActivity, and SongsActivity. These -will each represent a separate tab. For now, make each one display a simple message using a {@link -android.widget.TextView}. For example: -
        -public class ArtistsActivity extends Activity {
        -    public void onCreate(Bundle savedInstanceState) {
        -        super.onCreate(savedInstanceState);
        -
        -        TextView textview = new TextView(this);
        -        textview.setText("This is the Artists tab");
        -        setContentView(textview);
        -    }
        -}
        -
        -

        Notice that this doesn't use a layout file. Just create a {@link -android.widget.TextView}, give it some text and set that as the content. Duplicate this for -each of the three activities, and add the corresponding <activity/> tags to the Android Manifest file.

        - -
      4. You need an icon for each of your tabs. For each icon, you should create two versions: one -for when the tab is selected and one for when it is unselected. The -general design recommendation is for the selected icon to be a dark color (grey), and the -unselected icon to be a light color (white). (See the Icon Design -Guidelines.) For example: -

        - - -

        -

        For this tutorial, you can copy these images and use them for all three tabs. (When you -create tabs in your own application, you should create customized tab icons.)

        -

        Now create a state-list drawable -that specifies which image to use for each tab state:

        -
          -
        1. Save the icon images in your project res/drawable/ directory.
        2. -
        3. Create a new XML file in res/drawable/ -named ic_tab_artists.xml and insert the following: -
          -<?xml version="1.0" encoding="utf-8"?>
          -<selector xmlns:android="http://schemas.android.com/apk/res/android">
          -    <!-- When selected, use grey -->
          -    <item android:drawable="@drawable/ic_tab_artists_grey"
          -          android:state_selected="true" />
          -    <!-- When not selected, use white-->
          -    <item android:drawable="@drawable/ic_tab_artists_white" />
          -</selector>
          -
          -

          This is a state-list drawable, -which you will apply as the tab image. When the tab state changes, the tab icon will -automatically switch between the images defined here.

          -
        4. -
        -
      5. - -
      6. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:id="@android:id/tabhost"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent">
        -    <LinearLayout
        -        android:orientation="vertical"
        -        android:layout_width="fill_parent"
        -        android:layout_height="fill_parent"
        -        android:padding="5dp">
        -        <TabWidget
        -            android:id="@android:id/tabs"
        -            android:layout_width="fill_parent"
        -            android:layout_height="wrap_content" />
        -        <FrameLayout
        -            android:id="@android:id/tabcontent"
        -            android:layout_width="fill_parent"
        -            android:layout_height="fill_parent"
        -            android:padding="5dp" />
        -    </LinearLayout>
        -</TabHost>
        -
        -

        This is the layout that will display the tabs and provide navigation between each {@link - android.app.Activity} created above.

        -

        The {@link android.widget.TabHost} requires that a {@link android.widget.TabWidget} and a -{@link android.widget.FrameLayout} both live somewhere within it. To position the {@link -android.widget.TabWidget} and {@link android.widget.FrameLayout} vertically, a {@link -android.widget.LinearLayout} is used. The {@link android.widget.FrameLayout} is where the content -for each tab goes, which is empty now because the {@link android.widget.TabHost} will automatically -embed each {@link android.app.Activity} within it.

        -

        Notice that the {@link android.widget.TabWidget} and the {@link android.widget.FrameLayout} - elements have the IDs {@code tabs} and {@code tabcontent}, respectively. These names - must be used so that the {@link android.widget.TabHost} can retrieve references to each of - them. It expects exactly these names.

        -
      7. - -
      8. Now open HelloTabWidget.java and make it extend {@link - android.app.TabActivity}:

        -
        -public class HelloTabWidget extends TabActivity {
        -
        -
      9. -
      10. Use the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} - method: -
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -
        -    Resources res = getResources(); // Resource object to get Drawables
        -    TabHost tabHost = getTabHost();  // The activity TabHost
        -    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        -    Intent intent;  // Reusable Intent for each tab
        -
        -    // Create an Intent to launch an Activity for the tab (to be reused)
        -    intent = new Intent().setClass(this, ArtistsActivity.class);
        -
        -    // Initialize a TabSpec for each tab and add it to the TabHost
        -    spec = tabHost.newTabSpec("artists").setIndicator("Artists",
        -                      res.getDrawable(R.drawable.ic_tab_artists))
        -                  .setContent(intent);
        -    tabHost.addTab(spec);
        -
        -    // Do the same for the other tabs
        -    intent = new Intent().setClass(this, AlbumsActivity.class);
        -    spec = tabHost.newTabSpec("albums").setIndicator("Albums",
        -                      res.getDrawable(R.drawable.ic_tab_albums))
        -                  .setContent(intent);
        -    tabHost.addTab(spec);
        -
        -    intent = new Intent().setClass(this, SongsActivity.class);
        -    spec = tabHost.newTabSpec("songs").setIndicator("Songs",
        -                      res.getDrawable(R.drawable.ic_tab_songs))
        -                  .setContent(intent);
        -    tabHost.addTab(spec);
        -
        -    tabHost.setCurrentTab(2);
        -}
        -
        -

        This sets up each tab with their text and icon, and assigns each one an {@link -android.app.Activity}.

        -

        A reference to the {@link android.widget.TabHost} is first captured with {@link -android.app.TabActivity#getTabHost()}. Then, for -each tab, a {@link android.widget.TabHost.TabSpec} is created to define the tab properties. The -{@link android.widget.TabHost#newTabSpec(String)} method creates a new {@link -android.widget.TabHost.TabSpec} identified by the given string tag. For each -{@link android.widget.TabHost.TabSpec}, {@link -android.widget.TabHost.TabSpec#setIndicator(CharSequence,Drawable)} is called to set the text and -icon for the tab, and {@link android.widget.TabHost.TabSpec#setContent(Intent)} is called to specify -the {@link android.content.Intent} to open the appropriate {@link android.app.Activity}. Each -{@link android.widget.TabHost.TabSpec} is then added to the {@link android.widget.TabHost} by -calling {@link android.widget.TabHost#addTab(TabHost.TabSpec)}.

        - -

        At the very end, {@link - android.widget.TabHost#setCurrentTab(int)} opens the tab to be displayed by default, specified - by the index position of the tab.

        - -

        Notice that not once was the {@link android.widget.TabWidget} object referenced. This is - because a {@link android.widget.TabWidget} must always be a child of a {@link - android.widget.TabHost}, which is what you use for almost all interaction with the tabs. So when - a tab is added to the {@link android.widget.TabHost}, it's automatically added to the child - {@link android.widget.TabWidget}.

        -
      11. - -
      12. Now open the Android Manifest file and add the NoTitleBar theme to the -HelloTabWidget's - <activity> tag. This will remove the default application title from the top - of the layout, leaving more space for the tabs, which effectively operate as their own titles. - The <activity> tag should look like this: -
        -<activity android:name=".HelloTabWidget" android:label="@string/app_name"
        -          android:theme="@android:style/Theme.NoTitleBar">
        -
        -
      13. - -
      14. Run the application.
      15. -
      - - -

      Your application should look like this (though your icons may be different):

      - - -

      References

      -
        -
      • {@link android.widget.TabWidget}
      • -
      • {@link android.widget.TabHost}
      • -
      • {@link android.widget.TabHost.TabSpec}
      • -
      • {@link android.widget.FrameLayout}
      • -
      - diff --git a/docs/html/resources/tutorials/views/hello-timepicker.jd b/docs/html/resources/tutorials/views/hello-timepicker.jd deleted file mode 100644 index cf16c8ecd32a..000000000000 --- a/docs/html/resources/tutorials/views/hello-timepicker.jd +++ /dev/null @@ -1,167 +0,0 @@ -page.title=Time Picker -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      To provide a widget for selecting a time, use the {@link android.widget.TimePicker} -widget, which allows the user to select the hour and minute in a familiar interface.

      - -

      In this tutorial, you'll create a {@link android.app.TimePickerDialog}, which presents the -time picker in a floating dialog box at the press of a button. When the time is set by -the user, a {@link android.widget.TextView} will update with the new date.

      - -
        -
      1. Start a new project named HelloTimePicker.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:layout_width="wrap_content"
        -    android:layout_height="wrap_content"
        -    android:orientation="vertical">
        -    <TextView android:id="@+id/timeDisplay"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text=""/>
        -    <Button android:id="@+id/pickTime"
        -        android:layout_width="wrap_content"
        -        android:layout_height="wrap_content"
        -        android:text="Change the time"/>
        -</LinearLayout>
        -
        -

        This is a basic {@link android.widget.LinearLayout} with a {@link android.widget.TextView} -that will display the time and a {@link android.widget.Button} that will open the {@link -android.app.TimePickerDialog}.

        -
      4. - -
      5. Open HelloTimePicker.java and insert the following class members: -
        -    private TextView mTimeDisplay;
        -    private Button mPickTime;
        -
        -    private int mHour;
        -    private int mMinute;
        -
        -    static final int TIME_DIALOG_ID = 0;
        -
        -

        This declares variables for the layout elements and time fields. -The TIME_DIALOG_ID is a static integer that uniquely identifies the dialog.

        -
      6. -
      7. Now insert the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} -method: -
        -    @Override
        -    protected void onCreate(Bundle savedInstanceState) {
        -        super.onCreate(savedInstanceState);
        -        setContentView(R.layout.main);
        -
        -        // capture our View elements
        -        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        -        mPickTime = (Button) findViewById(R.id.pickTime);
        -
        -        // add a click listener to the button
        -        mPickTime.setOnClickListener(new View.OnClickListener() {
        -            public void onClick(View v) {
        -                showDialog(TIME_DIALOG_ID);
        -            }
        -        });
        -
        -        // get the current time
        -        final Calendar c = Calendar.getInstance();
        -        mHour = c.get(Calendar.HOUR_OF_DAY);
        -        mMinute = c.get(Calendar.MINUTE);
        -
        -        // display the current date
        -        updateDisplay();
        -    }
        -
        - -

        First, the content is set to the main.xml layout and then the {@link -android.widget.TextView} and {@link android.widget.Button} are captured with {@link -android.app.Activity#findViewById(int)}. -Then an {@link android.view.View.OnClickListener} is created for the {@link android.widget.Button}, -so that when clicked, it will call {@link -android.app.Activity#showDialog(int)}, passing the unique integer ID for the time picker -dialog. Using {@link android.app.Activity#showDialog(int)} allows the {@link -android.app.Activity} to manage the life-cycle of the dialog and will call the {@link -android.app.Activity#onCreateDialog(int)} callback method to request the {@link android.app.Dialog} -that should be displayed (which you'll define later). After the on-click listener is set, a new -{@link java.util.Calendar} is created to get the current hour and minute. Finally, the -private updateDisplay() method is called in order to fill the {@link -android.widget.TextView} with the current time.

        -
      8. - -
      9. Add the updateDisplay() and pad() methods: -
        -// updates the time we display in the TextView
        -private void updateDisplay() {
        -    mTimeDisplay.setText(
        -        new StringBuilder()
        -                .append(pad(mHour)).append(":")
        -                .append(pad(mMinute)));
        -}
        -
        -private static String pad(int c) {
        -    if (c >= 10)
        -        return String.valueOf(c);
        -    else
        -        return "0" + String.valueOf(c);
        -}
        -
        -

        The updateDisplay() method uses the member fields for the time and inserts them in -the mTimeDisplay {@link android.widget.TextView}. The pad() method returns -the appropriate string representation of the hour or minute—it will prefix a zero to the -number if it's a single digit.

        -
      10. - -
      11. Add a class member for a {@link android.app.TimePickerDialog.OnTimeSetListener} that will be -called when the user sets a new time: -
        -// the callback received when the user "sets" the time in the dialog
        -private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        -    new TimePickerDialog.OnTimeSetListener() {
        -        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        -            mHour = hourOfDay;
        -            mMinute = minute;
        -            updateDisplay();
        -        }
        -    };
        -
        -

        When the user is done setting the time (clicks the "Set" button), the -onTimeSet() method is called and it updates the member fields with -the new time and updates the layout's {@link android.widget.TextView}.

        -
      12. - -
      13. Add the {@link android.app.Activity#onCreateDialog(int)} callback method: -
        -@Override
        -protected Dialog onCreateDialog(int id) {
        -    switch (id) {
        -    case TIME_DIALOG_ID:
        -        return new TimePickerDialog(this,
        -                mTimeSetListener, mHour, mMinute, false);
        -    }
        -    return null;
        -}
        -
        -

        This is an {@link android.app.Activity} callback that is passed the identifier you passed to -{@link android.app.Activity#showDialog(int)}, in the {@link android.widget.Button}'s on-click -listener. When the ID matches, this initializes the {@link android.app.TimePickerDialog} with the -member variables initialized at the end of onCreate() and the {@link -android.app.TimePickerDialog.OnTimeSetListener} created in the previous step.

        -
      14. - -
      15. Run the application.
      16. -
      -

      When you press the "Change the time" button, you should see the following:

      - - -

      References

      -
        -
      1. {@link android.widget.TimePicker}
      2. -
      3. {@link android.app.TimePickerDialog.OnTimeSetListener}
      4. -
      5. {@link android.widget.Button}
      6. -
      7. {@link android.widget.TextView}
      8. -
      9. {@link java.util.Calendar}
      10. -
      - diff --git a/docs/html/resources/tutorials/views/hello-webview.jd b/docs/html/resources/tutorials/views/hello-webview.jd deleted file mode 100644 index f6a6a7188b26..000000000000 --- a/docs/html/resources/tutorials/views/hello-webview.jd +++ /dev/null @@ -1,131 +0,0 @@ -page.title=Web View -parent.title=Hello, Views -parent.link=index.html -@jd:body - -

      {@link android.webkit.WebView} allows you to create your own window for viewing web pages (or even -develop a complete browser). In this tutorial, you'll create a simple {@link android.app.Activity} -that can view and navigate web pages.

      - -
        -
      1. Create a new project named HelloWebView.
      2. -
      3. Open the res/layout/main.xml file and insert the following: -
        -<?xml version="1.0" encoding="utf-8"?>
        -<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        -    android:id="@+id/webview"
        -    android:layout_width="fill_parent"
        -    android:layout_height="fill_parent"
        -/>
        -
        -
      4. - -
      5. Now open the HelloWebView.java file. - At the top of the class, declare a {@link android.webkit.WebView} object: -
        WebView mWebView;
        -

        Then use the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} - method:

        -
        -public void onCreate(Bundle savedInstanceState) {
        -    super.onCreate(savedInstanceState);
        -    setContentView(R.layout.main);
        -
        -    mWebView = (WebView) findViewById(R.id.webview);
        -    mWebView.getSettings().setJavaScriptEnabled(true);
        -    mWebView.loadUrl("http://www.google.com");
        -}
        -
        -

        This initializes the member {@link android.webkit.WebView} with the one from the - {@link android.app.Activity} layout; requests a {@link android.webkit.WebSettings} object with - {@link android.webkit.WebView#getSettings()}; and enables JavaScript for the {@link - android.webkit.WebView} with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean)}. - Finally, an initial web page is loaded with {@link - android.webkit.WebView#loadUrl(String)}.

        -
      6. - -
      7. Because this application needs access to the Internet, you need to add the appropriate - permissions to the Android manifest file. Open the AndroidManifest.xml file - and add the following as a child of the <manifest> element: - -
        <uses-permission android:name="android.permission.INTERNET" />
      8. - -
      9. While you're in the manifest, give some more space for web pages by removing the title - bar, with the "NoTitleBar" theme: -
        -<activity android:name=".HelloWebView" android:label="@string/app_name"
        -     android:theme="@android:style/Theme.NoTitleBar">
        -
        -
      10. - -
      11. Now run the application. -

        You now have a simplest web page viewer. - It's not quite a browser yet because as soon as you click a link, the default Android Browser - handles the Intent to view a web page, because this {@link android.app.Activity} isn't - technically enabled to do so. Instead of adding an intent filter to view web pages, you can - override the {@link android.webkit.WebViewClient} class and enable this {@link - android.app.Activity} to handle its own URL requests.

        -
      12. - -
      13. In the HelloAndroid Activity, add this nested class: -
        -private class HelloWebViewClient extends WebViewClient {
        -    @Override
        -    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        -        view.loadUrl(url);
        -        return true;
        -    }
        -}
        -
        -
      14. -
      15. Then towards the end of the {@link android.app.Activity#onCreate(Bundle)} method, set an - instance of the HelloWebViewClient as the {@link android.webkit.WebViewClient}: -
        mWebView.setWebViewClient(new HelloWebViewClient());
        - -

        This line can go anywhere following the initialization of the {@link - android.webkit.WebView} object.

        -

        This creates a {@link android.webkit.WebViewClient} that will load any URL selected from this - {@link android.webkit.WebView} into the same {@link android.webkit.WebView}. The - {@link android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String)} method is passed -the current {@link android.webkit.WebView} and the URL requested, so all it needs to do is load -the URL in the given view. Returning true says that the method has handled the URL -and the event should not propagate (in which case, an Intent would be created that's handled by -the Browser application).

        -

        If you run the application again, new pages will now load in this Activity. - However, you can't navigate back to previous pages. To do this, you need to handle the BACK - button on the device, so that it will return to the previous page, rather than exit the - application.

        -
      16. - -
      17. To handle the BACK button key press, add the following method inside the - HelloWebView Activity: -
         
        -@Override
        -public boolean onKeyDown(int keyCode, KeyEvent event) {
        -    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        -        mWebView.goBack();
        -        return true;
        -    }
        -    return super.onKeyDown(keyCode, event);
        -}
        -
        -

        This {@link android.app.Activity#onKeyDown(int,KeyEvent)} callback method will be called - anytime a button is pressed while in the Activity. The condition inside uses the {@link - android.view.KeyEvent} to check whether the key pressed is the BACK button and whether the - {@link android.webkit.WebView} is actually capable of navigating back (if it has a history). If - both are true, then the {@link android.webkit.WebView#goBack()} method is called, - which will navigate back one step in the {@link android.webkit.WebView} - history.Returning true indicates that the event has been handled. If this condition - is not met, then the event is sent back to the system.

        -
      18. -
      19. Run the application again. You'll now be able to follow links and navigate back through the -page history.
      20. -
      -

      When you open the application, it should look like this:

      - - -

      Resource

      -
        -
      • {@link android.webkit.WebView}
      • -
      • {@link android.webkit.WebViewClient}
      • -
      • {@link android.view.KeyEvent}
      • -
      diff --git a/docs/html/resources/tutorials/views/images/android.png b/docs/html/resources/tutorials/views/images/android.png deleted file mode 100755 index 39a1ac729394..000000000000 Binary files a/docs/html/resources/tutorials/views/images/android.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/android_focused.png b/docs/html/resources/tutorials/views/images/android_focused.png deleted file mode 100644 index f84d0fe4a5e4..000000000000 Binary files a/docs/html/resources/tutorials/views/images/android_focused.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/android_normal.png b/docs/html/resources/tutorials/views/images/android_normal.png deleted file mode 100644 index 94a708425300..000000000000 Binary files a/docs/html/resources/tutorials/views/images/android_normal.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/android_pressed.png b/docs/html/resources/tutorials/views/images/android_pressed.png deleted file mode 100644 index fe81ff9e279c..000000000000 Binary files a/docs/html/resources/tutorials/views/images/android_pressed.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/androidmarker.png b/docs/html/resources/tutorials/views/images/androidmarker.png deleted file mode 100755 index 8c43d4668218..000000000000 Binary files a/docs/html/resources/tutorials/views/images/androidmarker.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-autocomplete.png b/docs/html/resources/tutorials/views/images/hello-autocomplete.png deleted file mode 100644 index 0b3e6803bb1f..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-autocomplete.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-datepicker.png b/docs/html/resources/tutorials/views/images/hello-datepicker.png deleted file mode 100755 index 2075066bfdc1..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-datepicker.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-formstuff.png b/docs/html/resources/tutorials/views/images/hello-formstuff.png deleted file mode 100644 index 949319f7c2d4..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-formstuff.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-gallery.png b/docs/html/resources/tutorials/views/images/hello-gallery.png deleted file mode 100755 index 22d1eaf6d145..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-gallery.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-gridview.png b/docs/html/resources/tutorials/views/images/hello-gridview.png deleted file mode 100755 index 2def0df666a4..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-gridview.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-linearlayout.png b/docs/html/resources/tutorials/views/images/hello-linearlayout.png deleted file mode 100755 index dfef819ef9d1..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-linearlayout.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-listview.png b/docs/html/resources/tutorials/views/images/hello-listview.png deleted file mode 100644 index 165b1ac69725..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-listview.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-mapview.png b/docs/html/resources/tutorials/views/images/hello-mapview.png deleted file mode 100644 index 6bd97400c29b..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-mapview.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-relativelayout.png b/docs/html/resources/tutorials/views/images/hello-relativelayout.png deleted file mode 100755 index ec4d9d44b0c6..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-relativelayout.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-spinner.png b/docs/html/resources/tutorials/views/images/hello-spinner.png deleted file mode 100755 index 42e2a915cb47..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-spinner.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-tablelayout.png b/docs/html/resources/tutorials/views/images/hello-tablelayout.png deleted file mode 100755 index 3d80e7f8a55a..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-tablelayout.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-tabwidget.png b/docs/html/resources/tutorials/views/images/hello-tabwidget.png deleted file mode 100644 index 6580c5b067ff..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-tabwidget.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-timepicker.png b/docs/html/resources/tutorials/views/images/hello-timepicker.png deleted file mode 100755 index bd5a1eeadaae..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-timepicker.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/hello-webview.png b/docs/html/resources/tutorials/views/images/hello-webview.png deleted file mode 100644 index 248c6d4d1ff5..000000000000 Binary files a/docs/html/resources/tutorials/views/images/hello-webview.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/ic_tab_artists_grey.png b/docs/html/resources/tutorials/views/images/ic_tab_artists_grey.png deleted file mode 100644 index 9baa30eac584..000000000000 Binary files a/docs/html/resources/tutorials/views/images/ic_tab_artists_grey.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/images/ic_tab_artists_white.png b/docs/html/resources/tutorials/views/images/ic_tab_artists_white.png deleted file mode 100644 index 3b010d536ade..000000000000 Binary files a/docs/html/resources/tutorials/views/images/ic_tab_artists_white.png and /dev/null differ diff --git a/docs/html/resources/tutorials/views/index.jd b/docs/html/resources/tutorials/views/index.jd deleted file mode 100644 index bba833070958..000000000000 --- a/docs/html/resources/tutorials/views/index.jd +++ /dev/null @@ -1,121 +0,0 @@ -page.title=Hello, Views -parent.title=Tutorials -parent.link=../../browser.html?tag=tutorial -@jd:body - - - -

      This is a collection of "Hello World"-style tutorials designed -to get you started quickly with common Android layouts and widgets.

      - -

      A certain amount of knowledge is assumed for these tutorials. Before you start, -you should have completed the Hello, -World tutorial—it will teach you several things about basic -Android development. More specifically, you should know:

      -
        -
      • How to create an Android project and run it
      • -
      • The basic structure of an Android project (resource files, layout files, etc.)
      • -
      • The basic components of an {@link android.app.Activity}
      • -
      - -

      Note: In order to make these tutorials as simple as possible, -some code may not conform to best practices for coding Android applications. In particular, -hard-coded strings are used in places, when the better practice is to reference strings from a -res/values/strings.xml resource file.

      - -

      Tip: After you have pasted sample code into an Eclipse project, -press Ctrl (or Cmd) + Shift + O to import the required packages.

      - -

      Layouts

      - - - - - - - -
      -Grid View
      - -
      - - - -
      -List View
      - -
      - -

       

      - -

      Widgets & Other Views

      - - - - - - - -
      -Spinner
      - -
      - - - -
      -Gallery
      - -
      - - - -
      -Web View
      - -
      - - -

      -There are plenty more layouts and widgets available. See the {@link android.view.View} class -for more on View layouts, and the {@link android.widget widget package} -for more useful widgets. And for more raw code samples, visit the -Api -Demos.

      - diff --git a/docs/html/sdk/OLD_RELEASENOTES.jd b/docs/html/sdk/OLD_RELEASENOTES.jd index 77516818c047..6865db235c0b 100644 --- a/docs/html/sdk/OLD_RELEASENOTES.jd +++ b/docs/html/sdk/OLD_RELEASENOTES.jd @@ -173,9 +173,9 @@ specify which port the emulator should bind to for the console. <port> mus

      The SDK includes several new development tools, such as

        -
      • HierarchyViewer is a visual tool for inspecting and debugging your user interfaces and layout.
      • -
      • Draw 9-patch allows you to easily create a NinePatch graphic using a WYSIWYG editor.
      • -
      • The UI/Application Exerciser Monkey generates pseudo-random system and user events, for testing your application.
      • +
      • HierarchyViewer is a visual tool for inspecting and debugging your user interfaces and layout.
      • +
      • Draw 9-patch allows you to easily create a NinePatch graphic using a WYSIWYG editor.
      • +
      • The UI/Application Exerciser Monkey generates pseudo-random system and user events, for testing your application.

      Application Signing @@ -326,7 +326,7 @@ specify which port the emulator should bind to for the console. <port> mus

      traceview

        -
      • The traceview tool is now included in the SDK.
      • +
      • The traceview tool is now included in the SDK.

      Resolved Issues

      @@ -387,13 +387,13 @@ specify which port the emulator should bind to for the console. <port> mus
      • Now provides support for emulating inbound SMS messages. The ADT plugin and DDMS provide integrated access to this capability. For more information about how to emulate inbound SMS from the console, -see SMS Emulation.
      • +see SMS Emulation.

      Emulator

      • The default emulator skin has been changed to HVGA-P from QVGA-L. For information about emulator skins and how to load a specific skin when starting the emulator, see -Using Emulator Skins.
      • +Using Emulator Skins.

      Resolved Issues

      diff --git a/docs/html/sdk/RELEASENOTES.jd b/docs/html/sdk/RELEASENOTES.jd index 91eb57f48582..c7ece4230b1b 100644 --- a/docs/html/sdk/RELEASENOTES.jd +++ b/docs/html/sdk/RELEASENOTES.jd @@ -37,15 +37,15 @@ now available from the "SDK" tab, under "Downloadable SDK Components."

      To get started with the SDK, review the Quick Start summary on the Android SDK download page or read Installing the SDK for detailed +href="{@docRoot}sdk/installing/index.html">Installing the SDK for detailed installation instructions.

      @@ -64,7 +64,7 @@ changes include:

      skins.
    1. Android SDK and AVD Manager, a graphical UI to let you manage your SDK and AVD environments more easily. The tool lets you create and manage -your Android Virtual +your Android Virtual Devices and download new SDK packages (such as platform versions and add-ons) into your environment.
    2. Improved support for test packages in New Project Wizard
    3. @@ -72,7 +72,7 @@ add-ons) into your environment. capability that lets you display only the parts of the API that are actually available to your application, based on the android:minSdkVersion value the application declares in its manifest. For more information, see -Android API Levels +Android API Levels

      For details about the Android platforms included in the SDK — including @@ -109,7 +109,7 @@ Plugin (0.9.3 or higher).

      The new version of ADT is downloadable from the usual remote update site or is separately downloadable as a .zip archive. For instructions on how to download the plugin, please see ADT Plugin for Eclipse.

      +href="{@docRoot}tools/sdk/eclipse-adt.html">ADT Plugin for Eclipse.

      Android SDK and AVD Manager

      @@ -222,7 +222,7 @@ skins, including:

      density for each skin, to create any combination of resolution/density (WVGA with medium density, for instance). To do so, use the android tool command line to create a new AVD that uses a custom hardware configuration. See -Creating an +Creating an AVD for more information.

      Other Notes and Resolved Issues

      @@ -330,7 +330,7 @@ changes include:

      Android 1.5). The tools are updated to let you deploy your application on any platform in the SDK, which helps you ensure forward-compatibility and, if applicable, backward-compatibility. -
    4. Introduces Android +
    5. Introduces Android Virtual Devices — (AVD) configurations of options that you run in the emulator to better model actual devices. Each AVD gets its own dedicated storage area, making it much easier to work with multiple emulators @@ -352,7 +352,7 @@ Android project.
    6. For details about the Android platforms included in the SDK — including bug fixes, features, and API changes — please read the Android 1.5 version notes.

      +href="{@docRoot}about/versions/android-1.5.html">Android 1.5 version notes.

      Installation and Upgrade Notes

      @@ -407,7 +407,7 @@ that can run in the emulator. available to use.

      For more information about AVDs, see Creating and Managing Virtual Devices +href="{@docRoot}tools/devices/index.html">Creating and Managing Virtual Devices

      Other Notes

      @@ -491,7 +491,7 @@ as well as a few minor API changes from the 1.0 version.

      For details about the Android 1.1 system image included in the SDK — including bug fixes, features, and API changes — please read the Android 1.1 version notes.

      +href="{@docRoot}about/versions/android-1.1.html">Android 1.1 version notes.

      App Versioning for Android 1.1

      @@ -545,7 +545,7 @@ testing.

      Plugin for Eclipse is 0.8.0. If you are using a previous version of ADT, you should update to the latest version for use with this SDK. For information about how to update your ADT plugin, see -ADT Plugin for Eclipse.

      +ADT Plugin for Eclipse.

      Installation and Upgrade Notes

      @@ -585,7 +585,7 @@ these USB drivers that you can install, to let you develop on the device:

      The USB driver files are located in the <SDK>/usb_driver directory. For details and installation instructions, see Connecting Hardware Devices.

      +href="{@docRoot}tools/device.html#setting-up">Connecting Hardware Devices.

      Resolved Issues, Changes

      @@ -650,7 +650,7 @@ added.

      Development Tools (ADT) Plugin for Eclipse is 0.8.0. If you are using a previous version of ADT, you should update to the latest version for use with this SDK. For information about how to update your ADT plugin, see ADT Plugin for Eclipse.

      +href="{@docRoot}tools/sdk/eclipse-adt.html">ADT Plugin for Eclipse.

      Other Notes

      diff --git a/docs/html/sdk/adding-components.jd b/docs/html/sdk/adding-components.jd deleted file mode 100644 index 599b2a831f62..000000000000 --- a/docs/html/sdk/adding-components.jd +++ /dev/null @@ -1,209 +0,0 @@ -page.title=Adding SDK Packages -@jd:body - - -
      -
      -

      Quickview

      -
        -
      • Use the Android SDK Manager to - set up your SDK and keep it up-to-date.
      • -
      - -

      In this document

      -
        -
      1. Launching the Android SDK Manager -
      2. Installing SDK Packages -
      3. Updating SDK Packages -
      4. Package Dependencies
      5. -
      6. Adding New Sites
      7. -
      8. Troubleshooting
      9. -
      -
      -
      - -

      Adding and updating packages in your Android SDK is fast and easy. To add or -update the individual SDK packages that you need, use the Android SDK -Manager (included in the SDK Tools).

      - -

      It only takes a couple of clicks to install individual versions of the -Android platform, new development tools, new documentation, and SDK add-ons. The -new SDK packages are automatically installed into your existing SDK directory, -so you don't need to update your development environment to specify a new SDK -location.

      - -

      If you're setting up your Android SDK for the first time, -see Installing the SDK for information about -what packages to install.

      - -

      Note: If you develop in Eclipse, you might also need -to update your ADT plugin when you update your development tools. See the revisions listed in the -ADT Plugin for Eclipse document.

      - - -

      Figure 1. The Android SDK Manager's -Available Packages panel, which shows the SDK packages that are -available for you to download into your environment.

      -
    - -

    Launching the Android SDK Manager

    - -

    The Android SDK Manager is the tool that you use to install and -upgrade SDK packages in your development environment.

    - -

    You can launch the Android SDK Manager in one of the following ways.

    - -

    Launching from Eclipse/ADT

    - -

    If you are developing in Eclipse and have already installed the ADT Plugin, -follow these steps to access the Android SDK Manager tool:

    - -
      -
    1. Open Eclipse
    2. -
    3. Select Window > Android SDK -Manager.
    4. -
    - -

    Launching from the SDK Manager script (Windows only)

    - -

    For Windows only, the SDK includes a script that invokes the Android SDK Manager. To launch the -tool using the script, double-click {@code SDK -Manager.exe} at the root of the the SDK directory.

    - -

    Launching from a command line

    - -

    In all development environments, follow these steps to access the Android SDK Manager tool from -the command line:

    - -
      -
    1. Navigate to the <sdk>/tools/ directory.
    2. -
    3. Execute the {@code android} tool command with no options. -
      $ android
    4. -
    - - -

    Installing SDK Packages

    - -

    Caution: Before you install SDK packages, -we recommend that you disable any antivirus software that may be running on -your computer. There are cases in which antivirus software on Windows is known to interfere with the -installation process, so we suggest you disable your antivirus until installation is -complete.

    - -

    Follow these steps to install new SDK packages in your environment:

    - -
      -
    1. Launch the Android SDK Manager as described in the section above.
    2. -
    3. Select Available Packages in the left panel. - This will reveal all of the packages that are currently available for download - from the SDK repository.
    4. -
    5. Select the package(s) you'd like to install and click Install - Selected. (If you aren't sure which packages to select, read Recommended Packages.)
    6. -
    7. Verify and accept the packages you want (ensure each one is selected with a green -checkmark) and click Install. The packages will now be installed into -your existing Android SDK directories.
    8. -
    - -

    New platforms are automatically saved into the -<sdk>/platforms/ directory of your SDK; -new add-ons are saved in the <sdk>/add-ons/ -directory; samples are saved in the -<sdk>/samples/android-<level>/; -and new documentation is saved in the existing -<sdk>/docs/ directory (old docs are replaced).

    - - -

    Updating SDK Packages

    - -

    From time to time, new revisions of existing SDK packages are released and -made available to you through the SDK repository. In most cases, if you have those -packages installed in your environment, you will want -to download the new revisions as soon as possible.

    - -

    You can learn about the release of new revisions in two ways:

    - -
      -
    • You can watch for updates listed in the "SDK" tab of the Android Developers -site, in the "Downloadable SDK Packages" section.
    • -
    • You can watch for updates listed in the Available Packages -panel of the Android SDK Manager.
    • -
    - -

    When you see that a new revision is available, you can use the Android SDK Manager to quickly -download it to your environment. Follow the same -procedure as given in Installing SDK Packages, above. The new -package is installed in place of the old, but without impacting your -applications.

    - -

    Tip: -Use the "Display updates only" checkbox to show only the packages -you do not have.

    - - -

    SDK Package Dependencies

    - -

    In some cases, an SDK package may require a specific minimum revision of -another package or SDK tool. Where such dependencies exist, they are -documented in the revision notes for each package, available from the links in -the "Downloadable SDK packages" section at left.

    - -

    For example, there may be a dependency between the ADT Plugin for Eclipse and -the SDK Tools package. When you install the SDK Tools -package, you should also upgrade to the required version of ADT (if you -are developing in Eclipse). In this case, the major version number for your ADT plugin should -always match the revision number of your SDK Tools (for example, ADT 8.x requires SDK Tools r8). -

    - -

    Also make sure that, each time you install a new version of the Android platform, you have -the latest version of the SDK Platform-tools package. The SDK Platform-tools contain -tools that are backward compatible with all versions of the Android platform and are -often updated to support new features in the latest version of the Android platform.

    - -

    The development tools will notify you with debug warnings if there is dependency that you need to -address. The Android SDK Manager also enforces dependencies by requiring that you download any -packages that are needed by those you have selected.

    - - -

    Adding New Sites

    - -

    By default, Available Packages displays packages available from the -Android Repository and Third party Add-ons. You can add other sites that host -their own Android SDK add-ons, then download the SDK add-ons -from those sites.

    - -

    For example, a mobile carrier or device manufacturer might offer additional -API libraries that are supported by their own Android-powered devices. In order -to develop using their libraries, you must install their Android SDK add-on, if it's not already -available under Third party Add-ons.

    - -

    If a carrier or device manufacturer has hosted an SDK add-on repository file -on their web site, follow these steps to add their site to the Android SDK -Manager:

    - -
      -
    1. Select Available Packages in the left panel.
    2. -
    3. Click Add Add-on Site and enter the URL of the -{@code repository.xml} file. Click OK.
    4. -
    -

    Any SDK packages available from the site will now be listed under a new item named -User Add-ons.

    - - -

    Troubleshooting

    - -

    Problems connecting to the SDK repository

    - -

    If you are using the Android SDK Manager to download packages and are encountering -connection problems, try connecting over http, rather than https. To switch the -protocol used by the Android SDK Manager, follow these steps:

    - -
      -
    1. With the Android SDK Manager window open, select "Settings" in the - left pane.
    2. -
    3. On the right, in the "Misc" section, check the checkbox labeled "Force - https://... sources to be fetched using http://..."
    4. -
    5. Click Save & Apply.
    6. -
    - - diff --git a/docs/html/sdk/adt-notes.jd b/docs/html/sdk/adt-notes.jd deleted file mode 100644 index 291b543f13fb..000000000000 --- a/docs/html/sdk/adt-notes.jd +++ /dev/null @@ -1,5 +0,0 @@ -page.title=ADT Plugin for Eclipse -sdk.redirect=true -sdk.redirect.path=eclipse-adt.html - -@jd:body diff --git a/docs/html/sdk/adt_download.html b/docs/html/sdk/adt_download.html deleted file mode 100644 index 5ba2ef5be745..000000000000 --- a/docs/html/sdk/adt_download.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Redirecting... - - -

    You should be redirected. Please click here.

    - - \ No newline at end of file diff --git a/docs/html/sdk/android-1.1.jd b/docs/html/sdk/android-1.1.jd deleted file mode 100644 index b61f18615c75..000000000000 --- a/docs/html/sdk/android-1.1.jd +++ /dev/null @@ -1,246 +0,0 @@ -page.title=Android 1.1 Version Notes -sdk.version=1.1_r1 -sys.date=February 2009 -@jd:body - -

    -Date: February 2009
    -API Level: 2

    - - -

    This document provides version notes for the Android 1.1 system image included in the SDK. - -

    - -

    Overview

    - -

    The Android 1.1 system image delivered in the SDK is the development -counterpart to the Android 1.1 production system image, deployable to -Android-powered handsets starting in February 2009.

    - -

    The Android 1.1 system image delivers an updated version of the framework -API. As with the Android 1.0 API, the Android 1.1 API -is assigned an integer identifier — 2 — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    Applications indicate the lowest system API Level that they are compatible with by adding -a value to the android:minSdkVersion attribute. -The value of the attribute is an integer corresponding to an API Level -identifier. Prior to installing an application, the system checks the value of -android:minSdkVersion and allows the install only -if the referenced integer is less than or equal to the API Level integer stored -in the system itself.

    - -

    If you use the Android 1.1 system image to build an application -compatible with Android-powered devices running the Android 1.1 -platform, you must set the -android:minSdkVersion attribute to "2" in order to specify that your application -is compatible only with devices using the Android 1.1 (or greater) system image. -

    - -

    Specifically, you specify the android:minSdkVersion -attribute in a <uses-sdk> element as a child of -<manifest> in the manifest file. When set, the -attribute looks like this:

    - -
    <manifest>
    -  ...
    -  <uses-sdk android:minSdkVersion="2" />
    -  ...
    -</manifest>
    -
    - -

    By setting android:minSdkVersion in this way, you ensure -that users will only be able to install your application if their -devices are running the Android 1.1 platform. In turn, this ensures that -your application will function properly on their devices, especially if -it uses APIs introduced in Android 1.1.

    - -

    If your application uses APIs introduced in Android 1.1 but does not -declare <uses-sdk android:minSdkVersion="2" />, then it will -run properly on Android 1.1 devices but not on Android 1.0 -devices. In the latter case, the application will crash at runtime when -it tries to use the Android 1.1 APIs.

    - -

    If your application does not use any new APIs introduced in Android -1.1, you can indicate Android 1.0 compatibility by removing -android:minSdkVersion or setting the attribute to "1". However, -before publishing your application, you must make sure to compile your -application against the Android 1.0 system image (available in the -Android 1.0 SDK), to ensure that it builds and functions properly for -Android 1.0 devices. You should test the application against system -images corresponding to the API Levels that the application is designed -to be compatible with.

    - -

    If you are sure your application is not using Android 1.1 APIs and -has no need to use them, you might find it easier to keep working in the -Android 1.0 SDK, rather than migrating to the Android 1.1 SDK and having -to do additional testing.

    - - -

    External Libraries

    - -

    The system image includes these external libraries, which you can -access from your application by adding a -<uses-library>.

    -
      -
    • com.google.android.maps — gives your -application access to Google Maps data. Note that, to use Google Maps -data, a Maps API Key is required.
    • -
    - -

    Device Compatibility

    - -

    The Android 1.1 system image was tested for compatability with the -Android-powered devices listed below:

    -
      -
    • T-Mobile G1
    • -
    - -

    Built-in Applications

    - -

    The system image includes these built-in applications:

    -
      -
    • Alarm Clock
    • -
    • API Demos
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Contacts
    • -
    • Dev Tools
    • -
    • Dialer
    • -
    • Email
    • -
    • Maps (and StreetView)
    • -
    • Messaging
    • -
    • Music
    • -
    • Pictures
    • -
    • Settings
    • -
    - -

    UI Localizations

    - -

    The system image provides localized UI strings for the languages -listed below.

    -
      -
    • English, US (en_US)
    • -
    • German (de)
    • -
    - -

    Localized UI strings match the locales that are displayable in -the emulator, accessible through the device Settings application.

    - -

    Resolved Issues

    -
      -
    • AlarmClock alert now plays audio/vibe directly, rather than through -AlarmManager. AlarmClock alert starts playing audio/vibe in its -IntentReceiver, rather than on activity start. These changes should -prevent alarms from being blocked by modal dialogs.
    • -
    • Fixes to device sleep.
    • -
    • Single tap no longer opens the in-call dialpad; users now need to -touch and drag it.
    • -
    • Fixes a bug causing approximately 1 in 25 outbound messages to -freeze up the IMAP connection (to a Gmail based server) when transferred -to the Sent folder.
    • -
    • Removes automatic account setup entries that were broken or not -testable. Adds minor fixes to a few of the remaining entries. Makes -improvements to warning dialogs used for a few special cases.
    • -
    • Changes default mail checking interval to every 15 minutes (instead -of defaulting to "never").
    • -
    • Fixes password-quoting bugs in IMAP, so that users can include -special characters in passwords (e.g. spaces).
    • -
    • Fixes various errors in auto and manual account setup
    • -
    • Improves reporting for various connection errors, making it easier -for the user to diagnose failed account setups.
    • -
    • Fixes new-mail notifications for POP3 accounts.
    • -
    • Ensures proper auto-checking of accounts marked as "never -check".
    • -
    • Now displays date and time using user preference (e.g. 24 hr vs. -AM/PM).
    • -
    • Now shows cc: in message view.
    • -
    • Improves recovery from POP3 connection failures.
    • -
    • POP3 parser rules loosened, so the application can work with -non-compliant email servers.
    • -
    - -

    New Features

    - -
      -
    • Maps: Adds details and reviews when a user does a search on Maps and -clicks on a business to view its details.
    • -
    • Dialer: In-call screen timeout default is now longer when using the -speakerphone.
    • -
    • Dialer: Adds a "Show dialpad" / "Hide dialpad" item to the in-call -menu, to make it easier to discover the DTMF dialpad.
    • -
    • Adds support for saving attachments from MMS
    • -
    • Adds support for marquee in layouts.
    • -
    - -

    API Changes

    - -

    Overview

    - - - -

    API Change Details

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Module or FeatureChange Description
    Annotations for test systems
    Added {@link android.test.suitebuilder.annotation.LargeTest LargeTest} annotation.
    Added {@link android.test.suitebuilder.annotation.MediumTest MediumTest} annotation.
    Added {@link android.test.suitebuilder.annotation.SmallTest SmallTest} annotation.
    Allow a process to easily know its UID.
    Added public method {@link android.os.Process#myUid} to class {@link android.os.Process android.os.Process}
    Padding in views
    Added public method {@link android.view.View#getBottomPaddingOffset} to class {@link android.view.View android.view.View}.
    Added public method {@link android.view.View#getLeftPaddingOffset} to class {@link android.view.View android.view.View}.
    Added public method {@link android.view.View#getRightPaddingOffset} to class {@link android.view.View android.view.View}.
    Added public method {@link android.view.View#getTopPaddingOffset} to class {@link android.view.View android.view.View}.
    Added public method {@link android.view.View#isPaddingOffsetRequired} to class {@link android.view.View android.view.View}.
    Marquee support
    Added public method {@link android.widget.TextView#setMarqueeRepeatLimit} to class {@link android.widget.TextView}
    Added public field {@link android.R.attr#marqueeRepeatLimit android.R.attr.marqueeRepeatLimit}
    New permissions
    Added public field {@link android.Manifest.permission#BROADCAST_SMS android.Manifest.permission.BROADCAST_SMS}
    Added public field {@link android.Manifest.permission#BROADCAST_WAP_PUSH android.Manifest.permission.BROADCAST_WAP_PUSH}
    API cleanup
    Removed protected constructor java.net.ServerSocket.ServerSocket(java.net.SocketImpl).
    - - - - - - diff --git a/docs/html/sdk/android-1.5-highlights.jd b/docs/html/sdk/android-1.5-highlights.jd deleted file mode 100644 index ff64e8c28cf9..000000000000 --- a/docs/html/sdk/android-1.5-highlights.jd +++ /dev/null @@ -1,208 +0,0 @@ -page.title=Android 1.5 Platform Highlights -@jd:body - -

    -April 2009 -

    - - -

    The Android 1.5 platform introduces many new features for users and developers. -The list below provides an overview of the changes.

    - - - -

    User Interface Refinements

    - - -

    Performance Improvements

    - - - -

    New Features

    - - - -

    New APIs and Manifest Elements

    - - diff --git a/docs/html/sdk/android-1.5.jd b/docs/html/sdk/android-1.5.jd deleted file mode 100644 index 9ed798c2a8f8..000000000000 --- a/docs/html/sdk/android-1.5.jd +++ /dev/null @@ -1,375 +0,0 @@ -page.title=Android 1.5 Platform -sdk.platform.version=1.5 -sdk.platform.apiLevel=3 -sdk.platform.majorMinor=major - -@jd:body - - - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release -deployable to Android-powered handsets starting in May 2009. -The release includes new features for users and developers, as well as changes -in the Android framework API.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes a -fully compliant Android library and system image, as well as a set of emulator -skins, sample applications, and more. The downloadable platform is fully -compliant and includes no external libraries.

    - -

    To get started developing or testing against the Android -{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to -download the platform into your Android 1.6 or later SDK. For more information, -see Adding SDK -Components.

    - - -

    Platform Highlights

    - -

    For a list of new user features and platform highlights, see the Android -{@sdkPlatformVersion} Platform Highlights document.

    - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - - -
    - - - Android 1.5, Revision 4 (May 2010) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r6 or higher.

    -
    - -
    Tools:
    -
    -
      -
    • Adds support for library projects in the Ant build system.
    • -
    • Fixes test project build in the Ant build system.
    • -
    -
    - -
    -
    -
    - -
    - - - Android 1.5, Revision 3 (July 2009) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r3 or higher.

    -
    -
    -
    -
    - -
    - - - Android 1.5, Revision 2 (May 2009) -
    -

    Not available as an SDK component — please use Android 1.5, r3 instead.

    -
    -
    - -
    - - - Android 1.5, Revision 1 (April 2009) -
    -

    Not available as an SDK component — please use Android 1.5, r3 instead.

    -
    -
    - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your -application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the -android:minSdkVersion attributes of the <uses-sdk> -element in your application's manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Framework API Changes

    - -

    The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.

    - -

    UI framework

    - - -

    AppWidget framework

    - - -

    Media framework

    - - -

    Input Method framework

    - - -

    Application-defined hardware requirements

    - -

    Applications can now use a new element in their manifest files, <uses-configuration> - to indicate to the Android system what hardware features -they require in order to function properly. For example, an application might -use the element to specify that it requires a physical keyboard or a particular -navigation device, such as a trackball. Prior to installing the application, the -Android system checks the attributes defined for the -<uses-configuration> element and allows the installation to -continue only if the required hardware is present.

    - -

    Speech recognition framework

    - - -

    Miscellaneous API additions

    - - - -

    API differences report

    - -

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to -the previous version, see the API -Differences Report.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Alarm Clock
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camcorder
    • -
    • Camera
    • -
    • Contacts
    • -
    • Custom Locale (developer app)
    • -
    • Dev Tools (developer app)
    • -
    -
    -
      -
    • Dialer
    • -
    • Email
    • -
    • Gallery
    • -
    • IME for Japanese text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    -
    - -

    Locales

    - -

    The system image included in the downloadable platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region -locale descriptor).

    - - - - - - -
    -
      -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    • Czech (cs_CZ)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • English, US (en_US)
    • -
    • English, Britain (en_GB)
    • -
    • English, Canada (en_CA)
    • -
    • English, Australia (en_AU)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • French, France (fr_FR)
    • -
    • French, Belgium (fr_BE)
    • -
    -
    -
  • French, Canada (fr_CA)
  • -
  • French, Switzerland (fr_CH)
  • -
  • German, Germany (de_DE)
  • -
  • German, Austria (de_AT)
  • -
  • German, Switzerland (de_CH)
  • -
  • German, Liechtenstein (de_LI)
  • -
  • Italian, Italy (it_IT)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Polish (pl_PL)
  • -
  • Russian (ru_RU)
  • -
  • Spanish (es_ES)
  • -
    - -

    Localized UI strings match the locales that are accessible -through Settings.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

    - - - -

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    diff --git a/docs/html/sdk/android-1.6-highlights.jd b/docs/html/sdk/android-1.6-highlights.jd deleted file mode 100644 index f0a50fb090b0..000000000000 --- a/docs/html/sdk/android-1.6-highlights.jd +++ /dev/null @@ -1,213 +0,0 @@ -page.title=Android 1.6 Platform Highlights -sdk.date=September 2009 - -@jd:body - - - - -
    - - - - - -
    - - -

    The Android 1.6 platform introduces new features for users and developers. -This page provides an overview of some new features and technologies.

    - - - - - -

    New User Features

    - - - -
    -
    -Quick Search Box -
    - -
    -
    -New Camera/Camcorder UI -
    - -
    -
    -Battery Usage Indicator -
    - - -

    Quick Search Box for Android

    - -

    Android 1.6 includes a redesigned search framework that provides a quick, -effective, and consistent way for users to search across multiple sources—such as -browser bookmarks & history, contacts, and the web—directly from -the home screen.

    - -

    The system constantly learns which search results are more relevant based on what is -clicked. So popular contacts or apps that have previously been picked will bubble up to -the top when a user types the first few letters of a relevant query.

    - -

    The search framework also provides developers a way to easily expose relevant -content from their applications in Quick Search Box.

    - -

    Camera, Camcorder, and Gallery

    - -

    An updated user interface provides an integrated camera, camcorder, and gallery experience. -Users can quickly toggle between still and video capture modes. Additionally, the gallery -enables users to select multiple photos for deletion.

    - -

    Android 1.6 also provides a much faster camera experience. -Compared to the previous release, launching the camera is now 39% faster, -and there is a 28% improvement in the time from completing one shot to the next.

    - - -

    VPN, 802.1x

    - -

    A new Virtual Private Network (VPN) control panel in Settings allows users -to configure and connect to the following types of VPNs:

    - - - - -

    Battery usage indicator

    - -

    A new battery usage screen lets users see which apps and services are consuming -battery power. If the user determines that a particular service or application is -using too much power, they can take action to save the battery by -adjusting settings, stopping the application, or uninstalling the application.

    - - -

    Accessibility

    - -

    Users will be able to download new accessibility services built -on the new accessibility framework and enable them in Settings.

    - - - - -

    Google Play Updates

    - -
    -
    -New Google Play UI -
    - -

    For devices with Google Play, the latest version improves the overall user experience and makes -it easier for users to discover great apps and games from developers.

    - - - - - - -

    New Platform Technologies

    - -

    Expanded Search Framework

    - -

    The Android search framework has been redesigned and expanded to provide -third-party applications the opportunity to surface -content from their applications in Quick Search Box, the global search tool. -To do this, developers will need to make their app "searchable" and provide -suggestions in response to user queries. -To enable application search suggestions, users simply select each application from which -they'd like to receive suggestions, under Searchable items in the Search settings.

    - - -

    Text-to-speech engine

    - -

    Android 1.6 features a multi-lingual speech synthesis engine called Pico. -It allows any Android application to "speak" a string of text with an accent that matches the language. -The engine supports the following languages: English (American and British accents), French, -Italian, German and Spanish. If you're using a T-Mobile G1 or Dream device, you'll need to download the -SpeechSynthesis Data Installer from Google Play, which includes the "voices" needed by the -text-to-speech engine.

    - - -

    Gestures

    - -

    A new gestures framework provides application developers with a framework for creating, storing, -loading, and recognizing gestures and associating them with specific actions.

    - -

    Developers can use the new GestureBuilder tool included in the Android 1.6 SDK to generate libraries -of gestures to include with their application.

    - - -

    Accessibility

    - -

    Android 1.6 provides a new accessibility framework. -With this framework, developers can create accessibility plugins that respond to user input, -such as making a sound when a new window is shown, vibrating when navigating to the top of -a list, and providing spoken feedback.

    - - -

    Expanded support for screen densities and resolutions

    - -

    Android 1.6 adds screen support that enables applications to be rendered properly on different -display resolutions and densities. Developers can also specify the types of screens supported by their -application.

    - - -

    Telephony support for CDMA

    - -

    Android 1.6 includes support for CDMA in the telephony stack.

    - - -

    New version of OpenCore

    - -

    Android 1.6 includes the updated OpenCore 2 media engine, which has:

    - - - -

    2.6.29 Linux kernel

    - -

    Android 1.6 upgrades the Linux kernel from 2.6.27 to 2.6.29.

    - - -

    New Framework APIs

    - -

    For a detailed overview of new APIs, see the -Version Notes. -For a complete report of all API changes, see the -API Differences Report. diff --git a/docs/html/sdk/android-1.6.jd b/docs/html/sdk/android-1.6.jd deleted file mode 100644 index a01a5f69643e..000000000000 --- a/docs/html/sdk/android-1.6.jd +++ /dev/null @@ -1,505 +0,0 @@ -page.title=Android 1.6 Platform -sdk.platform.version=1.6 -sdk.platform.apiLevel=4 -sdk.platform.majorMinor=minor - -@jd:body - -

    - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release -deployable to Android-powered handsets since October 2009. -The platform includes new features for users and developers, as well as changes -in the Android framework API.

    - -

    For developers, a new release of the Android {@sdkPlatformVersion} platform -is available as a downloadable component for the Android SDK. The platform -— Android 1.6 r2 — includes a fully compliant Android library and -system image, as well as a set of emulator skins, sample applications, and minor -development updates. The downloadable platform is fully compliant (API Level 4) -and includes no external libraries.

    - -

    To get started developing or testing against the Android -{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to -download the latest Android 1.6 platform into your Android 1.6 or later SDK. For -more information, see Adding SDK -Components.

    - - -

    Platform Highlights

    - -

    For a list of new user features and platform highlights, see the Android -{@sdkPlatformVersion} Platform Highlights document.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - - -
    - - - Android 1.6, Revision 3 (May 2010) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r6 or higher.

    -
    -
    Tools:
    -
    -
      -
    • Adds support for library projects in the Ant build system.
    • -
    -
    -
    -
    -
    - -
    - - - Android 1.6, Revision 2 (December 2009) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r4 or higher.

    -
    - -
    API related:
    -
    -
      -
    • Properly exposes CDMA-related constants in android.telephony.TelephonyManager: DATA_ACTIVITY_DORMANT, -PHONE_TYPE_CDMA, NETWORK_TYPE_CDMA, -NETWORK_TYPE_EVDO_0, NETWORK_TYPE_EVDO_A, and -NETWORK_TYPE_1xRTT.
    • -
    -
    -
    System image:
    -
    -
      -
    • Fixes bug so that Bitmap's density is now propagated through Parcelable.
    • -
    • Fixes NinePatchDrawable to properly scale its reported padding for compatibility mode.
    • -
    • Fixes TextView to properly compute styled font metrics based on the screen density.
    • -
    • Updates kernel to 2.6.29, to match kernel on commercially -available Android-powered devices.
    • -
    -
    -
    Tools:
    -
    -
      -
    • Adds new Ant build system with support for Emma instrumentation projects -(code coverage).
    • -
    • Fixes emulator skins to properly emulate d-pad in landscape mode.
    • -
    • Fixes density rendering in the layout editor in ADT.
    • -
    -
    -
    -
    -
    - -
    - - - Android 1.6, Revision 1 (September 2009) -
    -
    -
    Dependencies
    -
    -

    Requires SDK Tools r3 or higher.

    -
    -
    -
    -
    - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your -application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the -android:minSdkVersion attributes of the <uses-sdk> -element in your application's manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Framework API Changes

    - -

    The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.

    - -

    UI framework

    - - -

    Search framework

    - - -

    Accessibility framework

    - - -

    Gesture input

    - - -

    Text-to-speech

    - - -

    Graphics

    - - -

    Telephony

    - - -

    Utilities

    - - -

    Android Manifest elements

    - - - -

    New permissions

    - - - - -

    API differences report

    - -

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to -the previous version, see the API -Differences Report.

    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Alarm Clock
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camcorder
    • -
    • Camera
    • -
    • Contacts
    • -
    • Custom Locale (developer app)
    • -
    • Dev Tools (developer app)
    • -
    • Dialer
    • -
    -
    -
      -
    • Email
    • -
    • Gallery
    • -
    • Gestures Builder
    • -
    • IME for Japanese text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    -
    - -

    Locales

    - -

    The system image included in the downloadable platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region -locale descriptor).

    - - - - - - -
    -
      -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    • Czech (cs_CZ)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • English, US (en_US)
    • -
    • English, Britain (en_GB)
    • -
    • English, Canada (en_CA)
    • -
    • English, Australia (en_AU)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • French, France (fr_FR)
    • -
    • French, Belgium (fr_BE)
    • -
    -
    -
  • French, Canada (fr_CA)
  • -
  • French, Switzerland (fr_CH)
  • -
  • German, Germany (de_DE)
  • -
  • German, Austria (de_AT)
  • -
  • German, Switzerland (de_CH)
  • -
  • German, Liechtenstein (de_LI)
  • -
  • Italian, Italy (it_IT)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Polish (pl_PL)
  • -
  • Russian (ru_RU)
  • -
  • Spanish (es_ES)
  • -
    - -

    Localized UI strings match the locales that are accessible -through Settings.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can -use for modeling your application in different screen sizes and resolutions. -The emulator skins are:

    - - - -

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    diff --git a/docs/html/sdk/android-2.0-highlights.jd b/docs/html/sdk/android-2.0-highlights.jd deleted file mode 100644 index d4d13fcc78a7..000000000000 --- a/docs/html/sdk/android-2.0-highlights.jd +++ /dev/null @@ -1,201 +0,0 @@ -page.title=Android 2.0 Platform Highlights -sdk.date=October 2009 - -@jd:body - - - - -
    - - - - - -
    - - -

    The Android 2.0 platform introduces many new and exciting features for -users and developers. This document provides a glimpse at some of the new features -and technologies in Android 2.0.

    - - - - - -

    New User Features

    - - - -
    -
    - Quick Contact for Android -
    - -
    -
    - Multiple Accounts -
    - -
    -
    - Messaging Search -
    - -
    -
    - Email Combined Inbox -
    - -
    -
    - Camera Modes -
    - - - -

    Contacts and accounts

    - - - - - - -

    Email

    - - - - -

    Messaging

    - - - - -

    Camera

    - - - -

    Android virtual keyboard

    - - - - -

    Browser

    - - - - -

    Calendar

    - - - -

    New Platform Technologies

    - -

    Media Framework

    - -

    Revamped graphics architecture for improved performance that enables better -hardware acceleration.

    - - -

    Bluetooth

    - - - - -

    New Framework APIs

    - -

    Android 2.0 includes several new developer APIs. -For an overview of new APIs, see the -Android 2.0 version notes.

    - -

    For a complete report of all API changes, see the -API Differences Report.

    - - - diff --git a/docs/html/sdk/android-2.0.1.jd b/docs/html/sdk/android-2.0.1.jd deleted file mode 100644 index 0c8afb61fb8f..000000000000 --- a/docs/html/sdk/android-2.0.1.jd +++ /dev/null @@ -1,361 +0,0 @@ -page.title=Android 2.0.1, Release 1 -sdk.platform.version=2.0.1 -sdk.platform.apiLevel=6 -sdk.platform.majorMinor=minor - -@jd:body - - - -

    - -API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release -deployable to Android-powered handsets starting in December 2009. -This release includes minor API -changes, bug fixes and framework behavioral changes. For information on changes -and fixes, see the Framework API section.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes a -fully compliant Android library and system image, as well as a set of emulator -skins, sample applications, and more. The downloadable platform -includes no external libraries.

    - -

    To get started developing or testing against the Android -{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to -download the platform into your Android 1.6 or later SDK. For more information, -see Adding SDK -Components.

    - - -

    Platform Highlights

    - -

    For a list of new user features and platform highlights, see the Android -2.0 Platform Highlights document.

    - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - - -
    - - - Android 2.0.1, Revision 1 (December 2009) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r4 or higher.

    -
    -
    -
    -
    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Alarm Clock
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camcorder
    • -
    • Camera
    • -
    • Contacts
    • -
    • Custom Locale (developer app)
    • -
    • Dev Tools (developer app)
    • -
    • Dialer
    • -
    -
    -
      -
    • Email
    • -
    • Gallery
    • -
    • Gestures Builder
    • -
    • IME for Japanese text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    -
    - -

    New with 2.0.1 The Dev Tools app now -includes a "Sync Tester" application to provide quick and easy testing of -third-party sync adapters.

    - -

    Locales

    - -

    The system image included in the downloadable platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    • Czech (cs_CZ)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • English, US (en_US)
    • -
    • English, Britain (en_GB)
    • -
    • English, Canada (en_CA)
    • -
    • English, Australia (en_AU)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • French, France (fr_FR)
    • -
    • French, Belgium (fr_BE)
    • -
    -
    -
  • French, Canada (fr_CA)
  • -
  • French, Switzerland (fr_CH)
  • -
  • German, Germany (de_DE)
  • -
  • German, Austria (de_AT)
  • -
  • German, Switzerland (de_CH)
  • -
  • German, Liechtenstein (de_LI)
  • -
  • Italian, Italy (it_IT)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Polish (pl_PL)
  • -
  • Russian (ru_RU)
  • -
  • Spanish (es_ES)
  • -
    - -

    Localized UI strings match the locales that are accessible -through Settings.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

    - - - -

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    - -

    Developer Features

    - -

    The sections below provide information about new developer features offered by the downloadable Android 2.0 platform component.

    - -

    Ant Support

    - - - -

    Framework API

    - -

    The sections below provide information about changes made to the application -framework API provided by the Android {@sdkPlatformVersion} platform. Note, -however, that Android 2.0.1 is a minor release to Android 2.0, so for more -information about the changes made to in Android 2.0, please refer to the -Android 2.0 version notes.

    - - -

    API level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of the framework -API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — {@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to -set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk> -element in your application's manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    API changes summary

    - -

    The following is a summary of changes to the framework APIs.

    - - - -

    Behavior changes

    - -

    The following is a summary of changes that affect the behavior of some -framework APIs but do not add or remove API functionality.

    - -

    Bluetooth

    - -

    Changes to the values returned by {@link -android.bluetooth.BluetoothAdapter#ACTION_REQUEST_ENABLE} and -{@link android.bluetooth.BluetoothAdapter#ACTION_REQUEST_DISCOVERABLE}:

    - - - -

    Contacts

    - -

    The {@link android.content.Intent#ACTION_INSERT} Intent now returns {@link -android.app.Activity#RESULT_CANCELED} in cases where the contact was not -persisted (for example, if the save was trimmed to a no-op).

    - - -

    Bug fixes

    - -

    The following is a summary of bug fixes that affect some framework APIs.

    - -

    Resources

    - -

    The framework now correctly selects application resources in project -folders that use the API Level qualifier. For example, {@code drawable-v4/} is a -folder of drawable resources for API Level 4 (or higher) devices. This version -matching did not work properly and has been fixed.

    - -

    Contacts

    - -

    The {@link android.content.Intent#ACTION_INSERT} Intent now returns the -appropriate kind of URI when the request is made using the (now -deprecated) {@link android.provider.Contacts} APIs.

    - -

    Other Framework fixes

    - - - - -

    API differences report

    - -

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to -API Level 5, see the API -Differences Report. There are very few API changes in API Level 6, -so you might also be interested in reviewing the API -differences between 4 and 5.

    - diff --git a/docs/html/sdk/android-2.0.jd b/docs/html/sdk/android-2.0.jd deleted file mode 100644 index 2c319236297b..000000000000 --- a/docs/html/sdk/android-2.0.jd +++ /dev/null @@ -1,384 +0,0 @@ -page.title=Android 2.0, Release 1 -sdk.platform.version=2.0 -sdk.platform.apiLevel=5 -sdk.platform.majorMinor=major - -@jd:body - - - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release -deployable to Android-powered handsets starting in November 2009. -The release includes new features for users and developers, as well as changes -in the Android framework API.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes a -fully compliant Android library and system image, as well as a set of emulator -skins, sample applications, and more. The downloadable platform is fully -compliant and includes no external libraries.

    - -

    To get started developing or testing against the Android -{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to -download the platform into your SDK. For more information, -see Adding SDK -Components.

    - - -

    Platform Highlights

    - -

    For a list of new user features and platform highlights, see the Android -{@sdkPlatformVersion} Platform Highlights document.

    - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - - -
    - - - Android 2.0, Revision 1 (October 2009) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r3 or higher.

    -
    -
    -
    -
    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Alarm Clock
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camcorder
    • -
    • Camera
    • -
    • Contacts
    • -
    • Custom Locale (developer app)
    • -
    • Dev Tools (developer app)
    • -
    • Dialer
    • -
    -
    -
      -
    • Email
    • -
    • Gallery
    • -
    • Gestures Builder
    • -
    • IME for Japanese text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    -
    - -

    Locales

    - -

    The system image included in the downloadable platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    • Czech (cs_CZ)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • English, US (en_US)
    • -
    • English, Britain (en_GB)
    • -
    • English, Canada (en_CA)
    • -
    • English, Australia (en_AU)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • French, France (fr_FR)
    • -
    • French, Belgium (fr_BE)
    • -
    -
    -
  • French, Canada (fr_CA)
  • -
  • French, Switzerland (fr_CH)
  • -
  • German, Germany (de_DE)
  • -
  • German, Austria (de_AT)
  • -
  • German, Switzerland (de_CH)
  • -
  • German, Liechtenstein (de_LI)
  • -
  • Italian, Italy (it_IT)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Polish (pl_PL)
  • -
  • Russian (ru_RU)
  • -
  • Spanish (es_ES)
  • -
    - -

    Localized UI strings match the locales that are accessible -through Settings.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use for modeling your application in different screen sizes and resolutions. The emulator skins are:

    - - - -

    For more information about how to develop an application that displays and functions properly on all Android-powered devices, see Supporting Multiple Screens.

    - -

    Developer Features

    - -

    The sections below provide information about new developer features offered by the downloadable Android 2.0 platform component.

    - -

    Ant Support

    - - - -

    Framework API

    - -

    The sections below provide information about the application framework API provided by the Android {@sdkPlatformVersion} platform.

    - - -

    API level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of the framework -API. As with previous versions, the Android {@sdkPlatformVersion} API -is assigned an integer identifier — {@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need to -set the proper value, "{@sdkPlatformApiLevel}", in the attributes of the <uses-sdk> -element in your application's manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    API changes summary

    - -

    Bluetooth

    - - -

    Sync adapters

    - - -

    Account Manager

    - - -

    Contacts

    - - -

    WebView

    - - -

    Camera

    - - -

    Media

    - - -

    Other Framework

    - - -

    Key events executed on key-up

    - -

    Android 2.0 is designed to run on devices that use virtual keys for HOME, -MENU, BACK, and SEARCH, rather than physical keys. To support the best user -experience on those devices, the Android platform now executes these buttons at -key-up, for a key-down/key-up pair, rather than key-down. This helps prevent -accidental button events and lets the user press the button area and then drag -out of it without generating an event.

    - -

    This change in behavior should only affect your application if it is -intercepting button events and taking an action on key-down, rather than on -key-up. Especially if your application is intercepting the BACK key, you should -make sure that your application is handling the key events properly.

    - -

    In general, intercepting the BACK key in an application is not recommended, -however, if your application is doing so and it invokes some action on -key-down, rather than key-up, you should modify your code.

    - -

    If your application will use APIs introduced in Android 2.0 (API Level 5), -you can take advantage of new APIs for managing key-event pairs:

    - - - -

    If you want to update a legacy application so that its handling of the BACK -key works properly for both Android 2.0 and older platform versions, you -can use an approach similar to that shown above. Your code can catch the -target button event on key-down, set a flag to track the key event, and -then also catch the event on key-up, executing the desired action if the tracking -flag is set. You'll also want to watch for focus changes and clear the tracking -flag when gaining/losing focus.

    - -

    API differences report

    - -

    For a detailed view of API changes in Android {@sdkPlatformVersion} (API Level {@sdkPlatformApiLevel}), as compared to -the previous version, see the API Differences Report.

    - diff --git a/docs/html/sdk/android-2.1.jd b/docs/html/sdk/android-2.1.jd deleted file mode 100644 index 1ee833c0094c..000000000000 --- a/docs/html/sdk/android-2.1.jd +++ /dev/null @@ -1,373 +0,0 @@ -page.title=Android 2.1 Platform -sdk.platform.version=2.1 -sdk.platform.apiLevel=7 -sdk.platform.majorMinor=minor - -@jd:body - - - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release -deployable to Android-powered handsets starting in January 2010. -This release includes new API -changes and bug fixes. For information on changes, see the Framework API -section.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes a -fully compliant Android library and system image, as well as a set of emulator -skins, sample applications, and more. The downloadable platform -includes no external libraries.

    - -

    To get started developing or testing against the Android -{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to -download the platform into your SDK. For more information, -see Adding SDK -Components.

    - - -

    Platform Highlights

    - -

    Android {@sdkPlatformVersion} does not add significant user features, see the Android -2.0 Platform Highlights document for the latest user features.

    - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 3 (July 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r12 or -higher.

    -
    -
    Notes:
    -
    -

    Improvements to the platform's rendering library to support the visual layout editor in the ADT -Eclipse plugin. This revision allows for more drawing features in ADT and fixes several -bugs in the previous rendering library. It also unlocks several editor features that were added in -ADT 12.

    -
    -
    - -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 2 (May 2010) -

    - -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r6 or higher.

    -
    - -
    Tools:
    -
    -
      -
    • Adds support for library projects in the Ant build system.
    • -
    • Adds improved layout rendering in ADT’s visual layout editor.
    • -
    -
    - -
    -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (January 2010) -

    - -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r4 or higher.

    -
    -
    -
    -
    - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your -application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the -android:minSdkVersion attributes of the <uses-sdk> -element in your application's manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Framework API Changes

    - -

    The sections below provide information about changes made to the application -framework API provided by the Android {@sdkPlatformVersion} platform.

    - -

    Live Wallpapers

    - -

    The following additions provide APIs for you to develop animated wallpapers:

    - - -

    Additionally, if your application uses or provides Live Wallpapers, you must -remember to add a <uses-feature> - element to the application's manifest, declaring the attribute -android:name="android.software.live_wallpaper". For example:

    - -
    -<uses-feature android:name="android.software.live_wallpaper" />
    -
    - -

    When you've published your application, Google Play checks for the -presence of this element and uses it as a filter, ensuring that your application -is not made available to users whose devices do not support Live Wallpapers. -

    - -

    Telephony

    - - - -

    Views

    - - - -

    WebKit

    - - - - - - - -

    API differences report

    - -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API -Level {@sdkPlatformApiLevel}), as compared to API Level 6, see the API -Differences Report.

    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Alarm Clock
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Contacts
    • -
    • Custom Locale (developer app)
    • -
    • Dev Tools (developer app)
    • -
    • Email
    • -
    -
    -
      - -
    • Gallery
    • -
    • IMEs for Japanese, Chinese, and Latin text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Phone
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    • Czech (cs_CZ)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • English, US (en_US)
    • -
    • English, Britain (en_GB)
    • -
    • English, Canada (en_CA)
    • -
    • English, Australia (en_AU)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • French, France (fr_FR)
    • -
    • French, Belgium (fr_BE)
    • -
    -
    -
  • French, Canada (fr_CA)
  • -
  • French, Switzerland (fr_CH)
  • -
  • German, Germany (de_DE)
  • -
  • German, Austria (de_AT)
  • -
  • German, Switzerland (de_CH)
  • -
  • German, Liechtenstein (de_LI)
  • -
  • Italian, Italy (it_IT)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Polish (pl_PL)
  • -
  • Russian (ru_RU)
  • -
  • Spanish (es_ES)
  • -
    - -

    Localized UI strings match the locales that are accessible -through Settings.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use -for modeling your application in different screen sizes and resolutions. The -emulator skins are:

    - - - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    diff --git a/docs/html/sdk/android-2.2-highlights.jd b/docs/html/sdk/android-2.2-highlights.jd deleted file mode 100644 index 37a20d506512..000000000000 --- a/docs/html/sdk/android-2.2-highlights.jd +++ /dev/null @@ -1,298 +0,0 @@ -page.title=Android 2.2 Platform Highlights - -@jd:body - - - - - -
    - - - - - -
    - - -

    The Android 2.2 platform introduces many new and exciting features for -users and developers. This document provides a glimpse at some of the new user features -and technologies in Android 2.2. For more information about the new developer APIs, see the Android 2.2 version notes.

    - - - - - -

    New User Features

    - -

    Home

    - - - - - - -
    - - -

    New Home screen tips widget assists new users on -how to configure the -home screen with shortcuts and widgets and how to make use of multiple home screens.

    -

    The Phone, applications Launcher, and Browser now have dedicated -shortcuts on the Home screen, making it easy to access them from any of the 5 home screen -panels.

    -
    - - - -

    Exchange support

    - - - - - - -
    -

    Improved security with the addition of numeric pin or alpha-numeric -password options to unlock device. Exchange administrators can enforce password policy across -devices.

    -

    Remote wipe: Exchange administrators can remotely reset the device to -factory defaults to secure data in case device is lost or stolen.

    -

    Exchange Calendars are now supported in the Calendar application.

    -

    Auto-discovery: you just need to know your user-name and password to -easily set up and sync an Exchange account (available for Exchange 2007 and higher).

    -

    Global Address Lists look-up is now available in the Email -application, enabling users to auto-complete recipient names from the directory.

    -
    - -
    - - -

    Camera and Gallery

    - - - - - - -
    - - -

    Gallery allows you to peek into picture stacks using a zoom -gesture.

    -

    Camera onscreen buttons provide easy access to a new UI for -controling zoom, flash, white balance, geo-tagging, focus and exposure. Camcorder also provides -an easy way to set video size/quality for MMS and YouTube.

    -

    With the LED flash now enabled for the Camcorder, videos can be shot -at night or in low light settings.

    -
    - - -

    Portable hotspot

    - - - - - - -
    -

    Certain devices like the Nexus One can be turned into a portable Wi-Fi -hotspot that can be shared with up to 8 devices.

    -

    You can use your Android-powered phone as a 3G connection for a Windows or Linux laptop by -connecting their phone to the computer with a USB cable. The connection is then shared between the -two devices.

    -
    - -
    - - -

    Multiple keyboard languages

    - - - - - - -
    - - -

    Multi-lingual users can add multiple languages to the keyboard and switch -between multiple Latin-based input languages by swiping across the space bar. This changes -the keys as well as the auto-suggest dictionary.

    -
    - - -

    Improved performance

    - - - - - - -
    -

    Performance of the browser has been enhanced using the V8 engine, -which enables faster loading of JavaScript-heavy pages.

    -

    Dalvik Performance Boost: 2x-5x performance speedup for CPU-heavy code -over Android 2.1 with Dalvik JIT.

    -

    The graph to the right shows the performance speedup from Android 2.1 -to Android 2.2 using various benchmark tests. For example, LinPack is now more than 5 times -faster.

    -

    Kernel Memory Management Boost: Improved memory reclaim by up to 20x, -which results in faster app switching and smoother performance on memory-constrained devices.

    -
    - -
    - - - - - -

    New Platform Technologies

    - - -

    Media framework

    - - - - -

    Bluetooth

    - - - - -

    2.6.32 kernel upgrade

    - - - - - - -

    New Developer Services

    - - -

    Android Cloud to Device Messaging

    - -

    Apps can utilize Android Cloud to Device Messaging to enable mobile alert, send to phone, and -two-way push sync functionality.

    - - -

    Android Application Error Reports

    - -

    New bug reporting feature for Google Play apps enables developers to receive crash and freeze -reports from their users. The reports will be available when they log into their publisher -account.

    - - - - -

    New Developer APIs

    - - -

    Apps on external storage

    - -

    Applications can now request installation on the shared external storage (such as an SD -card).

    - - -

    Media framework

    - -

    Provides new APIs for audio focus, routing audio to SCO, and auto-scan of files to media -database. Also provides APIs to let applications detect completion of sound loading and auto-pause -and auto-resume audio playback.

    - - -

    Camera and Camcorder

    - -

    New preview API doubles the frame rate from ~10FPS to ~20FPS. Camera now supports portrait -orientation, zoom controls, access to exposure data, and a thumbnail utility. A new camcorder -profile enables apps to determine device hardware capablities.

    - - -

    Graphics

    - -

    New APIs for OpenGL ES 2.0, working with YUV image format, and ETC1 for texture -compression.

    - - -

    Data backup

    - -

    Apps can participate in data backup and restore, to ensure that users maintain their data -after performing a factory reset or when switching devices.

    - - -

    Device policy manager

    - -

    New device policy management APIs allow developers to write "device administrator" applications -that can control security features on the device, such as the minimum password strength, data wipe, -and so on. Users can select the administrators that are enabled on their devices.

    - - -

    UI framework

    - -

    New "car mode" and "night mode" controls and configurations allow applications to adjust their UI -for these situations. A scale gesture detector API provides improved definition of multi-touch -events. Applications can now customize the bottom strip of a TabWidget.

    - - - -

    For more information about the new developer APIs, see the Android 2.2 version notes and the API Differences Report.

    - - - - - diff --git a/docs/html/sdk/android-2.2.jd b/docs/html/sdk/android-2.2.jd deleted file mode 100644 index c22220cf7262..000000000000 --- a/docs/html/sdk/android-2.2.jd +++ /dev/null @@ -1,470 +0,0 @@ -page.title=Android 2.2 Platform -sdk.platform.version=2.2 -sdk.platform.apiLevel=8 -sdk.platform.majorMinor=minor - -@jd:body - - - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is a {@sdkPlatformMajorMinor} platform release including user -features, developer features, API changes, and bug -fixes. For information on developer features and API changes, see the -Framework API section.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes a -fully compliant Android library and system image, as well as a set of emulator -skins, sample applications, and more. The downloadable platform -includes no external libraries.

    - -

    To get started developing or testing against the Android -{@sdkPlatformVersion} platform, use the Android SDK and AVD Manager tool to -download the platform into your SDK. For more information, -see Adding SDK -Components. If you are new to Android, download the SDK Starter Package -first.

    - - -

    Platform Highlights

    - -

    For a list of new user features and platform highlights, see the Android -2.2 Platform Highlights document.

    - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 3 (July 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r12 or -higher.

    -
    -
    Notes:
    -
    -

    Improvements to the platform's rendering library to support the visual layout editor in the ADT -Eclipse plugin. This revision allows for more drawing features in ADT and fixes several -bugs in the previous rendering library. It also unlocks several editor features that were added in -ADT 12.

    -
    -
    - -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 2 (July 2010) -

    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r6 or higher.

    -
    - -
    System Image:
    -
    -
      -
    • Adds default Search Widget.
    • -
    • Includes proper provisioning for the platform's Backup Manager. For more information about how to use the Backup Manager, see Data Backup.
    • -
    • Updates the Android 2.2 system image to FRF91.
    • -
    -
    - - -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (May 2010) -

    - -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r6 or higher.

    -
    - -
    Tools:
    -
    -

    Adds support for building with Android library projects. See SDK Tools, r6 for information.

    -
    - -
    -
    -
    - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your -application, you need to set the proper value, "{@sdkPlatformApiLevel}", in the -android:minSdkVersion attributes of the <uses-sdk> -element in your application's manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Framework API Changes

    - -

    The sections below provide information about changes made to the application -framework API provided by the Android {@sdkPlatformVersion} platform.

    - -

    App installation on external storage media

    - -

    The Android platform now allows applications to request installation onto the -device's external storage media (such as the SD card), as an alternative to -installation onto the device's internal memory.

    - -

    Application developers can express the preferred installation location for -their applications by means of a new attribute of <manifest> -in the manifest file, -android:installLocation. The attribute supports three values: -"internalOnly", "preferExternal", and -"auto". At install time, the system checks the value of -android:installLocation and installs the application -.apk according to the preferred location, if possible. If the -application has requested external installation, the system installs it into a -private, encrypted partition in the external media. Once an application .apk is -installed externally, the system lets the user change the storage location of -the .apk and move it onto the device's internal memory if needed (and vice -versa), through Manage Applications in the user settings.

    - -

    By default, the system installs all applications onto the device's internal -memory, except for those that explicitly request external installation. This -means that the system will always install legacy applications onto internal -memory, since they do not have access to the -android:installLocation attribute. However, it is possible to -configure and compile a legacy application such that it is installed internally -on older versions of the platform and externally on Android 2.2 and later -platforms, if necessary.

    - -

    Note that requesting installation onto the device's external media is not -suitable for all applications, particularly because the external media may be -removable and unmounting/remounting may disrupt the user experience and system -settings.

    - -

    For more information about setting a preferred install location for your -application, including a discussion of what types of applications should and -should not request external installation, please read the App Install Location -document.

    - -

    Data backup

    - -

    The platform now provides a generalized backup service that -applications can use to backup and restore user data, to ensure that users can -maintain their data when switching devices or reinstalling the application. The -Backup Manager handles the work of transporting the application data to and from -the backup storage area in the cloud. The Backup Manager can store any type of -data, from arbitrary data to files, and manages backup and restore operations -in an atomic manner. For more information, see Data Backup.

    - -

    Graphics

    - - - -

    Media

    - - - -

    Speech recognition and third-party recognition engines

    - - - -

    Camera and camcorder

    - - - -

    Device policy manager

    - -

    New device policy management APIs allow developers to write "device -administrator" applications that can control security features of the device, -such as the minimum password strength, data wipe, and so on. Users can select -the administrators that are enabled on their devices. For more information, see -the {@link android.app.admin android.app.admin} classees or the example -application code in DeviceAdminSample.java.

    - -

    UI Framework

    - - - -

    Accounts and sync

    - - - -

    New manifest elements and attributes

    - - - -

    Permissions

    - - - -

    API differences report

    - -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API -Level {@sdkPlatformApiLevel}), see the API -Differences Report.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Alarm Clock
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Contacts
    • -
    • Custom Locale (developer app)
    • -
    • Dev Tools (developer app)
    • -
    • Email
    • -
    -
    -
      - -
    • Gallery
    • -
    • IMEs for Japanese, Chinese, and Latin text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Phone
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    • Czech (cs_CZ)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • English, US (en_US)
    • -
    • English, Britain (en_GB)
    • -
    • English, Canada (en_CA)
    • -
    • English, Australia (en_AU)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • French, France (fr_FR)
    • -
    • French, Belgium (fr_BE)
    • -
    -
    -
  • French, Canada (fr_CA)
  • -
  • French, Switzerland (fr_CH)
  • -
  • German, Germany (de_DE)
  • -
  • German, Austria (de_AT)
  • -
  • German, Switzerland (de_CH)
  • -
  • German, Liechtenstein (de_LI)
  • -
  • Italian, Italy (it_IT)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Polish (pl_PL)
  • -
  • Russian (ru_RU)
  • -
  • Spanish (es_ES)
  • -
    - -

    Localized UI strings match the locales that are accessible -through Settings.

    - -

    Note: Android supports more locales than are listed above. However, -the entire collection of locale strings cannot fit on a single system image, so the above list is -only what's included in the system image for the SDK. All of Android's supported locales are -available in the Android Open Source Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use -for modeling your application in different screen sizes and resolutions. The -emulator skins are:

    - - - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    diff --git a/docs/html/sdk/android-2.3-highlights.jd b/docs/html/sdk/android-2.3-highlights.jd deleted file mode 100644 index b076b3de191c..000000000000 --- a/docs/html/sdk/android-2.3-highlights.jd +++ /dev/null @@ -1,446 +0,0 @@ -page.title=Android 2.3 Platform Highlights - -@jd:body - - - - -
    - - - - - -
    - -

    The Android 2.3 platform introduces many new and exciting features for -users and developers. This document provides a glimpse at some of the new features -and technologies in Android 2.3. For detailed information about the new developer APIs, see the Android 2.3 version notes.

    - - - - -

    New User Features

    - -
    - - - -

    UI refinements for simplicity and speed

    - -

    The user interface is refined in many ways across the system, making it -easier to learn, faster to use, and more power-efficient. A simplified -visual theme of colors against black brings vividness and contrast to the -notification bar, menus, and other parts of the UI. Changes in menus and -settings make it easier for the user to navigate and control the features -of the system and device.

    - -

    Faster, more intuitive text input

    - -

    The Android soft keyboard is redesigned and optimized for faster text input -and editing. The keys themselves are reshaped and repositioned for improved -targeting, making them easier to see and press accurately, even at high speeds. -The keyboard also displays the current character and dictionary suggestions in a -larger, more vivid style that is easier to read.

    - -

    The keyboard adds the capability to correct entered words from suggestions in -the dictionary. As the user selects a word already entered, the keyboard -displays suggestions that the user can choose from, to replace the selection. -The user can also switch to voice input mode to replace the selection. Smart -suggestions let the user accept a suggestion and then return to correct it -later, if needed, from the original set of suggestions.

    - -

    New multitouch key-chording lets the user quickly enter numbers and symbols -by pressing Shift+<letter> and ?123+<symbol>, -without needing to manually switch input modes. From certain keys, users can -also access a popup menu of accented characters, numbers, and symbols by holding -the key and sliding to select a character.

    -
    - -
    -
    -
    - - -

    One-touch word selection and copy/paste

    - -

    When entering text or viewing a web page, the user can quickly select a word -by press-hold, then copy to the clipboard and paste. Pressing on a word enters a -free-selection mode — the user can adjust the selection area as needed by -dragging a set of bounding arrows to new positions, then copy the bounded area -by pressing anywhere in the selection area. For text entry, the user can -slide-press to enter a cursor mode, then reposition the cursor easily and -accurately by dragging the cursor arrow. With both the selection and cursor -modes, no use of a trackball is needed.

    - -
    - -
    -
    -
    - -

    Improved power management

    - -

    The Android system takes a more active role in managing apps that are keeping -the device awake for too long or that are consuming CPU while running in the -background. By managing such apps — closing them if appropriate — -the system helps ensure best possible performance and maximum battery life.

    - -

    The system also gives the user more visibility over the power being consumed -by system components and running apps. The Application settings provides an -accurate overview of how the battery is being used, with details of the usage -and relative power consumed by each component or application.

    - -

    Control over applications

    - -

    A shortcut to the Manage Applications control now appears in the Options Menu -in the Home screen and Launcher, making it much easier to check and manage -application activity. Once the user enters Manage Applications, a new Running -tab displays a list of active applications and the storage and memory being used -by each. The user can read further details about each application and if -necessary stop an application or report feedback to its developer.

    -
    - -

    New ways of communicating, organizing

    - -

    An updated set of standard applications lets the user take new approaches to -managing information and relationships.

    - -
    -

    -
    -
    - -

    Internet calling

    - -

    The user can make voice calls over the internet to other users who have SIP -accounts. The user can add an internet calling number (a SIP address) to any -Contact and can initiate a call from Quick Contact or Dialer. To use internet -calling, the user must create an account at the SIP provider of their choice -— SIP accounts are not provided as part of the internet calling feature. -Additionally, support for the platform's SIP and internet calling features on -specific devices is determined by their manufacturers and associated carriers. -

    - -
    - -

    Near-field communications

    - -

    An NFC Reader application lets the user read and interact with near-field -communication (NFC) tags. For example, the user can “touch” or “swipe” an NFC -tag that might be embedded in a poster, sticker, or advertisement, then act on -the data read from the tag. A typical use would be to read a tag at a -restaurant, store, or event and then rate or register by jumping to a web site -whose URL is included in the tag data. NFC communication relies on wireless -technology in the device hardware, so support for the platform's NFC features on -specific devices is determined by their manufacturers. -

    -
    - -

    Downloads management

    - -

    The Downloads application gives the user easy access to any file downloaded from -the browser, email, or another application. Downloads is built on an completely new -download manager facility in the system that any other applications can use, to -more easily manage and store their downloads.

    - -

    Camera

    - -

    The application now lets the user access multiple cameras on the device, -including a front-facing camera, if available.

    - - -

    New Developer Features

    - -

    Android 2.3 delivers a variety of features and APIs that -let developers bring new types of applications to the Android -platform.

    - - - -

    Enhancements for gaming

    - -

    Performance

    - -

    Android 2.3 includes a variety of improvements across the system that make -common operations faster and more efficient for all applications. Of particular -interest to game developers are:

    - - - - -

    Native input and -sensor events

    - -

    Applications that use native code can now receive and process input and -sensor events directly in their native code, which dramatically improves -efficiency and responsiveness.

    - -

    Native libraries exposed by the platform let applications handle the same -types of input events as those available through the framework. Applications -can receive events from all supported sensor types and can enable/disable -specific sensors and manage event delivery rate and queueing.

    - - -

    Gyroscope and other -new sensors, for improved 3D motion processing

    - -

    Android 2.3 adds API support for several new sensor types, including -gyroscope, rotation vector, linear acceleration, gravity, and barometer sensors. -Applications can use the new sensors in combination with any other sensors -available on the device, to track three-dimensional device motion and -orientation change with high precision and accuracy. For example, a game -application could use readings from a gyroscope and accelerometer on the device -to recognize complex user gestures and motions, such as tilt, spin, thrust, and -slice.

    - - -

    Open API for native -audio

    - -

    The platform provides a software implementation of Khronos OpenSL ES, a standard API -that gives applications access to powerful audio controls and effects from -native code. Applications can use the API to manage audio devices and control -audio input, output, and processing directly from native code.

    - -

    Native graphics -management

    - -

    The platform provides an interface to its Khronos EGL library, which lets -applications manage graphics contexts and create and manage OpenGL ES textures -and surfaces from native code.

    - - -

    Native access to -Activity lifecycle, window management

    - -

    Native applications can declare a new type of Activity class, -NativeActivity whose lifecycle callbacks are implemented directly -in native code. The NativeActivity and its underlying native code -run in the system just as do other Activities — they run in the -application's system process and execute on the application's main UI thread, -and they receive the same lifecycle callbacks as do other Activities.

    - -

    The platform also exposes native APIs for managing windows, including the -ability to lock/unlock the pixel buffer to draw directly into it. Through the -API, applications can obtain a native window object associated with a framework -Surface object and interact with it directly in native code.

    - - -

    Native access to -assets, storage

    - -

    Applications can now access a native Asset Manager API to retrieve -application assets directly from native code without needing to go through JNI. -If the assets are compressed, the platform does streaming decompression as the -application reads the asset data. There is no longer a limit on the size of -compressed .apk assets that can be read.

    - -

    Additionally, applications can access a native Storage Manager API to work -directly with OBB files downloaded and managed by the system. Note that although -platform support for OBB is available in Android 2.3, development tools for -creating and managing OBB files will not be available until early 2011.

    - - -

    Robust native -development environment

    - -

    The Android NDK (r5 or higher) provides a complete set of tools, toolchains, -and libraries for developing applications that use the rich native environment -offered by the Android 2.3 platform. For more information or to download the -NDK, please see the Android NDK -page.

    - - -

    New forms of communication

    - -

    Internet -telephony

    - -

    Developers can now add SIP-based internet telephony features to their -applications. Android 2.3 includes a full SIP protocol stack and integrated call -management services that let applications easily set up outgoing and incoming -voice calls, without having to manage sessions, transport-level communication, -or audio record or playback directly.

    - -

    Support for the platform's SIP and internet calling features on specific -devices is determined by their manufacturers and associated carriers.

    - - -

    Near Field -Communications (NFC)

    - -

    The platform's support for Near Field Communications (NFC) lets developers -get started creating a whole new class of applications for Android. Developers -can create new applications that offer proximity-based information and services -to users, organizations, merchants, and advertisers.

    - -

    Using the NFC API, -applications can read and respond to NFC tags “discovered” as the user “touches” an -NFC-enabled device to elements embedded in stickers, smart posters, and even -other devices. When a tag of interest is collected, applications can respond to -the tag, read messages from it, and then store the messages, prompting -the user as needed.

    - -

    Starting from Android 2.3.3, applications can also write to tags and -set up peer-to-peer connections with other NFC devices.

    - -

    NFC communication relies on wireless technology in the device hardware, so -support for the platform's NFC features on specific devices is determined by -their manufacturers.

    - - -

    Rich multimedia

    - -

    Mixable audio -effects

    - -

    A new audio effects API lets developers easily create rich audio environments -by adding equalization, bass boost, headphone virtualization (widened -soundstage), and reverb to audio tracks and sounds. Developers can mix multiple -audio effects in a local track or apply effects globally, across multiple -tracks.

    - -

    Support for new media -formats

    - -

    The platform now offers built-in support for the VP8 open video compression -format and the WebM open container format. The platform also adds support for -AAC encoding and AMR wideband encoding (in software), so that applications can -capture higher quality audio than narrowband.

    - -

    Access to multiple -cameras

    - -

    The Camera API now lets developers access any cameras that are available on a -device, including a front-facing camera. Applications can query the platform for -the number of cameras on the device and their types and characteristics, then -open the camera needed. For example, a video chat application might want to access a -front-facing camera that offers lower-resolution, while a photo application -might prefer a back-facing camera that offers higher-resolution.

    - - -

    New Platform Technologies

    - -

    Media Framework

    - - - -

    Linux Kernel

    - - -

    Networking

    - - -

    Dalvik runtime

    - - - -

    For more information about the new developer APIs, see the Android 2.3 version notes and the API Differences Report.

    diff --git a/docs/html/sdk/android-2.3.3.jd b/docs/html/sdk/android-2.3.3.jd deleted file mode 100644 index 405c063fa857..000000000000 --- a/docs/html/sdk/android-2.3.3.jd +++ /dev/null @@ -1,419 +0,0 @@ -page.title=Android 2.3.3 Platform -sdk.platform.version=2.3.3 -sdk.platform.apiLevel=10 - - -@jd:body - -
    -
    - -

    In this document

    -
      -
    1. Revisions
    2. -
    3. API Overview
    4. -
    5. API Level
    6. -
    7. Built-in Applications
    8. -
    9. Locales
    10. -
    11. Emulator Skins
    12. -
    - -

    Reference

    -
      -
    1. API -Differences Report »
    2. -
    - -

    See Also

    -
      -
    1. Adding SDK Components
    2. -
    - -
    -
    - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android 2.3.3 is a small feature release that adds several improvements -and APIs to the Android 2.3 platform.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes -an Android library and system image, as well as a set of emulator -skins and more. The downloadable platform -includes no external libraries.

    - -

    To get started developing or testing against Android -{@sdkPlatformVersion}, use the Android SDK Manager to -download the platform into your SDK. For more information, -see Adding SDK -Components. If you are new to Android, download the SDK Starter Package -first.

    - -

    For a high-level introduction to Android 2.3, see the Platform Highlights.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 2 (July 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r12 or -higher.

    -
    -
    Notes:
    -
    -

    Improvements to the platform's rendering library to support the visual layout editor in the ADT -Eclipse plugin. This revision allows for more drawing features in ADT and fixes several -bugs in the previous rendering library. It also unlocks several editor features that were added in -ADT 12.

    -
    -
    - -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (February 2011) -

    - -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r9 or higher.

    -
    -
    - -
    -
    - - -

    API Overview

    - -

    The sections below provide a technical overview of what's new for developers -in {@sdkPlatformVersion}, including new features and changes in the framework -API since the previous version.

    - -

    Near Field Communications (NFC)

    - -

    Android 2.3.3 provides improved and extended support for NFC, to allow -applications to interact with more types of tags in new ways.

    - -

    A new, comprehensive set of APIs give applications read and write access -to a wider range of standard tag technologies, including:

    - - - -

    The platform also provides a limited peer-to-peer communication protocol -and API. Foreground Activities can use the API to register an NDEF -message that will get pushed to other NFC devices when they connect.

    - -

    Advanced tag dispatching now gives applications more control over how and -when they are launched, when an NFC tag is discovered. Previously, the platform -used a single-step intent dispatch to notify interested applications that a tag -was discovered. The platform now uses a four-step process that enables the -foreground application to take control of a tag event before it is passed to any -other applications (android.nfc.NfcAdapter.enableForegroundDispatch()). - -The new dispatch process also lets apps listen for specific tag content and -tag technologies, based on two new intent actions — -android.nfc.action.NDEF_DISCOVERED and -android.nfc.action.TECH_DISCOVERED.

    - -

    The NFC API is available in the {@link android.nfc} and -{@link android.nfc.tech} packages. The key classes are:

    - - - -

    NFC communication relies on wireless technology in the device hardware, and -is not present in all Android devices. Android devices that do not support -NFC will return a null object when -{@link android.nfc.NfcAdapter#getDefaultAdapter(android.content.Context) -getDefaultAdapter(Context)} is called, and -context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC) -will return false. The NFC API is always present, however, regardless of -underlying hardware support.

    - -

    To use the NFC API, applications must request permission from the user by -declaring <uses-permission -android:name="android.permission.NFC"> in their manifest files.

    - -

    Additionally, developers can request filtering on Google Play, such that -their applications are not discoverable to users whose devices do not support -NFC. To request filtering, add -<uses-feature android:name="android.hardware.nfc" -android:required="true"> to the application's manifest.

    - -

    To look at sample code for NFC, see -NFCDemo app, filtering by tag technology, using foreground dispatch, and foreground NDEF push (P2P).

    - -

    Bluetooth

    - -

    Android 2.3.3 adds platform and API support for Bluetooth nonsecure socket -connections. This lets applications communicate with simple devices that may not -offer a UI for authentication. See -{@link android.bluetooth.BluetoothDevice#createInsecureRfcommSocketToServiceRecord(java.util.UUID)} and -{@link android.bluetooth.BluetoothAdapter#listenUsingInsecureRfcommWithServiceRecord(java.lang.String, java.util.UUID)} -for more information.

    - -

    Graphics

    - - - - -

    Media framework

    - - - - -

    Speech recognition

    - -

    The speech-recognition API includes new constants to let you manage voice -search results in new ways. Although the new constants are not needed for normal -use of speech recognition, you could use them to offer a different view of voice -search results in your application. For information, see {@link -android.speech.RecognizerResultsIntent}.

    - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, -you need compile the application against the Android library that is provided in -the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might -also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" -attribute to the <uses-sdk> element in the application's -manifest. If your application is designed to run only on Android 2.3 and higher, -declaring the attribute prevents the application from being installed on earlier -versions of the platform.

    - -

    For more information about how to use API Level, see the API Levels document.

    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Clock
    • -
    • Contacts
    • -
    • Cusom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    -
    -
      -
    • Gallery
    • -
    • IMEs for Japanese, Chinese, and Latin text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Phone
    • -
    • Search
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    • Speech Recorder
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian-Bokmol, Norway(nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use -for modeling your application in different screen sizes and resolutions. The -emulator skins are:

    - - - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    diff --git a/docs/html/sdk/android-2.3.4.jd b/docs/html/sdk/android-2.3.4.jd deleted file mode 100644 index 4bfdabdb6a4a..000000000000 --- a/docs/html/sdk/android-2.3.4.jd +++ /dev/null @@ -1,381 +0,0 @@ -page.title=Android 2.3.4 Platform -sdk.platform.version=2.3.4 -sdk.platform.apiLevel=10 - - -@jd:body - - - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    Android 2.3.4 is a maintenance release that adds several bug fixes and patches -to the Android 2.3 platform, without any API changes from Android 2.3.3. Additionally, -Android 2.3.4 brings support for the Open Accessory API to mobile devices, -through the optional Open Accessory Library.

    - -

    For developers, the Android {@sdkPlatformVersion} platform and the Open -Accessory Library are available together in the latest version of the Google -APIs Add-On, a downloadable component for the Android SDK.

    - -

    To get started developing or testing against Android {@sdkPlatformVersion}, -use the Android SDK Manager to download the latest version of the Google APIs -Add-On into your SDK. For more information, see Adding SDK Components. If you -are new to Android, download the SDK Starter -Package first.

    - -

    For a high-level introduction to Android 2.3, see the Platform Highlights.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - - -
    - - - Android {@sdkPlatformVersion}, Revision 1 (May 2011) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r11 or higher.

    -
    - -
    -
    -
    - - -

    API Overview

    - -

    Android 2.3.4 provides the same framework API to applications as Android 2.3.3 -(API level 10). For a summary of the API, see the -Android 2.3.3 version notes.

    - - -

    Open Accessory Library

    - -

    Open Accessory is a new capability for integrating -connected peripherals with applications running on the platform. The capability -is based on a USB (Universal Serial Bus) stack built into the platform and an -API exposed to applications. Peripherals that attach to Android-powered devices -as accessories connect as USB hosts.

    - -

    Open Accessory is introduced in Android 3.1 (API level 12), but is -made available to devices running Android 2.3.4 by means of an optional external -library, the Open Accessory Library. The library exposes a framework API that -lets applications discover, communicate with, and manage a variety of device -types connected over USB. It also provides the implementation of the API against -parts of the Android platform that are not directly exposed to applications in -Android 2.3.4.

    - -

    The Open Accessory Library is optional on any given device. Device -manufacturers may choose whether to include the Open Accessory Library in their -products or exclude it. The library is forward-compatible with Android 3.1, so -applications developed against Android 2.3.4 will run properly on devices -running Android 3.1, if those devices support USB accessories.

    - -

    The API provided by the Open Accessory Library is based on the Open Accessory -API provided in Android 3.1. In most areas, you can use the same techniques and -APIs. However, developing for the Open Accessory Library on Android 2.3.4 differs -from the standard USB API in these ways: - -

    - -

    To develop apps using the Open Accessory Library, you need:

    - - - -

    For a full discussion of how to develop applications that interact with USB -accessories, please see the related developer documentation.

    - -

    Additionally, developers can request filtering on Google Play, such that -their applications are not available to users whose devices do not provide the -appropriate accessory support. To request filtering, add the element below -to the application manifest:

    - -
    <uses-feature
    -  android:name="android.hardware.usb.accessory"
    -  android:required="true">
    - - -

    API Level

    - -

    The Android 2.3.4 platform does not increment the API level — -it uses the same API level as Android 2.3.3, API level 10. - -

    To use APIs introduced in API level 10 in your application, -you need compile the application against the Android library that is provided in -the latest version of the Google APIs Add-On, which also includes the Open -Accessory Library.

    - -

    Depending on your needs, you might -also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" -attribute to the <uses-sdk> element in the application's -manifest. If your application is designed to run only on Android 2.3.3 and higher, -declaring the attribute prevents the application from being installed on earlier -versions of the platform.

    - -

    For more information about how to use API Level, see the API Levels document.

    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Clock
    • -
    • Contacts
    • -
    • Custom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    -
    -
      -
    • Gallery
    • -
    • IMEs for Japanese, Chinese, and Latin text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Phone
    • -
    • Search
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    • Speech Recorder
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
      -
    • Croatian, Croatia (hr_HR)
    • -
    • Hungarian, Hungary (hu_HU)
    • -
    • Indonesian, Indonesia (id_ID)
    • -
    • Italian, Switzerland (it_CH)
    • -
    • Italian, Italy (it_IT)
    • -
    • Japanese (ja_JP)
    • -
    • Korean (ko_KR)
    • -
    • Lithuanian, Lithuania (lt_LT)
    • -
    • Latvian, Latvia (lv_LV)
    • -
    • Norwegian-Bokmol, Norway(nb_NO)
    • -
    • Dutch, Belgium (nl_BE)
    • -
    • Dutch, Netherlands (nl_NL)
    • -
    • Polish (pl_PL)
    • -
    • Portuguese, Brazil (pt_BR)
    • -
    • Portuguese, Portugal (pt_PT)
    • -
    • Romanian, Romania (ro_RO)
    • -
    • Russian (ru_RU)
    • -
    • Slovak, Slovakia (sk_SK)
    • -
    • Slovenian, Slovenia (sl_SI)
    • -
    • Serbian (sr_RS)
    • -
    • Swedish, Sweden (sv_SE)
    • -
    • Thai, Thailand (th_TH)
    • -
    • Tagalog, Philippines (tl_PH)
    • -
    • Turkish, Turkey (tr_TR)
    • -
    • Ukrainian, Ukraine (uk_UA)
    • -
    • Vietnamese, Vietnam (vi_VN)
    • -
    • Chinese, PRC (zh_CN)
    • -
    • Chinese, Taiwan (zh_TW)
    • -
    -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use -for modeling your application in different screen sizes and resolutions. The -emulator skins are:

    - - - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    diff --git a/docs/html/sdk/android-2.3.jd b/docs/html/sdk/android-2.3.jd deleted file mode 100644 index b46691309891..000000000000 --- a/docs/html/sdk/android-2.3.jd +++ /dev/null @@ -1,942 +0,0 @@ -page.title=Android 2.3 Platform -sdk.platform.version=2.3 -sdk.platform.apiLevel=9 - - -@jd:body - -
    -
    - -

    In this document

    -
      -
    1. Revisions
    2. -
    3. API Overview
    4. -
    5. API Level
    6. -
    7. Built-in Applications
    8. -
    9. Locales
    10. -
    11. Emulator Skins
    12. -
    - -

    Reference

    -
      -
    1. API -Differences Report »
    2. -
    - -

    See Also

    -
      -
    1. Adding SDK Components
    2. -
    - -
    -
    - -

    -API Level: {@sdkPlatformApiLevel}

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes -an Android library and system image, as well as a set of emulator -skins and more. The downloadable platform -includes no external libraries.

    - -

    To get started developing or testing against Android -{@sdkPlatformVersion}, use the Android SDK Manager to -download the platform into your SDK. For more information, -see Adding SDK -Components. If you are new to Android, download the SDK Starter Package -first.

    - -

    For a high-level introduction to Android {@sdkPlatformVersion}, see the Platform Highlights.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Android {@sdkPlatformVersion} platform component for the Android SDK, as denoted by -revision number. To determine what revision(s) of the Android -{@sdkPlatformVersion} platforms are installed in your SDK environment, refer to -the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - - -
    - - - Android {@sdkPlatformVersion}, Revision 1 (December 2010) -
    -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r8 or higher.

    -
    - -
    -
    -
    - -

    API Overview

    - -

    The sections below provide a technical overview of what's new for developers -in {@sdkPlatformVersion}, including new features and changes in the framework -API since the previous version.

    - - -

    SIP-based VoIP

    - -

    The platform now includes a SIP protocol stack and framework API that lets -developers build internet telephony applications. Using the API, applications can offer -voice calling features without having to manage sessions, transport-level -communication, or audio — these are handled -transparently by the platform's SIP API and services.

    - -

    The SIP API is available in the {@link android.net.sip android.net.sip} -package. The key class is {@link android.net.sip.SipManager}, which applications -use to set up and manage SIP profiles, then initiate audio calls and receive -audio calls. Once an audio call is established, applications can mute calls, -turn on speaker mode, send DTMF tones, and more. Applications can also use the -{@link android.net.sip.SipManager} to create generic SIP connections.

    - -

    The platform’s underlying SIP stack and services are available on devices at -the discretion of the manufacturer and associated carrier. For this reason, -applications should use the {@link android.net.sip.SipManager#isApiSupported -isApiSupported()} method to check whether SIP support is available, before -exposing calling functionality to users.

    - -

    To use the SIP API, applications must request permission from the user by -declaring <uses-permission -android:name="android.permission.INTERNET"> and <uses-permission -android:name="android.permission.USE_SIP"> in their manifest files.

    - -

    Additionally, developers can request filtering on Google Play, such that -their applications are not discoverable to users whose devices do not include -the platform’s SIP stack and services. To request filtering, add <uses-feature -android:name="android.software.sip" -android:required="true"> and <uses-feature -android:name="android.software.sip.voip"> to the application manifest.

    - -

    To look at a sample application that uses the SIP API, see SIP Demo.

    - -

    Near Field Communications (NFC)

    - -

    Android 2.3 includes an NFC stack and framework API that lets developers -read NDEF tags that are discovered as a user touches an NFC-enabled device -to tag elements embedded in stickers, smart posters, and even other devices.

    - -

    The platform provides the underlying NFC services that work with the device -hardware to discover tags when they come into range. On discovering a tag, the -platform notifies applications by broadcasting an Intent, appending the tag's -NDEF messages to the Intent as extras. Applications can create Intent filters to -recognize and handle targeted tags and messages. For example, after receiving a -tag by Intent, applications extract the NDEF messages, store them, alert the -user, or handle them in other ways.

    - -

    The NFC API is available in the {@link android.nfc} package. The key classes are:

    - -
    - -

    NFC communication relies on wireless technology in the device hardware, so -support for the platform's NFC features on specific devices is determined by -their manufacturers. To determine the NFC support on the current device, -applications can call {@link android.nfc.NfcAdapter#isEnabled isEnabled()} to -query the {@link android.nfc.NfcAdapter}. The NFC API is always present, -however, regardless of underlying hardware support.

    - -

    To use the NFC API, applications must request permission from the user by -declaring <uses-permission -android:name="android.permission.NFC"> in their manifest files.

    - -

    Additionally, developers can request filtering on Google Play, such that -their applications are not discoverable to users whose devices do not support -NFC. To request filtering, add -<uses-feature android:name="android.hardware.nfc" -android:required="true"> to the application's manifest.

    - -

    To look at a sample application that uses the NFC API, see -NFCDemo.

    - -

    Gyroscope and other sensors

    - -

    Android 2.3 adds platform and API support for several new sensor reading -types — gyroscope, rotation vector, linear acceleration, gravity, and barometer. -Developers can use the new sensor readings to create applications that respond -quickly and smoothly to precise changes in device position and motion. The -Sensor API reports gyroscope and other sensor changes to interested -applications, whether they are running on the application framework or in native -code.

    - -

    Note that the specific set of hardware sensors available on any given device -varies at the discretion of the device manufacturer.

    - -

    Developers can request filtering on Google Play, such that their -applications are not discoverable to users whose devices do not offer a -gyroscope sensor. To do so, add <uses-feature -android:name="android.hardware.sensor.gyroscope" -android:required="true"> to the application manifest.

    - -

    For API details, see {@link android.hardware.Sensor}.

    - - -

    Multiple cameras support

    - -

    Applications can now make use of any cameras that are available on a device, -for either photo or video capture. The {@link android.hardware.Camera} lets -applications query for the number of cameras available and the unique -characteristics of each.

    - - - -

    To look at sample code for accessing a front-facing camera, see CameraPreview.java -in the ApiDemos sample application.

    - -

    The Camera API also adds:

    - - -

    Mixable audio effects

    - -

    The platform's media framework adds support for new per-track or global audio effects, -including bass boost, headphone virtualization, equalization, and reverb.

    - - -

    To look at sample code for audio effects, see -AudioFxDemo.java -in the ApiDemos sample application.

    - -

    The media framework also adds:

    - - -

    Download manager

    - -

    The platform includes a new {@link android.app.DownloadManager} system service -that handles long-running HTTP downloads. Applications can request that a URI be -downloaded to a particular destination file. The DownloadManager -will conduct the download in the background, taking care of HTTP interactions -and retrying downloads after failures or across connectivity changes and system -reboots.

    - - -

    StrictMode

    - -

    To help developers monitor and improve the performance of their applications, -the platform offers a new system facility called {@link android.os.StrictMode}. -When implemented in an application, StrictMode catches and notifies the -developer of accidental disk or network activity that could degrade application -performance, such as activity taking place on the application's main thread -(where UI operations are received and animations are also taking place). -Developers can evaluate the network and disk usages issues raised in StrictMode -and correct them if needed, keeping the main thread more responsive and -preventing ANR dialogs from being shown to users. - -

    - -

    For more information about how to use StrictMode to optimize your -application, see the class documentation and sample code at {@link -android.os.StrictMode android.os.StrictMode}.

    - -

    UI Framework

    - - - -

    Extra Large Screens

    - -

    The platform now supports extra large screen sizes, such as those that might -be found on tablet devices. Developers can indicate that their applications are -designed to support extra large screen sizes by adding a <supports -screens ... android:xlargeScreens="true"> element to their manifest -files. Applications can use a new resource qualifier, xlarge, to -tag resources that are specific to extra large screens. For -details on how to support extra large and other screen sizes, see Supporting Multiple -Screens.

    - -

    Graphics

    - - - -

    Content Providers

    - - - -

    Location

    - - - -

    Storage

    - - - -

    Package Manager

    - - - -

    Telephony

    - - - -

    Native access to Activity lifecycle, windows

    - -

    Android 2.3 exposes a broad set of APIs to applications that use native -code. Framework classes of interest to such applications include:

    - - - -

    For full information on working with native code or to download the NDK, -see the Android NDK page.

    - - -

    Dalvik Runtime

    - - - -

    New manifest elements and attributes

    - - - -

    New Permissions

    - - - -

    New Feature Constants

    - -

    The platform adds several new hardware features that developers can declare -in their application manifests as being required by their applications. This -lets developers control how their application is filtered, when published on -Google Play.

    - - - -

    For full information about how to declare features and use them for -filtering, see the documentation for <uses-feature>.

    - -

    API differences report

    - -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API -Level {@sdkPlatformApiLevel}), see the API -Differences Report.

    - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, -you need compile the application against the Android library that is provided in -the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might -also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" -attribute to the <uses-sdk> element in the application's -manifest. If your application is designed to run only on Android 2.3 and higher, -declaring the attribute prevents the application from being installed on earlier -versions of the platform.

    - -

    For more information about how to use API Level, see the API Levels document.

    - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Clock
    • -
    • Contacts
    • -
    • Cusom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    -
    -
      -
    • Gallery
    • -
    • IMEs for Japanese, Chinese, and Latin text input
    • -
    • Messaging
    • -
    • Music
    • -
    • Phone
    • -
    • Search
    • -
    • Settings
    • -
    • Spare Parts (developer app)
    • -
    • Speech Recorder
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android {@sdkPlatformVersion} system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian-Bokmol, Norway(nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes a set of emulator skins that you can use -for modeling your application in different screen sizes and resolutions. The -emulator skins are:

    - - - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    diff --git a/docs/html/sdk/android-3.0-highlights.jd b/docs/html/sdk/android-3.0-highlights.jd deleted file mode 100644 index 33897de91c6c..000000000000 --- a/docs/html/sdk/android-3.0-highlights.jd +++ /dev/null @@ -1,263 +0,0 @@ -page.title=Android 3.0 Platform Highlights - -@jd:body - - - - - -

    Welcome to Android 3.0!

    - -

    The Android 3.0 platform introduces many new and exciting features for users and developers. -This document provides a glimpse of some of the new features and technologies, as delivered in -Android 3.0. For a more detailed look at new developer APIs, see the Android 3.0 Platform document.

    - - - -

    New User Features

    - -
    -
    - -

    New UI designed from the ground up for tablets

    - -

    Android 3.0 is a new version of the Android platform that is specifically optimized for devices with larger screen sizes, particularly tablets. It introduces a brand new, truly virtual and “holographic” UI design, as well as an elegant, content-focused interaction model.

    - -

    Android 3.0 builds on the things people love most about Android — refined multitasking, rich notifications, Home screen customization, widgets, and more — and transforms them with a vibrant, 3D experience and deeper interactivity, making them familiar but even better than before.

    - -

    The new UI brings fresh paradigms for interaction, navigation, and customization and makes them available to all applications — even those built for earlier versions of the platform. Applications written for Android 3.0 are able to use an extended set of UI objects, powerful graphics, and media capabilities to engage users in new ways.

    - -

    System Bar, for global status and notifications

    - -

    Across the system and in all applications, users have quick access to notifications, system status, and soft navigation buttons in a System Bar, available at the bottom of the screen. The System Bar is always present and is a key touchpoint for users, but in a new "lights out mode" can also be dimmed for full-screen viewing, such as for videos.

    - -

    Action Bar, for application control

    - -

    In every application, users have access to contextual options, navigation, widgets, or other types of content in an Action Bar, displayed at the top of the screen. The Action Bar is always present when an application is in use, although its content, theme, and other properties are managed by the application rather than the system. The Action Bar is another key touchpoint for users, especially with action items and an overflow dropdown menu, which users frequently access in a similar manner in most applications.

    - -
    - -
    -
    - -

    Customizable Home screens

    - -

    Five customizable Home screens give users instant access to all parts of the system from any context. Each screen offers a large grid that maintains spatial arrangement in all orientations. Users can select and manipulate Home screen widgets, app shortcuts, and wallpapers using a dedicated visual layout mode. Visual cues and drop shadows improve visibility when adjusting the layout of shortcuts and widgets. Each Home screen also offers a familiar launcher for access to all installed applications, as well as a Search box for universal search of apps, contacts, media files, web content, and more.

    - -
    - -
    -
    - -
    - -

    Recent Apps, for easy visual multitasking

    - -

    Multitasking is a key strength of Android and it is central to the Android 3.0 experience. As users launch applications to handle various tasks, they can use the Recent Apps list in the System Bar to see the tasks underway and quickly jump from one application context to another. To help users rapidly identify the task associated with each app, the list shows a snapshot of its actual state when the user last viewed it.

    - -
    - - -

    Redesigned keyboard

    - -

    The Android soft keyboard is redesigned to make entering text fast and accurate on larger screen sizes. The keys are reshaped and repositioned for improved targeting, and new keys have been added, such as a Tab key, to provide richer and more efficient text input. Users can touch-hold keys to access menus of special characters and switch text/voice input modes from a button in the System Bar.

    - -
    -
    - - -

    Improved text selection, copy and paste

    - -

    When entering or viewing text, a new UI lets users quickly select a word by press-hold and then adjust the selection area as needed by dragging a set of bounding arrows to new positions. Users can then select an action from the Action Bar, such as copy to the clipboard, share, paste, web search, or find.

    - - -

    New connectivity options

    - -

    Android 3.0 includes new connectivity features that add versatility and convenience for users. Built-in support for Media/Picture Transfer Protocol lets users instantly sync media files with a USB-connected camera or desktop computer, without needing to mount a USB mass-storage device. Users can also connect full keyboards over either USB or Bluetooth, for a familiar text-input environment. For improved wi-fi connectivity, a new combo scan reduces scan times across bands and filters. New support for Bluetooth tethering means that more types of devices can share the network connection of an Android-powered device.

    - - -

    Updated set of standard apps

    - -
    -

    -
    - -

    The Android 3.0 platform includes an updated set of standard applications that are designed for use on larger screen devices. The sections below highlight some of the new features.

    - -Browser

    - -

    The browser includes new features that let users navigate and organize more efficiently. Multiple tabs replace browser windows and a new “incognito” mode allows anonymous browsing. Bookmarks and history are presented and managed in a single unified view. Users can now choose to automatically sign into Google sites on the browser with a supplied account and sync bookmarks with Google Chrome. New multitouch support is now available to JavaScript and plugins. Users can enjoy a better browsing experience at non-mobile sites through an improved zoom and viewport model, overflow scrolling, support for fixed positioning, and more.

    - -

    Camera and Gallery

    - -

    The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. The Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection.

    - -

    Contacts

    - -

    The Contacts app uses a new two-pane UI and Fast Scroll to let users easily organize and locate contacts. The application offers improved formatting of international phone numbers as user types, based on home country and an international number parsing library. Contact information is presented in a card-like UI, making it easier for users to read and edit contacts.

    - -

    Email

    - -

    The Email application uses a new two-pane UI to make viewing and organizing messages more efficient. The app lets users select one or more messages, then select an action from the Action Bar, such as moving them to a folder. Users can sync attachments for later viewing and keep track of email using a home screen Widget.

    - -
    - - -

    New Developer Features

    - -

    The Android 3.0 platform is designed specially to meet the unique needs of applications on devices with larger screen sizes. It offers all of the tools developers need to create incredible visual and interaction experiences on these devices.

    - - - -

    New UI Framework for creating great tablet apps

    - -
    -
    - - -

    Activity fragments, for greater control of content and design flexibility

    - -

    Starting with Android 3.0, developers can break the Activities of their applications into subcomponents called Fragments, then combine them in a variety of ways to create a richer, more interactive experience. For example, an application can use a set of Fragments to create a true multipane UI, with the user being able to interact with each pane independently. Fragments can be added, removed, replaced, and animated inside an Activity dynamically, and they are modular and reusable across multiple Activities. Because they are modular, Fragments also offer an efficient way for developers to write applications that can run properly on both larger screen as well as smaller screen devices.

    - -
    - -

    Redesigned UI widgets

    - -

    Android 3.0 offers an updated set of UI widgets that developers can use to quickly add new types of content to their applications. The new UI widgets are redesigned for use on larger screens such as tablets and incorporate the new holographic UI theme. Several new widget types are available, including a 3D stack, search box, a date/time picker, number picker, calendar, popup menu, and others. Most of the redesigned UI widgets can now be used as remote views in application widgets displayed on the home screen. Applications written for earlier versions can inherit the new Widget designs and themes.

    - - -
    -
    - -

    Expanded Home screen widgets

    - -

    Home screen widgets are popular with users because they offer fast access to application-specific data directly from the home screen. Android 3.0 lets developers take home screen widgets to the next level, offering more types of content and new modes of interaction with users. Developers can now use more standard UI widget types home screen widgets, including widgets that let users flip through collections of content as 3D stacks, grids, or lists. Users can interact with the home screen widgets in new ways, such as by using touch gestures to scroll and flip the content displayed in a widget.

    - -
    - -

    Persistent Action Bar

    - -

    The platform provides each application with its own instance of the Action Bar at the top of the screen, which the application can use to give the user quick access to contextual options, widgets, status, navigation, and more. The application can also customize the display theme of its Action Bar instance. The Action Bar lets developers expose more features of their applications to users in a familiar location, while also unifying the experience of using an application that spans multiple Activities or states.

    - -

    Richer notifications

    - -

    Notifications are a key part of the Android user experience because they let applications show key updates and status information to users in real time. Android 3.0 extends this capability, letting developers include richer content and control more properties. A new builder class lets developers quickly create notifications that include large and small icons, a title, a priority flag, and any properties already available in previous versions. Notifications can offer more types of content by building on the expanded set of UI Widgets that are now available as remote Views.

    - -
    -
    - -

    Multiselect, clipboard, and drag-and-drop

    - -

    The platform offers convenient new interaction modes that developers can use. For managing collections of items in lists or grids, developers can offer a new multiselect mode that lets users choose multiple items for an action. Developers can also use a new system-wide Clipboard to let users easily copy any type of data into and out of their applications. To make it easier for users to manage and organize files, developers can now add drag-and-drop interaction through a DragEvent framework.

    - -
    - - -

    High-performance 2D and 3D graphics

    - -

    New animation framework

    - -

    The platform includes a flexible new animation framework that lets developers easily animate the properties of UI elements such as Views, Widgets, Fragments, Drawables, or any arbitrary object. Animations can create fades or movement between states, loop an animated image or an existing animation, change colors, and much more. Adding animation to UI elements can add visual interest to an application and refine the user experience, to keep users engaged.

    - -

    Hardware-accelerated 2D graphics

    - -

    Android 3.0 offers a new hardware-accelerated OpenGL renderer that gives a performance boost to many common graphics operations for applications running in the Android framework. When the renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. Developers can control how hardware-acceleration is applied at every level, from enabling it globally in an application to enabling it in specific Activities and Views inside the application.

    - -

    Renderscript 3D graphics engine

    - -

    Renderscript is a runtime 3D framework that provides both an API for building 3D scenes as well as a special, platform-independent shader language for maximum performance. Using Renderscript, you can accelerate graphics operations and data processing. Renderscript is an ideal way to create high-performance 3D effects for applications, wallpapers, carousels, and more.

    - - -

    Support for multicore processor architectures

    - -

    Android 3.0 is the first version of the platform designed to run on either single or multicore processor architectures. A variety of changes in the Dalvik VM, Bionic library, and elsewhere add support for symmetric multiprocessing in multicore environments. These optimizations can benefit all applications, even those that are single-threaded. For example, with two active cores, a single-threaded application might still see a performance boost if the Dalvik garbage collector runs on the second core. The system will arrange for this automatically.

    - - -

    Rich multimedia and connectivity

    - -

    HTTP Live streaming

    - -

    Applications can now pass an M3U playlist URL to the media framework to begin an HTTP Live streaming session. The media framework supports most of the HTTP Live streaming specification, including adaptive bit rate.

    - -

    Pluggable DRM framework

    - -

    Android 3.0 includes an extensible DRM framework that lets applications manage protected content according to a variety of DRM mechanisms that may be available on the device. For application developers, the framework API offers an consistent, unified API that simplifies the management of protected content, regardless of the underlying DRM engines.

    - -

    Digital media file transfer

    - -

    The platform includes built-in support for Media/Picture Transfer Protocol (MTP/PTP) over USB, which lets users easily transfer any type of media files between devices and to a host computer. Developers can build on this support, creating applications that let users create or manage media files that they may want to transfer or share across devices.

    - -

    More types of connectivity

    - -

    The platform offers new connectivity that developers can build on. API support for Bluetooth A2DP and HSP profiles lets applications query Bluetooth profiles for connected devices, audio state, and more, then notify the user. For example, a music application can check connectivity and status and let the user know that music is playing through a stereo headset. Applications can also register to receive system broadcasts of pre-defined vendor-specific AT commands, such as Platronics Xevent. For example, an application could receive broadcasts that indicate a connected device's battery level and could notify the user or take other action as needed. Applications can also take advantage of the platform's new support for full keyboards connected by USB or Bluetooth.

    - - -

    Enhancements for enterprise

    - -

    In Android 3.0, developers of device administration applications can support new types of policies, including policies for encrypted storage, password expiration, password history, and password complex characters required.

    - -

    Compatibility with existing apps

    - -

    Android 3.0 brings a new UI designed for tablets and other larger screen devices, but it also is fully compatible with applications developed for earlier versions of the platform, or for smaller screen sizes. Existing applications can seamlessly participate in the new holographic UI theme without code changes, by adding a single attribute in their manifest files. The platform emulates the Menu key, which is replaced by the overflow menu in the Action Bar in the new UI. Developers wanting to take fuller advantage of larger screen sizes can also create dedicated layouts and assets for larger screens and add them to their existing applications.

    - - -

    More information

    - -
    - - - - - -
    - -

    For more information about the new developer APIs, see the Android 3.0 Platform document.

    - -

    For a video overview of platform features, see the Android 3.0 Sneak Peek.

    diff --git a/docs/html/sdk/android-3.0.jd b/docs/html/sdk/android-3.0.jd deleted file mode 100644 index 3acb35885af8..000000000000 --- a/docs/html/sdk/android-3.0.jd +++ /dev/null @@ -1,1186 +0,0 @@ -page.title=Android 3.0 Platform -sdk.platform.version=3.0 -sdk.platform.apiLevel=11 -@jd:body - -
    - -
    - - -

    API Level: {@sdkPlatformApiLevel}

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a downloadable -component for the Android SDK. The downloadable platform includes an Android library and system -image, as well as a set of emulator skins and more. The downloadable platform includes no external -libraries.

    - -

    To get started developing or testing against Android {@sdkPlatformVersion}, use the Android SDK -Manager to download the platform into your SDK. For more information, see Adding SDK Packages. If you are new to Android, download the SDK Starter Package first.

    - -

    For a high-level introduction to Android {@sdkPlatformVersion}, see the Platform -Highlights.

    - -

    Note: -If you've already published an Android application, please test and optimize your application on -Android 3.0 as soon as possible. You should do so to be sure your application provides the best -experience possible on the latest Android-powered devices. For information about what you can do, -read Supporting Tablets and -Handsets.

    - - -

    Revisions

    - -

    To determine what revision of the Android {@sdkPlatformVersion} platform you have installed, -refer to the "Installed Packages" listing in the Android SDK and AVD Manager.

    - - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 2 (July 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r12 or -higher.

    -
    -
    Notes:
    -
    -

    Improvements to the platform's rendering library to support the visual layout editor in the ADT -Eclipse plugin. This revision allows for more drawing features in ADT and fixes several -bugs in the previous rendering library. It also unlocks several editor features that were added in -ADT 12.

    -
    -
    - -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (February 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r10 or higher.

    -
    -
    - -
    -
    - - - -

    API Overview

    - -

    The sections below provide a technical overview of what's new for developers in Android 3.0, -including new features and changes in the framework API since the previous version.

    - - - - - -

    Fragments

    - -

    A fragment is a new framework component that allows you to separate distinct elements of an -activity into self-contained modules that define their own UI and lifecycle. To create a -fragment, you must extend the {@link android.app.Fragment} class and implement several lifecycle -callback methods, similar to an {@link android.app.Activity}. You can then combine multiple -fragments in a single activity to build a multi-pane UI in which each -pane manages its own lifecycle and user inputs.

    - -

    You can also use a fragment without providing a UI and instead use the fragment as a worker -for the activity, such as to manage the progress of a download that occurs only while the -activity is running.

    - -

    Additionally:

    - - - -

    To manage the fragments in your activity, you must use the {@link -android.app.FragmentManager}, which provides several APIs for interacting with fragments, such -as finding fragments in the activity and popping fragments off the back stack to restore their -previous state.

    - -

    To perform a transaction, such as add or remove a fragment, you must create a {@link -android.app.FragmentTransaction}. You can then call methods such as {@link -android.app.FragmentTransaction#add add()} {@link android.app.FragmentTransaction#remove -remove()}, or {@link android.app.FragmentTransaction#replace replace()}. Once you've applied all -the changes you want to perform for the transaction, you must call {@link -android.app.FragmentTransaction#commit commit()} and the system applies the fragment transaction to -the activity.

    - -

    For more information about using fragments, read the Fragments documentation. Several -samples are also available in the -API Demos application.

    - - - - -

    Action Bar

    - -

    The Action Bar is a replacement for the traditional title bar at the top of the activity window. -It includes the application logo in the left corner and provides a new interface for items in the -Options Menu. Additionally, the -Action Bar allows you to:

    - - - -

    The Action Bar is standard for all applications that use the new holographic theme, which is -also standard when you set either the {@code -android:minSdkVersion} or {@code -android:targetSdkVersion} to {@code "11"}.

    - -

    For more information about the Action Bar, read the Action Bar documentation. Several -samples are also available in the -API Demos application.

    - - - - -

    System clipboard

    - -

    Applications can now copy and paste data (beyond mere text) to and from the system-wide -clipboard. Clipped data can be plain text, a URI, or an intent.

    - -

    By providing the system access to the data you want the user to copy, through a content provider, -the user can copy complex content (such as an image or data structure) from your application and -paste it into another application that supports that type of content.

    - -

    To start using the clipboard, get the global {@link android.content.ClipboardManager} object -by calling {@link android.content.Context#getSystemService getSystemService(CLIPBOARD_SERVICE)}.

    - -

    To copy an item to the clipboard, you need to create a new {@link -android.content.ClipData} object, which holds one or more {@link android.content.ClipData.Item} -objects, each describing a single entity. To create a {@link android.content.ClipData} object -containing just one {@link android.content.ClipData.Item}, you can use one of the helper methods, -such as {@link android.content.ClipData#newPlainText newPlainText()}, {@link -android.content.ClipData#newUri newUri()}, and {@link android.content.ClipData#newIntent -newIntent()}, which each return a {@link android.content.ClipData} object pre-loaded with the -{@link android.content.ClipData.Item} you provide.

    - -

    To add the {@link android.content.ClipData} to the clipboard, pass it to {@link -android.content.ClipboardManager#setPrimaryClip setPrimaryClip()} for your instance of {@link -android.content.ClipboardManager}.

    - -

    You can then read a file from the clipboard (in order to paste it) by calling {@link -android.content.ClipboardManager#getPrimaryClip()} on the {@link -android.content.ClipboardManager}. Handling the {@link android.content.ClipData} you receive can -be complicated and you need to be sure you can actually handle the data type in the clipboard -before attempting to paste it.

    - -

    The clipboard holds only one piece of clipped data (a {@link android.content.ClipData} -object) at a time, but one {@link android.content.ClipData} can contain multiple {@link -android.content.ClipData.Item}s.

    - -

    For more information, read the Copy -and Paste documentation. You can also see a simple implementation of copy and paste in the API Demos -and a more complete implementation in the Note Pad application.

    - - - - -

    Drag and drop

    - -

    New APIs simplify drag and drop operations in your application's user interface. A drag -operation is the transfer of some kind of data—carried in a {@link android.content.ClipData} -object—from one place to another. The start and end point for the drag operation is a {@link -android.view.View}, so the APIs that directly handle the drag and drop operations are -in the {@link android.view.View} class.

    - -

    A drag and drop operation has a lifecycle that's defined by several drag actions—each -defined by a {@link android.view.DragEvent} object—such as {@link -android.view.DragEvent#ACTION_DRAG_STARTED}, {@link android.view.DragEvent#ACTION_DRAG_ENTERED}, and -{@link android.view.DragEvent#ACTION_DROP}. Each view that wants to participate in a drag -operation can listen for these actions.

    - -

    To begin dragging content in your activity, call {@link android.view.View#startDrag startDrag()} -on a {@link android.view.View}, providing a {@link android.content.ClipData} object that represents -the data to drag, a {@link android.view.View.DragShadowBuilder} to facilitate the "shadow" -that users see under their fingers while dragging, and an {@link java.lang.Object} that can share -information about the drag object with views that may receive the object.

    - -

    To accept a drag object in a {@link android.view.View} (receive the "drop"), register the view -with an {@link android.view.View.OnDragListener OnDragListener} by calling {@link -android.view.View#setOnDragListener setOnDragListener()}. When a drag event occurs on the view, the -system calls {@link android.view.View.OnDragListener#onDrag onDrag()} for the {@link -android.view.View.OnDragListener OnDragListener}, which receives a {@link android.view.DragEvent} -describing the type of drag action has occurred (such as {@link -android.view.DragEvent#ACTION_DRAG_STARTED}, {@link android.view.DragEvent#ACTION_DRAG_ENTERED}, and -{@link android.view.DragEvent#ACTION_DROP}). During a drag, the system repeatedly calls {@link -android.view.View.OnDragListener#onDrag onDrag()} for the view underneath the drag, to deliver a -stream of drag events. The receiving view can inquire the event type delivered to {@link -android.view.View#onDragEvent onDragEvent()} by calling {@link android.view.DragEvent#getAction -getAction()} on the {@link android.view.DragEvent}.

    - -

    Note: Although a drag event may carry a {@link -android.content.ClipData} object, this is not related to the system clipboard. A drag and drop -operation should never put the dragged data in the system clipboard.

    - -

    For more information, read the Dragging and -Dropping documentation. You can also see an implementation of drag and drop in the -API Demos application and the Honeycomb Gallery -application.

    - - - -

    App widgets

    - -

    Android 3.0 supports several new widget classes for more interactive app widgets on the users -Home screen, including: {@link android.widget.GridView}, {@link android.widget.ListView}, {@link -android.widget.StackView}, {@link android.widget.ViewFlipper}, and {@link -android.widget.AdapterViewFlipper}.

    - -

    More importantly, you can use the new {@link android.widget.RemoteViewsService} to create app -widgets with collections, using widgets such as {@link android.widget.GridView}, {@link -android.widget.ListView}, and {@link android.widget.StackView} that are backed by remote data, -such as from a content provider.

    - -

    The {@link android.appwidget.AppWidgetProviderInfo} class (defined in XML with an {@code -<appwidget-provider>} element) also supports two new fields: {@link -android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} and {@link -android.appwidget.AppWidgetProviderInfo#previewImage}. The {@link -android.appwidget.AppWidgetProviderInfo#autoAdvanceViewId} field lets you specify the view ID of the -app widget subview that should be auto-advanced by the app widget’s host. The -{@link android.appwidget.AppWidgetProviderInfo#previewImage} field specifies a preview of what the -app widget looks like and is shown to the user from the widget picker. If this field is not -supplied, the app widget's icon is used for the preview.

    - -

    To help create a preview image for your app widget (to specify in the {@link -android.appwidget.AppWidgetProviderInfo#previewImage} field), the Android emulator includes an -application called "Widget Preview." To create a preview image, launch this application, select the -app widget for your application and set it up how you'd like your preview image to appear, then save -it and place it in your application's drawable resources.

    - -

    You can see an implementation of the new app widget features in the StackView App Widget and Weather List Widget -applications.

    - - - -

    Status bar notifications

    - -

    The {@link android.app.Notification} APIs have been extended to support more content-rich status -bar notifications, plus a new {@link android.app.Notification.Builder} class allows you to easily -create {@link android.app.Notification} objects.

    -

    New features include:

    - - - - -

    Content loaders

    - -

    New framework APIs facilitate asynchronous loading of data using the {@link -android.content.Loader} class. You can use it in combination with UI components such as views and -fragments to dynamically load data from worker threads. The {@link -android.content.CursorLoader} subclass is specially designed to help you do so for data backed by -a {@link android.content.ContentProvider}.

    - -

    All you need to do is implement the {@link android.app.LoaderManager.LoaderCallbacks -LoaderCallbacks} interface to receive callbacks when a new loader is requested or the data has -changed, then call {@link android.app.LoaderManager#initLoader initLoader()} to initialize the -loader for your activity or fragment.

    - -

    For more information, read the Loaders documentation. You can also see -example code using loaders in the LoaderCursor -and -LoaderThrottle samples.

    - - - -

    Bluetooth A2DP and headset APIs

    - -

    Android now includes APIs for applications to verify the state of connected Bluetooth A2DP and -headset profile devices. For example, applications can identify when a Bluetooth headset is -connected for listening to music and notify the user as appropriate. Applications can also receive -broadcasts for vendor specific AT commands and notify the user about the state of the connected -device, such as when the connected device's battery is low.

    - -

    You can initialize the respective {@link android.bluetooth.BluetoothProfile} by calling {@link -android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()} with either the {@link -android.bluetooth.BluetoothProfile#A2DP} or {@link android.bluetooth.BluetoothProfile#HEADSET} -profile constant and a {@link android.bluetooth.BluetoothProfile.ServiceListener} to receive -callbacks when the Bluetooth client is connected or disconnected.

    - - - - -

    Animation framework

    - -

    An all new flexible animation framework allows you to animate arbitrary properties of any object -(View, Drawable, Fragment, Object, or anything else). It allows you to define several aspects of an -animation, such as:

    - - -

    You can define these animation aspects, and others, for an object's int, float, and hexadecimal -color values, by default. That is, when an object has a property field for one of these types, you -can change its value over time to affect an animation. To animate any other type of value, you tell -the system how to calculate the values for that given type, by implementing the {@link -android.animation.TypeEvaluator} interface.

    - -

    There are two animators you can use to animate the values of a property: {@link -android.animation.ValueAnimator} and {@link android.animation.ObjectAnimator}. The {@link -android.animation.ValueAnimator} computes the animation values, but is not aware of the specific -object or property that is animated as a result. It simply performs the calculations, and you must -listen for the updates and process the data with your own logic. The {@link -android.animation.ObjectAnimator} is a subclass of {@link android.animation.ValueAnimator} and -allows you to set the object and property to animate, and it handles all animation work. -That is, you give the {@link android.animation.ObjectAnimator} the object to animate, the -property of the object to change over time, and a set of values to apply to the property over -time, then start the animation.

    - -

    Additionally, the {@link android.animation.LayoutTransition} class enables automatic transition -animations for changes you make to your activity layout. To enable transitions for part of the -layout, create a {@link android.animation.LayoutTransition} object and set it on -any {@link android.view.ViewGroup} by calling {@link -android.view.ViewGroup#setLayoutTransition setLayoutTransition()}. This causes default -animations to run whenever items are added to or removed from the group. To specify custom -animations, call {@link android.animation.LayoutTransition#setAnimator setAnimator()} on the {@link -android.animation.LayoutTransition} and provide a custom {@link android.animation.Animator}, -such as a {@link android.animation.ValueAnimator} or {@link android.animation.ObjectAnimator} -discussed above.

    - -

    For more information, see the Property Animation documentation. You can -also see several samples using the animation APIs in the API -Demos application.

    - - - - -

    Extended UI framework

    - - - - - -

    Graphics

    - -
    - - - - -

    Media

    - - - - - - -

    Keyboard support

    - - - - - - -

    Split touch events

    - -

    Previously, only a single view could accept touch events at one time. Android 3.0 -adds support for splitting touch events across views and even windows, so different views can accept -simultaneous touch events.

    - -

    Split touch events is enabled by default when an application targets -Android 3.0. That is, when the application has set either the {@code android:minSdkVersion} -or {@code -android:targetSdkVersion} attribute's value to {@code "11"}.

    - -

    However, the following properties allow you to disable split touch events across views inside -specific view groups and across windows.

    - - - - - -

    WebKit

    - - - - - -

    Browser

    - -

    The Browser application adds the following features to support web applications:

    - - - - - -

    JSON utilities

    - -

    New classes, {@link android.util.JsonReader} and {@link android.util.JsonWriter}, help you -read and write JSON streams. The new APIs complement the {@link org.json} classes, which manipulate -a document in memory.

    - -

    You can create an instance of {@link android.util.JsonReader} by calling -its constructor method and passing the {@link java.io.InputStreamReader} that feeds the JSON string. -Then begin reading an object by calling {@link android.util.JsonReader#beginObject()}, read a -key name with {@link android.util.JsonReader#nextName()}, read the value using methods -respective to the type, such as {@link android.util.JsonReader#nextString()} and {@link -android.util.JsonReader#nextInt()}, and continue doing so while {@link -android.util.JsonReader#hasNext()} is true.

    - -

    You can create an instance of {@link android.util.JsonWriter} by calling its constructor and -passing the appropriate {@link java.io.OutputStreamWriter}. Then write the JSON data in a manner -similar to the reader, using {@link android.util.JsonWriter#name name()} to add a property name -and an appropriate {@link android.util.JsonWriter#value value()} method to add the respective -value.

    - -

    These classes are strict by default. The {@link android.util.JsonReader#setLenient setLenient()} -method in each class configures them to be more liberal in what they accept. This lenient -parse mode is also compatible with the {@link org.json}'s default parser.

    - - - - -

    New feature constants

    - -

    The {@code <uses-feature>} -manfest element should be used to inform external entities (such as Google Play) of the set of -hardware and software features on which your application depends. In this release, Android adds the -following new constants that applications can declare with this element:

    - - - - - - -

    New permissions

    - - - - - -

    New platform technologies

    - - - - - -

    API differences report

    - -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level -{@sdkPlatformApiLevel}), see the API Differences Report.

    - - - - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, -you need compile the application against the Android library that is provided in -the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you might -also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" -attribute to the <uses-sdk> element in the application's -manifest. If your application is designed to run only on Android 2.3 and higher, -declaring the attribute prevents the application from being installed on earlier -versions of the platform.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • API Demos
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Clock
    • -
    • Contacts
    • -
    • Custom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    -
    -
      -
    • Gallery
    • -
    • Gestures Builder
    • -
    • Messaging
    • -
    • Music
    • -
    • Search
    • -
    • Settings
    • -
    • Spare Parts
    • -
    • Speech Recorder
    • -
    • Widget Preview
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android 3.0 system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian bokmål, Norway (nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes the following emulator skin:

    - - - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    \ No newline at end of file diff --git a/docs/html/sdk/android-3.1-highlights.jd b/docs/html/sdk/android-3.1-highlights.jd deleted file mode 100644 index 88bc1eec0c55..000000000000 --- a/docs/html/sdk/android-3.1-highlights.jd +++ /dev/null @@ -1,380 +0,0 @@ -page.title=Android 3.1 Platform Highlights - -@jd:body - - - - -

    Welcome to Android 3.1!

    - -

    Android 3.1 is an incremental platform release that refines many of the -features introduced in Android 3.0. It builds on the same tablet-optimized UI -and features offered in Android 3.0 and adds several new capabilities for -users and developers. This document provides an overview of the new features and -technologies introduced in Android 3.1. For a more detailed look at new -developer APIs, see the API -Overview document.

    - -

    For a high-level introduction to Android 3.0, please see the Android 3.0 Platform -Highlights.

    - - - -

    New User Features

    - -
    -
    -
    Figure 1. An Android 3.1 Home screen.
    -
    - -

    UI refinements

    - -

    The Android 3.1 platform adds a variety of refinements to make the user -interface more intuitive and more efficient to use.

    - -

    UI transitions are improved throughout the system and across the standard -apps. The Launcher animation is optimized for faster, smoother transition to and -from the Apps list. Adjustments in color, positioning, and text make UI elements -easier to see, understand, and use. Accessibility is improved with consistent -audible feedback throughout the UI and a new setting to let users customize the -touch-hold interval to meet their needs.

    - -

    Navigation to and from the five home screens is now easier — touching -the Home button in the system bar now takes you to the home screen most recently -used. Settings offers an improved view of internal storage, -showing the storage used by a larger set of file types.

    - -

    Connectivity for USB accessories

    - -

    Android 3.1 adds broad platform support for a variety of USB-connected -peripherals and accessories. Users can attach many types of input devices -(keyboards, mice, game controllers) and digital cameras. Applications can build -on the platform’s USB support to extend connectivity to almost any type of USB -device.

    - -

    The platform also adds new support for USB accessories — external -hardware devices designed to attach to Android-powered devices as USB hosts. When an -accessory is attached, the framework will look for a corresponding application -and offer to launch it for the user. The accessory can also present a URL -to the user, for downloading an appropriate application if one is not already -installed. Users can interact with the application to control powered accessories such -as robotics controllers; docking stations; diagnostic and musical equipment; -kiosks; card readers; and much more.

    - -

    The platform’s USB capabilities rely on components in device hardware, so -support for USB on specific devices may vary and is determined by device -manufacturers.

    - -
    -
    -
    Figure 2. The Recent Apps menu is now expandable and scrollable.
    -
    - -

    Expanded Recent Apps list

    - -

    For improved multitasking and instant visual access to a much larger number -of apps, the Recent Apps list is now expandable. Users can now scroll the list -of recent apps vertically to see thumbnail images all of the tasks in progress -and recently used apps, then touch a thumbnail to jump back into that task.

    - -

    Resizeable Home screen widgets

    - -

    For more flexible Home screen customization, users can now resize their Home -screen widgets using drag bars provided by the system. Users can expand widgets -both horizontally and/or vertically to include more content, where supported by -each widget.

    - - -

    Support for external keyboards -and pointing devices

    - -

    Users can now attach almost any type of external keyboard or mouse to their -Android-powered devices, to create a familiar environment and work more -efficiently. One or more input devices can be attached to the system simultaneously -over USB and/or Bluetooth HID, in any combination. No special configuration or -driver is needed, in most cases. When multiple devices are connected, users can -conveniently manage the active keyboard and IME using the keyboard settings that -are available from the System bar.

    - -

    For pointing devices, the platform supports most types of mouse with a single -button and optionally a scroll wheel, as well as similar devices such as -trackballs. When these are connected, users can interact with the UI using -point, select, drag, scroll, hover, and other standard actions.

    - -

    Support for joysticks and gamepads

    - -

    To make the platform even better for gaming, Android 3.1 adds support for -most PC joysticks and gamepads that are connected over USB or Bluetooth HID.

    - -

    For example, users can connect PlayStation®3 and Xbox 360® -game controllers over USB (but not Bluetooth), Logitech Dual Action™ gamepads and -flight sticks, or a car racing controller. Game controllers that use proprietary -networking or pairing are not supported by default, but in general, the platform -supports most PC-connectible joysticks and gamepads.

    - -

    Robust Wi-Fi networking

    - -

    Android 3.1 adds robust Wi-Fi features, to make sure that users and their -apps can take full advantage of higher-speed Wi-Fi access at home, at work, and -while away.

    - -

    A new high-performance Wi-Fi lock lets applications maintain -high-performance Wi-Fi connections even when the device screen is off. Users can -take advantage of this to play continuous streamed music, video, and voice -services for long periods, even when the device is otherwise idle and the screen -is off.

    - -

    Users can now configure an HTTP proxy for each individual Wi-Fi access -point, by touch-hold of the access point in Settings. The browser uses the HTTP -proxy when communicating with the network over the access point and other apps -may also choose to do so. The platform also provides backup and restore of the -user-defined IP and proxy settings.

    -

    The platform adds support for Preferred Network Offload (PNO), a background -scanning capability that conserves battery power savings in cases where Wi-Fi -needs to be available continuously for long periods of time.

    - -

    Updated set of standard apps

    - -

    The Android 3.1 platform includes an updated set of standard applications -that are optimized for use on larger screen devices. The sections below -highlight some of the new features.

    - -
    -
    -
    Figure 3. Quick Controls menu in the Browser.
    -
    -
    - -

    Browser

    - -

    The Browser app includes a variety of new features and UI improvements that -make viewing web content simpler, faster, and more convenient.

    - -

    The Quick Controls UI, accessible from Browser Settings, is extended and -redesigned. Users can now use the controls to view thumbnails of open tabs and -close the active tab, as well as access the overflow menu for instant access to -Settings and other controls.

    - -

    To ensure a consistent viewing experience, the Browser extends it's support -for popular web standards such as CSS 3D, animations, and CSS fixed -positioning to all sites, mobile or desktop. It also adds support for embedded -playback of HTML5 video content. To make it easier to manage favorite -content, users can now save a web page locally for offline viewing, including -all styling and images. For convenience when visiting Google sites, an improved -auto-login UI lets users sign in quickly and manage access when multiple users -are sharing a device.

    - -

    For best performance, the Browser adds support for plugins that use hardware -accelerated rendering. Page zoom performance is also dramatically improved, -making it faster to navigate and view web pages.

    - -

    Gallery

    - -

    The Gallery app now supports Picture Transfer Protocol (PTP), so that users -can connect their cameras over USB and import their pictures to Gallery with a -single touch. The app also copies the pictures to local storage and provides an -indicator to let users see how much space is available.

    - -
    -
    -
    Figure -4. Home screen widgets can now be resized.
    - -

    Calendar

    - -

    Calendar grids are larger, for better readability and more accurate -touch-targeting. Additionally, users can create a larger viewing area for grids -by hiding the calendar list controls. Controls in the date picker are -redesigned, making them easier to see and use. - - -

    Contacts

    - -

    The Contacts app now lets you locate contacts more easily using full text -search. Search returns matching results from all fields that are stored for a -contact. -

    - -

    Email

    - -

    When replying or forwarding an HTML message, The Email app now sends both -plain text and HTML bodies as a multi-part mime message. This ensures that the -message will be formatted properly for all recipients. Folder prefixes for IMAP -accounts are now easier to define and manage. To conserve battery power and -minimize cell data usage, the application now prefetches email from the server -only when the device is connected to a Wi-Fi access point.

    - -

    An updated Home screen widget give users quick access to more email. Users -can touch Email icon at the top of the widget to cycle through labels such as -Inbox, Unread, and Starred. The widget itself is now resizable, both -horizontally and vertically.

    - -

    Enterprise support

    - -

    Users can now configure an HTTP proxy for each connected Wi-Fi access point. -This lets administrators work with users to set a proxy hostname, port, and any -bypass subdomains. This proxy configuration is automatically used by the Browser -when the Wi-Fi access point is connected, and may optionally be used by other -apps. The proxy and IP configuration is now backed up and restored across system -updates and resets.

    - -

    To meet the needs of tablet users, the platform now allows a "encrypted -storage card" device policy to be accepted on devices with emulated storage -cards and encrypted primary storage.

    - - -

    New Developer Features

    - -

    The Android 3.1 platform adds refinements and new capabilities that -developers can build on, to create powerful and engaging application experiences -on tablets and other large-screen devices.

    - -

    Open Accessory API for rich interaction with -peripherals

    - -

    Android 3.1 introduces a new API for integrating hardware accessories with -applications running on the platform. The API provides a way to interact across -a wide range of peripherals, from robotics controllers to musical equipment, -exercise bicycles, and more.

    - -

    The API is based on a new USB (Universal Serial Bus) stack and services -that are built into the platform. The platform provides services for discovering -and identifying connected hardware, as well as for notifying interested -applications that the hardware is available.

    - -

    When a user plugs in a USB accessory, the platform receives -identifying information such as product name, accessory type, manufacturer, and -version. The platform sets up communication with the accessory and uses its -information to notify and launch a targeted app, if one is available. Optionally, -an accessory can provide a URL that lets users find and download an -app that works with the accessory. These discovery features make -first-time setup easier for the user and ensure that an appropriate application -is available for interacting with the connected hardware.

    - -

    For application developers and accessory manufacturers, accessory mode offers -many new ways to engage users and build powerful interaction experiences with -connected hardware.

    - -

    To learn more about how to develop applications that interact with -accessories, see the USB -Accessory documentation.

    - -

    USB host API

    - -

    Android 3.1 provides built-in platform support for USB host mode and exposes -an API that lets applications manage connected peripherals. On devices that -support host mode, applications can use the API to identify and communicate with -connected devices such as audio devices. input devices, communications devices, -hubs, cameras, and more.

    - -

    To learn more about how to develop applications that interact with -USB devices, see the USB -Host documentation.

    - -

    Input from mice, joysticks, and gamepads

    - -

    Android 3.1 extends the input event system to support a variety of new input -sources and motion events, across all views and windows. Developers can build on -these capabilities to let users interact with their applications using mice, -trackballs, joysticks, gamepads, and other devices, in addition to keyboards and -touchscreens.

    - -

    For mouse and trackball input, the platform supports two new motion event -actions: scroll (horizontal or vertical) such as from a scrollwheel; and hover, -which reports the location of the mouse when no buttons are pressed. -Applications can handle these events in any way needed.

    - -

    For joysticks and gamepads, the platform provides a large number of motion -axes that applications can use from a given input source, such as X, Y, Hat X, -Hat Y, rotation, throttle, pressure, size, touch, tool, orientation, and others. -Developers can also define custom axes if needed, to capture motion in -additional ways. The platform provides motion events to applications as a batch, -and applications can query the details of the movements included in the batch, -for more efficient and precise handling of events.

    - -

    Applications can query for the list of connected input devices and the motion -ranges (axes) supported by each device. Applications can also handle multiple -input and motion events from a single input device. For example, an application -can use mouse and joystick and mouse event sources from a single input -device.

    - -

    Resizable Home screen widgets

    - -

    Developers can now create Home screen widgets that users can resize -horizontally, vertically, or both. By simply adding an attribute to the -declaration of a widget, the widget becomes resizable horizontally, vertically, -or both. This lets users customize the display of the widget content and display -more of it on their Home screens.

    - -

    MTP API for integrating with external cameras

    - -

    In Android 3.1, a new MTP (Media Transfer Protocol) API lets developers write -apps that interact directly with connected cameras and other PTP devices. The -new API makes it easy for applications to receive notifications when devices are -attached and removed, manage files and storage on those devices, and transfer -files and metadata to and from them. The MTP API implements the PTP (Picture -Transfer Protocol) subset of the MTP specification.

    - -

    RTP API, for control over audio streaming sessions

    - -

    Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) -stack, which applications can use to directly manage on-demand or interactive -data streaming. In particular, apps that provide VOIP, push-to-talk, -conferencing, and audio streaming can use the API to initiate sessions and -transmit or receive data streams over any available network.

    - -

    Performance optimizations

    - -

    Android 3.1 includes a variety of performance optimizations that help make -applications faster and more responsive. Some of the optimizations include:

    - -
      -
    • A new LRU cache class lets applications benefit from efficient caching. -Applications can use the class to reduce the time spent computing or downloading -data from the network, while maintaining a sensible memory footprint for the -cached data.
    • -
    • The UI framework now supports partial invalidates in hardware-accelerated -Views, which makes drawing operations in those Views more efficient.
    • -
    • A new graphics method, {@link android.graphics.Bitmap#setHasAlpha(boolean) -setHasAlpha()}, allows apps to hint that a given bitmap is opaque. This provides -an extra performance boost for some types of blits and is especially useful for -applications that use ARGB_8888 bitmaps.
    • -
    - diff --git a/docs/html/sdk/android-3.1.jd b/docs/html/sdk/android-3.1.jd deleted file mode 100644 index 7ec7e331b982..000000000000 --- a/docs/html/sdk/android-3.1.jd +++ /dev/null @@ -1,1106 +0,0 @@ -page.title=Android 3.1 Platform -sdk.platform.version=3.1 -sdk.platform.apiLevel=12 -@jd:body - -
    - -
    - - -

    API Level: {@sdkPlatformApiLevel}

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes -an Android library and system image, as well as a set of emulator skins and -more. The downloadable platform includes no external libraries.

    - -

    To get started developing or testing against Android {@sdkPlatformVersion}, -use the Android SDK Manager to download the platform into your SDK. For more -information, see Adding SDK -Components. If you are new to Android, download the SDK Starter Package first.

    - -

    For a high-level introduction to Android {@sdkPlatformVersion}, see the Platform -Highlights.

    - -

    Reminder: If you've already published an -Android application, please test and optimize your application on Android 3.0 -and Android 3.1 as soon as possible. You should do so to be sure your -application provides the best experience possible on the latest Android-powered -devices. For information about what you can do, read Optimizing Apps for -Android 3.0.

    - - -

    Revisions

    - -

    To determine what revision of the Android {@sdkPlatformVersion} platform you -have installed, refer to the "Installed Packages" listing in the Android SDK and -AVD Manager.

    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 3 (July 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r12 or -higher.

    -
    -
    Notes:
    -
    -

    Improvements to the platform's rendering library to support the visual layout editor in the ADT -Eclipse plugin. This revision allows for more drawing features in ADT and fixes several -bugs in the previous rendering library. It also unlocks several editor features that were added in -ADT 12.

    -
    -
    - -
    -
    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 2 (May 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r11 or -higher.

    -
    -
    Notes:
    -
    -

    Fixes an issue with the visual layout editor rendering library that prevented Android 3.1 from -running in ADT.

    -
    -
    - -
    -
    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (May 2011) -

    - -
    - -
    -
    Dependencies:
    -
    -

    Requires SDK Tools r11 or -higher.

    -
    -
    - -
    -
    - - -

    API Overview

    - -

    The sections below provide a technical overview of what's new for developers -in Android 3.1, including new features and changes in the framework API since -the previous version.

    - -

    USB APIs

    - -

    Android 3.1 introduces powerful new APIs for -integrating connected peripherals with applications running on the platform. -The APIs are based on a USB (Universal Serial Bus) stack and services that are -built into the platform, including support for both USB host and device -interactions. Using the APIs, developers can create applications that are able to -discover, communicate with, and manage a variety of device types connected over -USB.

    - -

    The stack and APIs distinguish two basic types of USB hardware, based on -whether the Android-powered device is acting as host or the external hardware -is acting as host:

    - -
      -
    • A USB device is a piece of connected hardware that depends on the -Android-powered device to serve as host. For example, most input devices, mice, -and joysticks are USB devices, as are many cameras, hubs, and so on.
    • -
    • A USB accessory is a piece of connected hardware that has a USB -host controller, provides power, and is designed to communicate with -Android-powered devices over USB, A variety of peripherals can connect as -accessories, from robotics controllers to musical equipment, exercise bicycles, -and more.
    • -
    - -

    For both types — USB devices and USB accessories — the -platform's USB APIs support discovery by intent broadcast when attached or -detached, as well as standard interfaces, endpoints, and transfer modes -(control, bulk, and interrupt).

    - -

    The USB APIs are available in the package {@link android.hardware.usb}. The -central class is {@link android.hardware.usb.UsbManager}, which provides -helper methods for identifying and communicating with -both USB devices and USB accessories. Applications can acquire an instance of -{@link android.hardware.usb.UsbManager} and then query for the list of attached -devices or accessories and then communicate with or manage them. -{@link android.hardware.usb.UsbManager} also declares intent actions that the -system broadcasts, to announce when a USB device or accessory is attached or -detached.

    - -

    Other classes include:

    - -
      -
    • {@link android.hardware.usb.UsbDevice}, a class representing external -hardware connected as a USB device (with the Android-powered device acting as -host).
    • -
    • {@link android.hardware.usb.UsbAccessory}, representing external hardware -connected as the USB host (with the Android-powered device acting as a USB -device).
    • -
    • {@link android.hardware.usb.UsbInterface} and {@link -android.hardware.usb.UsbEndpoint}, which provide access to standard USB -interfaces and endpoints for a device.
    • -
    • {@link android.hardware.usb.UsbDeviceConnection} and {@link -android.hardware.usb.UsbRequest}, for sending and receiving data and control -messages to or from a USB device, sychronously and asynchronously. -
    • {@link android.hardware.usb.UsbConstants}, which provides constants for -declaring endpoint types, device classes, and so on.
    • -
    - -

    Note that although the USB stack is built into the platform, actual support -for USB host and open accessory modes on specific devices is determined by -their manufacturers. In particular, host mode relies on appropriate USB -controller hardware in the Android-powered device.

    - -

    Additionally, developers can request filtering on Google Play, such that -their applications are not availabe to users whose devices do not provide the -appropriate USB support. To request filtering, add one or both of the elements -below to the application manifest, as appropriate:

    - -
      -
    • If the application should only be visible to devices that support USB -host mode (connection of USB devices), declare this element: -

      <uses-feature - android:name="android.hardware.usb.host" - android:required="true">

      -
    • -
    • If the application should only be visible to devices that support USB -accessories (connection of USB hosts), declare this element: -

      <uses-feature - android:name="android.hardware.usb.accessory" - android:required="true">

      -
    • -
    - -

    For complete information about how to develop applications that interact with -USB accessories, please see the -developer documentation.

    - -

    To look at sample applications that use the USB host API, see ADB Test and Missile -Launcher

    - -

    MTP/PTP API

    - -

    Android 3.1 exposes a new MTP API that lets applications interact directly -with connected cameras and other PTP devices. The new API makes it easy for an -application to receive notifications when devices are attached and removed, -manage files and storage on those devices, and transfer files and metadata to -and from them. The MTP API implements the PTP (Picture Transfer Protocol) subset -of the MTP (Media Transfer Protocol) specification.

    - -

    The MTP API is available in the {@link android.mtp} package and provides -these classes:

    - -
      -
    • The {@link android.mtp.MtpDevice} encapsulates an MTP device that is -connected over the USB host bus. An application can instantiate an object of -this type and then use its methods to get information about the device and -objects stored on it, as well as opening the connection and transferring data. -Some of the methods include: -
        -
      • {@link android.mtp.MtpDevice#getObjectHandles(int, int, int) -getObjectHandles()} returns a list of handles for all objects on the device that -match a specified format and parent. To get information about an object, an -application can pass a handle to {@link android.mtp.MtpDevice#getObjectInfo(int) -getObjectInfo()}.
      • -
      • {@link android.mtp.MtpDevice#importFile(int, java.lang.String) -importFile()} lets an application copy data for an object to a file in external -storage. This call may block for an arbitrary amount of time depending on the -size of the data and speed of the devices, so should be made from a spearate -thread.
      • -
      • {@link -android.mtp.MtpDevice#open(android.hardware.usb.UsbDeviceConnection) open()} -lets an application open a connected MTP/PTP device.
      • -
      • {@link android.mtp.MtpDevice#getThumbnail(int) getThumbnail()} returns -the thumbnail of the object as a byte array.
      • -
      -
    • -
    • {@link android.mtp.MtpStorageInfo} holds information about about a storage -unit on an MTP device, corresponding to the StorageInfo Dataset described in -section 5.2.2 of the MTP specification. Methods in the class let an application -get a storage unit’s description string, free space, maximum storage capacity, -storage ID, and volume identifier.
    • -
    • {@link android.mtp.MtpDeviceInfo} holds information about an MTP device -corresponding to the DeviceInfo Dataset described in section 5.1.1 of the MTP -specification. Methods in the class let applications get a device’s -manufacturer, model, serial number, and version.
    • -
    • {@link android.mtp.MtpObjectInfo} holds information about an object stored -on an MTP device, corresponding to the ObjectInfo Dataset described in section -5.3.1 of the MTP specification. Methods in the class let applications get an -object’s size, data format, association type, creation date, and thumbnail -information.
    • -
    • {@link android.mtp.MtpConstants} provides constants for declaring MTP file -format codes, association type, and protection status.
    • -
    - -

    Support for new input devices and motion events

    - -

    Android 3.1 extends the input subsystem to support new input devices and new -types of motion events, across all views and windows. Developers can build on -these capabilities to let users interact with their applications using mice, -trackballs, joysticks, gamepads, and other devices, in addition to keyboards and -touchscreens.

    - -

    For handling mouse, scrollwheel, and trackball input, the platform supports -two new motion event actions:

    -
      -
    • {@link android.view.MotionEvent#ACTION_SCROLL}, which describes the pointer -location at which a non-touch scroll motion, such as from a mouse scroll wheel, -took place. In the MotionEvent, the value of the {@link -android.view.MotionEvent#AXIS_HSCROLL} and {@link -android.view.MotionEvent#AXIS_VSCROLL} axes specify the relative scroll -movement.
    • -
    • {@link android.view.MotionEvent#ACTION_HOVER_MOVE}, reports the current -position of the mouse when no buttons are pressed, as well as any intermediate -points since the last HOVER_MOVE event. Hover enter and exit -notifications are not yet supported.
    • -
    - -

    To support joysticks and gamepads, the {@link android.view.InputDevice} class -includes these new input device sources:

    -
      -
    • {@link android.view.InputDevice#SOURCE_CLASS_JOYSTICK} — the source -device has joystick axes.
    • -
    • {@link android.view.InputDevice#SOURCE_CLASS_BUTTON} — the source -device has buttons or keys.
    • -
    • {@link android.view.InputDevice#SOURCE_GAMEPAD} — the source device -has gamepad buttons such as {@link android.view.KeyEvent#KEYCODE_BUTTON_A} -or {@link android.view.KeyEvent#KEYCODE_BUTTON_B}. Implies -{@link android.view.InputDevice#SOURCE_CLASS_BUTTON}
    • -
    • {@link android.view.InputDevice#SOURCE_JOYSTICK} — the source device -has joystick axes. Implies SOURCE_CLASS_JOYSTICK.
    • -
    - -

    To describe motion events from these new sources, as well as those from mice -and trackballs, the platform now defines axis codes on {@link -android.view.MotionEvent}, similar to how it defines key codes on {@link -android.view.KeyEvent}. New axis codes for joysticks -and game controllers include -{@link android.view.MotionEvent#AXIS_HAT_X}, {@link -android.view.MotionEvent#AXIS_HAT_Y}, {@link -android.view.MotionEvent#AXIS_RTRIGGER}, {@link -android.view.MotionEvent#AXIS_ORIENTATION}, {@link -android.view.MotionEvent#AXIS_THROTTLE}, and many others. -Existing {@link android.view.MotionEvent} axes are represented by {@link -android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, -{@link android.view.MotionEvent#AXIS_PRESSURE}, {@link -android.view.MotionEvent#AXIS_SIZE}, {@link -android.view.MotionEvent#AXIS_TOUCH_MAJOR}, {@link -android.view.MotionEvent#AXIS_TOUCH_MINOR}, {@link -android.view.MotionEvent#AXIS_TOOL_MAJOR}, {@link -android.view.MotionEvent#AXIS_TOOL_MINOR}, and {@link -android.view.MotionEvent#AXIS_ORIENTATION}.

    - -

    Additionally, {@link android.view.MotionEvent} defines a number of generic -axis codes that are used when the framework does not know how to map a -particular axis. Specific devices can use the generic axis codes to pass custom -motion data to applications. For a full list of axes and their intended -interpretations, see the {@link android.view.MotionEvent} class documentation. -

    - -

    The platform provides motion events to applications in batches, so a single -event may contain a current position and multiple so-called historical movements. -Applications should use {@link android.view.MotionEvent#getHistorySize()} to get -the number of historical samples, then retrieve and process all historical -samples in order using {@link -android.view.MotionEvent#getHistoricalAxisValue(int, int, int) -getHistoricalAxisValue()}. After that, applications should process the current -sample using {@link android.view.MotionEvent#getAxisValue(int) getAxisValue()}. -

    - -

    Some axes can be retrieved using special accessor methods. For example, -instead of calling {@link android.view.MotionEvent#getAxisValue(int) -getAxisValue()}, applications can call {@link android.view.MotionEvent#getX(int) -getX()}. Axes that have built-in accessors include {@link -android.view.MotionEvent#AXIS_X}, {@link android.view.MotionEvent#AXIS_Y}, -{@link android.view.MotionEvent#AXIS_PRESSURE}, {@link -android.view.MotionEvent#AXIS_SIZE}, {@link -android.view.MotionEvent#AXIS_TOUCH_MAJOR}, {@link -android.view.MotionEvent#AXIS_TOUCH_MINOR}, {@link -android.view.MotionEvent#AXIS_TOOL_MAJOR}, {@link -android.view.MotionEvent#AXIS_TOOL_MINOR}, and {@link -android.view.MotionEvent#AXIS_ORIENTATION}.

    - -

    Each input device has a unique, system-assigned ID and may also provide -multiple sources. When a device provides multiple sources, more than one source -can provide axis data using the same axis. For example, a touch event coming -from the touch source uses the X axis for screen position data, while a joystick -event coming from the joystick source will use the X axis for the stick position -instead. For this reason, it's important for applications to interpret axis -values according to the source from which they originate. When handling a motion -event, applications should use methods on the {@link android.view.InputDevice} -class to determine the axes supported by a device or source. Specifically, -applications can use {@link android.view.InputDevice#getMotionRanges() -getMotionRanges()} to query for all axes of a device or all axes of a given -source of the device. In both cases, the range information for axes returned in -the {@link android.view.InputDevice.MotionRange} object specifies the source for -each axis value.

    - -

    Finally, since the motion events from joysticks, gamepads, mice, and -trackballs are not touch events, the platform adds a new callback method for -passing them to a {@link android.view.View} as "generic" motion events. -Specifically, it reports the non-touch motion events to -{@link android.view.View}s through a call to {@link -android.view.View#onGenericMotionEvent(android.view.MotionEvent) -onGenericMotionEvent()}, rather than to {@link -android.view.View#onTouchEvent(android.view.MotionEvent) -onTouchEvent()}.

    - -

    The platform dispatches generic motion events differently, depending on the -event source class. {@link android.view.InputDevice#SOURCE_CLASS_POINTER} events -go to the {@link android.view.View} under the pointer, similar to how touch -events work. All others go to the currently focused {@link android.view.View}. -For example, this means a {@link android.view.View} must take focus in order to -receive joystick events. If needed, applications can handle these events at the -level of Activity or Dialog by implementing {@link -android.view.View#onGenericMotionEvent(android.view.MotionEvent) -onGenericMotionEvent()} there instead.

    - -

    To look at a sample application that uses joystick motion -events, see GameControllerInput -and GameView.

    - -

    RTP API

    - -

    Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) -stack, which applications can use to manage on-demand or interactive data -streaming. In particular, apps that provide VOIP, push-to-talk, conferencing, -and audio streaming can use the API to initiate sessions and transmit or receive -data streams over any available network.

    - -

    The RTP API is available in the {@link android.net.rtp} package. Classes -include:

    -
      -
    • {@link android.net.rtp.RtpStream}, the base class of streams that send and -receive network packets with media payloads over RTP.
    • -
    • {@link android.net.rtp.AudioStream}, a subclass of {@link -android.net.rtp.RtpStream} that carries audio payloads over RTP.
    • -
    • {@link android.net.rtp.AudioGroup}, a local audio hub for managing and -mixing the device speaker, microphone, and {@link android.net.rtp.AudioStream}.
    • -
    • {@link android.net.rtp.AudioCodec}, which holds a collection of codecs that -you define for an {@link android.net.rtp.AudioStream}.
    • -
    - -

    To support audio conferencing and similar usages, an application instantiates -two classes as endpoints for the stream:

    - -
      -
    • {@link android.net.rtp.AudioStream} specifies a remote endpoint and consists -of network mapping and a configured {@link android.net.rtp.AudioCodec}.
    • -
    • {@link android.net.rtp.AudioGroup} represents the local endpoint for one -or more {@link android.net.rtp.AudioStream}s. The {@link android.net.rtp.AudioGroup} mixes -all the {@link android.net.rtp.AudioStream}s and optionally interacts with the device -speaker and the microphone at the same time.
    • -
    - -

    The simplest usage involves a single remote endpoint and local endpoint. -For more complex usages, please refer to the limitations described for -{@link android.net.rtp.AudioGroup}.

    - -

    To use the RTP API, applications must request permission from the user by -declaring <uses-permission -android:name="android.permission.INTERNET"> -in their manifest files. To acquire the device microphone, the <uses-permission -android:name="android.permission.RECORD_AUDIO"> permission is also required.

    - -

    Resizable app widgets

    - -

    Starting in Android 3.1, developers can make their homescreen widgets -resizeable — horizontally, vertically, or on both axes. Users touch-hold a -widget to show its resize handles, then drag the horizontal and/or vertical -handles to change the size on the layout grid.

    - -

    Developers can make any Home screen widget resizeable by defining a -resizeMode attribute in the widget's {@link -android.appwidget.AppWidgetProviderInfo} metadata. Values for the -resizeMode attribute include "horizontal", "vertical", and "none". -To declare a widget as resizeable horizontally and vertically, supply the value -"horizontal|vertical". - -

    Here's an example:

    - -
    <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    -    android:minWidth="294dp"
    -    android:minHeight="72dp"
    -    android:updatePeriodMillis="86400000"
    -    android:previewImage="@drawable/preview"
    -    android:initialLayout="@layout/example_appwidget"
    -    android:configure="com.example.android.ExampleAppWidgetConfigure"
    -    android:resizeMode="horizontal|vertical" >
    -</appwidget-provider>
    - -

    For more information about Home screen widgets, see the App Widgets -documentation.

    - -

    Animation framework

    - -
      -
    • New ViewPropertyAnimator class -
        -
      • A new {@link android.view.ViewPropertyAnimator} class provides a -convenient -way for developers to animate select properties on {@link android.view.View} objects. The class -automaties and optimizes the animation of the properties and makes it easier to -manage multiple simulataneous animations on a {@link android.view.View} object. -

        Using the {@link android.view.ViewPropertyAnimator} is straightforward. To animate properties for -a {@link android.view.View}, call {@link android.view.View#animate()} to -construct a {@link android.view.ViewPropertyAnimator} object for that {@link android.view.View}. Use the -methods on the {@link android.view.ViewPropertyAnimator} to specify what property to -animate and how to animate it. For example, to fade the {@link android.view.View} to transparent, -call alpha(0);. The {@link android.view.ViewPropertyAnimator} object -handles the details of configuring the underlying {@link -android.animation.Animator} class and starting it, then rendering the -animation.

      • -
      -
    • -
    • Animation background color -
        -
      • New {@link android.view.animation.Animation#getBackgroundColor()} and - {@link android.view.animation.Animation#setBackgroundColor(int)} methods let - you get/set the background color behind animations, for window animations -only. Currently the background must be black, with any desired alpha level.
      • -
      -
    • -
    • Getting animated fraction from ViewAnimator -
        -
      • A new {@link android.animation.ValueAnimator#getAnimatedFraction()} -method -lets you get the current animation fraction — the elapsed/interpolated -fraction used in the most recent frame update — from a {@link -android.animation.ValueAnimator}.
      • -
      -
    • -
    - -

    UI framework

    -
      -
    • Forced rendering of a layer -
        -
      • A new {@link android.view.View#buildLayer()} method lets an application -force a View's layer to be created and the View rendered into it immediately. -For example, an application could use this method to render a View into its -layer before starting an animation. If the View is complex, rendering it into -the layer before starting the animation will avoid skipping frames.
      • -
      -
    • -
    • Camera distance -
        -
      • Applications can use a new method -{@link android.view.View#setCameraDistance(float)} to set the distance from the -camera -to a View. This gives applications improved control over 3D transformations of -the View, such as rotations.
      • -
      -
    • -
    • Getting a calendar view from a DatePicker -
        -
      • A new {@link android.widget.DatePicker#getCalendarView()} method - lets you get a {@link android.widget.CalendarView} from a {@link -android.widget.DatePicker} - instance.
      • -
      -
    • -
    • Getting callbacks when views are detached -
        -
      • A new {@link android.view.View.OnAttachStateChangeListener} lets you -receive -callbacks when a View is attached or detached from its window. Use {@link -android.view.View#addOnAttachStateChangeListener(android.view.View.OnAttachStateChangeListener) addOnAttachStateChangeListener()} -to add a listener and {@link -android.view.View#removeOnAttachStateChangeListener(android.view.View.OnAttachStateChangeListener) addOnAttachStateChangeListener()} to remove it.
      • -
      -
    • -
    • Fragment breadcrumb listener, new onInflate() signature -
        -
      • A new method, {@link -android.app.FragmentBreadCrumbs#setOnBreadCrumbClickListener(android.app.FragmentBreadCrumbs.OnBreadCrumbClickListener) setOnBreadCrumbClickListener()}, -provides a hook to let -applications intercept fragment-breadcrumb clicks and take any action needed -before going to the backstack entry or fragment that was clicked.
      • -
      • In the {@link android.app.Fragment} class, {@link -android.app.Fragment#onInflate(android.util.AttributeSet, android.os.Bundle) -onInflate(attrs, savedInstanceState)} is deprecated. Please use {@link -android.app.Fragment#onInflate(android.app.Activity, android.util.AttributeSet, -android.os.Bundle) onInflate(activity, attrs, savedInstanceState)} instead.
      • -
      -
    • -
    • Display search result in new tab -
        -
      • An {@link android.app.SearchManager#EXTRA_NEW_SEARCH} data key for {@link -android.content.Intent#ACTION_WEB_SEARCH} intents lets you open a search in a -new browser tab, rather than in an existing one.
      • -
      -
    • - -
    • Drawable text cursor -
        -
      • You can now specify a drawable to use as the text cursor using the new -resource attribute {@link android.R.attr#textCursorDrawable}.
      • -
      -
    • -
    • Setting displayed child in remote views -
        -
      • A new convenience method, {@link -android.widget.RemoteViews#setDisplayedChild(int, int) setDisplayedChild(viewId, -childIndex)}, is available in {@link android.widget.RemoteViews} subclasses, to -let you set the child displayed in {@link android.widget.ViewAnimator} and -{@link android.widget.AdapterViewAnimator} subclasses such as {@link -android.widget.AdapterViewFlipper}, {@link android.widget.StackView}, {@link -android.widget.ViewFlipper}, and {@link android.widget.ViewSwitcher}.
      • -
      -
    • -
    • Generic keys for gamepads and other input devices -
        -
      • {@link android.view.KeyEvent} adds a range of generic keycodes to - accommodate gamepad buttons. The class also adds - {@link android.view.KeyEvent#isGamepadButton(int)} and several other - helper methods for working with keycodes.
      • -
      -
    • -
    - -

    Graphics

    - -
      -
    • Helpers for managing bitmaps -
        -
      • {@link android.graphics.Bitmap#setHasAlpha(boolean)} lets an app indicate that -all of the pixels in a Bitmap are known to be opaque (false) or that some of the -pixels may contain non-opaque alpha values (true). Note, for some configs (such -as RGB_565) this call is ignored, since it does not support per-pixel alpha -values. This is meant as a drawing hint, as in some cases a bitmap that is known -to be opaque can take a faster drawing case than one that may have non-opaque -per-pixel alpha values.
      • -
      • {@link android.graphics.Bitmap#getByteCount()} gets a Bitmap's size in -bytes.
      • -
      • {@link android.graphics.Bitmap#getGenerationId()} lets an application find -out whether a Bitmap has been modified, such as for caching.
      • -
      • {@link android.graphics.Bitmap#sameAs(android.graphics.Bitmap)} determines -whether a given Bitmap differs from the current Bitmap, in dimension, -configuration, or pixel data.
      • -
      -
    • -
    • Setting camera location and rotation -
        -
      • {@link android.graphics.Camera} adds two new methods {@link -android.graphics.Camera#rotate(float, float, float) rotate()} and {@link -android.graphics.Camera#setLocation(float, float, float) setLocation()} for -control of the -camera's location, for 3D transformations.
      • -
      -
    • -
    - -

    Network

    - -
      -
    • High-performance Wi-Fi lock -
        -
      • A new high-performance Wi-Fi lock lets applications maintain -high-performance Wi-Fi connections even when the device screen is off. -Applications that stream music, video, or voice for long periods can acquire the -high-performance Wi-Fi lock to ensure streaming performance even when the screen -is off. Because it uses more power, applications should acquire the -high-performance Wi-Fi when there is a need for a long-running active -connection. -

        To create a high-performance lock, pass {@link -android.net.wifi.WifiManager#WIFI_MODE_FULL_HIGH_PERF} as the lock mode in a -call to {@link android.net.wifi.WifiManager#createWifiLock(int, -java.lang.String) createWifiLock()}.

      • -
      -
    • -
    • More traffic stats -
        -
      • Applications can now access statistics about more types of network usage -using new methods in {@link android.net.TrafficStats}. Applications can use the -methods to get UDP stats, packet count, TCP transmit/receive payload bytes and -segments for a given UID.
      • -
      -
    • -
    • SIP auth username -
        -
      • Applications can now get and set the SIP auth username for a profile -using -the new methods {@link android.net.sip.SipProfile#getAuthUserName() -getAuthUserName()} and {@link -android.net.sip.SipProfile.Builder#setAuthUserName(java.lang.String) -setAuthUserName()}.
      • -
      -
    • -
    - - -

    Download Manager

    -
      -
    • Handling of completed downloads -
        -
      • Applications can now initiate downloads that notify users only on -completion. To initiate this type of download, applications pass {@link -android.app.DownloadManager.Request#VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION} -in the {@link -android.app.DownloadManager.Request#setNotificationVisibility(int) -setNotificationVisibility()} method of -the a request object.
      • -
      • A new method, {@link -android.app.DownloadManager#addCompletedDownload(java.lang.String, -java.lang.String, boolean, java.lang.String, java.lang.String, long, boolean) -addCompletedDownload()}, lets an application add a file to the -downloads database, so that it can be managed by the Downloads application.
      • -
      -
    • -
    • Show downloads sorted by size -
        -
      • Applications can start the Downloads application in sort-by-size mode by -adding the new extra {@link -android.app.DownloadManager#INTENT_EXTRAS_SORT_BY_SIZE} to an {@link -android.app.DownloadManager#ACTION_VIEW_DOWNLOADS} intent.
      • -
      -
    • -
    - -

    IME framework

    - -
      -
    • Getting an input method's extra value key -
      • The {@link android.view.inputmethod.InputMethodSubtype} adds the -method -{@link -android.view.inputmethod.InputMethodSubtype#containsExtraValueKey(java.lang.String) containsExtraValueKey()} to check whether an ExtraValue string is stored -for the subtype and -the method {@link -android.view.inputmethod.InputMethodSubtype#getExtraValueOf(java.lang.String) -getExtraValueOf()} to extract a specific key value from the ExtraValue hashmap. -
      • -
      -
    • -
    - -

    Media

    - -
      -
    • New streaming audio formats -
        -
      • The media framework adds built-in support for raw ADTS AAC content, for -improved streaming audio, as well as support for FLAC audio, for highest quality -(lossless) compressed audio content. See the Supported Media Formats -document for more information.

      • -
      -
    • -
    - -

    Launch controls on stopped -applications

    - -

    Starting from Android 3.1, the system's package manager keeps track of -applications that are in a stopped state and provides a means of controlling -their launch from background processes and other applications.

    - -

    Note that an application's stopped state is not the same as an Activity's -stopped state. The system manages those two stopped states separately.

    - -

    The platform defines two new intent flags that let a sender specify -whether the Intent should be allowed to activate components in stopped -application.

    - -
      -
    • {@link android.content.Intent#FLAG_INCLUDE_STOPPED_PACKAGES} — -Include intent filters of stopped applications in the list of potential targets -to resolve against.
    • -
    • {@link android.content.Intent#FLAG_EXCLUDE_STOPPED_PACKAGES} — -Exclude intent filters of stopped applications from the list of potential -targets.
    • -
    - -

    When neither or both of these flags is defined in an intent, the default -behavior is to include filters of stopped applications in the list of -potential targets.

    - -

    Note that the system adds {@link -android.content.Intent#FLAG_EXCLUDE_STOPPED_PACKAGES} to all broadcast -intents. It does this to prevent broadcasts from background services from -inadvertently or unnecessarily launching components of stoppped applications. -A background service or application can override this behavior by adding the -{@link android.content.Intent#FLAG_INCLUDE_STOPPED_PACKAGES} flag to broadcast -intents that should be allowed to activate stopped applications.

    - -

    Applications are in a stopped state when they are first installed but are not -yet launched and when they are manually stopped by the user (in Manage -Applications).

    - -

    Notification of application first launch and upgrade

    - -

    The platform adds improved notification of application first launch and -upgrades through two new intent actions:

    - -
      -
    • {@link android.content.Intent#ACTION_PACKAGE_FIRST_LAUNCH} — Sent to -the installer package of an application when that application is first launched -(that is, the first time it is moved out of a stopped state). The data -contains the name of the package.
    • - -
    • {@link android.content.Intent#ACTION_MY_PACKAGE_REPLACED} — Notifies -an application that it was updated, with a new version was installed over -an existing version. This is only sent to the application that was replaced. It -does not contain any additional data. To receive it, declare an intent filter -for this action. You can use the intent to trigger code that helps get your -application back in proper running shape after an upgrade. - -

      This intent is sent directly to the application, but only if the application -was upgraded while it was in started state (not in a stopped state).

    • - -
    - -

    Core utilities

    - -
      -
    • LRU cache -
        -
      • A new {@link android.util.LruCache} class lets your applications benefit -from efficient caching. Applications can use the class to reduce the time spent -computing or downloading data from the network, while maintaining a sensible -memory footprint for the cached data.{@link android.util.LruCache} is a cache -that holds strong references to a limited number of values. Each time a value is -accessed, it is moved to the head of a queue. When a value is added to a full -cache, the value at the end of that queue is evicted and may become eligible for -garbage collection.
      • -
      -
    • -
    • File descriptor as int -
        -
      • You can now get the native file descriptor int for a {@link -android.os.ParcelFileDescriptor} using either of the new methods {@link -android.os.ParcelFileDescriptor#getFd()} or {@link -android.os.ParcelFileDescriptor#detachFd()}.
      • -
      -
    • -
    - - - - - - -

    WebKit

    - -
      - -
    • File scheme cookies -
        -
      • The {@link android.webkit.CookieManager} now supports cookies that use -the -file: URI scheme. You can use {@link -android.webkit.CookieManager#setAcceptFileSchemeCookies(boolean) -setAcceptFileSchemeCookies()} to -enable/disable support for file scheme cookies, before constructing an instance -of WebView or CookieManager. In a -CookieManager instance, you can check whether file scheme cookies -is enabled by calling {@link -android.webkit.CookieManager#allowFileSchemeCookies()}.
      • -
      -
    • -
    • Notification of login request -
        -
      • To support the browser autologin features introduced in Android 3.0, the -new -method {@link -android.webkit.WebViewClient#onReceivedLoginRequest(android.webkit.WebView,java.lang.String, java.lang.String, java.lang.String) onReceivedLoginRequest()} -notifies the host -application that an autologin request for the user was processed.
      • -
      -
    • -
    • Removed classes and interfaces -
        -
      • Several classes and interfaces were removed from the public API, after -previously being in deprecated state. See the API -Differences Report for more information.

      • -
      -
    • -
    - - - -

    Browser

    - -

    The Browser application adds the following features to support web -applications:

    - -
      -
    • Support for inline playback of video embedded in HTML5 -<video> tag. Playback is hardware-accelerated where possible. -
    • -
    • Layer support for fixed position elements for all sites (mobile and -desktop).
    • -
    - - - - - -

    New feature constants

    - -

    The platform adds new hardware feature constants that developers can declare -in their application manifests, to inform external entities such as Google -Play of the application's requirement for new hardware capabilities supported -in this version of the platform. Developers declare these and other feature -constants in {@code -<uses-feature>} manifest elements. - -

      -
    • {@link android.content.pm.PackageManager#FEATURE_USB_ACCESSORY -android.hardware.usb.accessory} — The application uses the USB -API to communicate with external hardware devices connected over USB and -function as hosts.
    • -
    • {@link android.content.pm.PackageManager#FEATURE_USB_HOST -android.hardware.usb.host} — The application uses the USB API -to communicate with external hardware devices connected over USB and function as -devices.
    • -
    - -

    Google Play filters applications based on features declared in {@code -<uses-feature>} manifest elements. For more information about -declaring features in an application manifest, read Google Play -Filters.

    - - - -

    API Differences Report

    - -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API -Level -{@sdkPlatformApiLevel}), see the API -Differences Report.

    - - - - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, -you need compile the application against the Android library that is provided in -the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you -might -also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" -attribute to the <uses-sdk> element in the application's -manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • API Demos
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Clock
    • -
    • Contacts
    • -
    • Custom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    -
    -
      -
    • Gallery
    • -
    • Gestures Builder
    • -
    • Messaging
    • -
    • Music
    • -
    • Search
    • -
    • Settings
    • -
    • Spare Parts
    • -
    • Speech Recorder
    • -
    • Widget Preview
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety -of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android 3.0 system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian bokmål, Norway (nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes the following emulator skin:

    - -
      -
    • - WXGA (1280x800, medium density, xlarge screen) -
    • -
    - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    \ No newline at end of file diff --git a/docs/html/sdk/android-3.2.jd b/docs/html/sdk/android-3.2.jd deleted file mode 100644 index 27df22cba0d9..000000000000 --- a/docs/html/sdk/android-3.2.jd +++ /dev/null @@ -1,741 +0,0 @@ -page.title=Android 3.2 Platform -sdk.platform.version=3.2 -sdk.platform.apiLevel=13 -@jd:body - - - - -

    API Level: {@sdkPlatformApiLevel}

    - -

    Welcome to Android 3.2!

    - -

    Android 3.2 is an incremental platform release that adds new -capabilities for users and developers. The sections below provide an overview -of the new features and developer APIs.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The downloadable platform includes -an Android library and system image, as well as a set of emulator skins and -more. The downloadable platform includes no external libraries.

    - -

    To get started developing or testing against Android {@sdkPlatformVersion}, -use the Android SDK Manager to download the platform into your SDK. For more -information, see Adding SDK -Components. If you are new to Android, download the SDK Starter Package first.

    - -

    Reminder: If you've already published an -Android application, please test and optimize your application on Android 3.2 as -soon as possible. You should do so to be sure your application provides the best -experience possible on the latest Android-powered devices. For information about -what you can do, read Optimizing Apps for -Android 3.x.

    - - -

    Revisions

    - -

    To determine what revision of the Android {@sdkPlatformVersion} platform you -have installed, refer to the "Installed Packages" listing in the Android SDK and -AVD Manager.

    - - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (July 2011) -

    - -
    - -
    -
    Initial release. SDK Tools r12 or higher is recommended.
    -
    - -
    -
    - -

    Platform Highlights

    - -

    New user features

    - -
      -
    • Optimizations for a wider range of tablets - -

      Android 3.2 includes a variety of optimizations across the system -to ensure a great user experience on a wider range of tablet devices.

    • - -
    • Compatibility zoom for fixed-sized apps - -

      Android 3.2 introduces a new compatibility zoom mode that gives -users a new way to view fixed-sized apps on larger devices. The new mode provides a -pixel-scaled alternative to the standard UI stretching for apps that are not -designed to run on larger screen sizes, such as on tablets. The new mode is -accessible to users from a menu icon in the system bar, for apps that need -compatibility support.

    • - -
    • Media sync from SD card -

      On devices that support an SD card, users can now load media files directly -from the SD card to apps that use them. A system facility makes the files -accessible to apps from the system media store.

    • -
    - - -

    New developer features

    - -
      -
    • Extended API for managing screens support - -

      Android 3.2 introduces extensions to the platform's screen support API to -give developers additional ways to manage application UI across the range of -Android-powered devices. The API includes new resource qualifiers and new -manifest attributes that give you more precise control over how your -apps are displayed on different sizes, rather than relying on generalized -size categories.

      - -

      To ensure the best possible display for fixed-sized apps and apps with limited -support for various screen sizes, the platform also provides a new zoom -compatibility mode that renders the UI on a smaller screen area, then scales it -up to fill the space available on the display. For more information about the -screen support API and the controls it provides, see the sections below.

    • -
    - - -

    API Overview

    - -

    Screens Support APIs

    - -

    Android 3.2 introduces new screens support APIs that give you more -control over how their applications are displayed across different screen sizes. -The API builds on the existing screens-support API, including the platform's -generalized screen density model, but extends it with the ability to precisely -target specific screen ranges by their dimensions, measured in -density-independent pixel units (such as 600dp or 720dp wide), rather than -by their generalized screen sizes (such as large or xlarge)

    - -

    When designing an application's UI, you can still rely on the platform to -provide density abstraction, which means that applications do not need to -compensate for the differences in actual pixel density across devices. You -can design the application UI according to the amount of horizontal or vertical -space available. The platform expresses the amount of space available using three new -characteristics: smallestWidth, width, and -height.

    - -
      -
    • A screen's smallestWidth is its fundamental minimum size, -measured in density-independent pixel ("dp") units. Of the screen's height or -width, it is the shorter of the two. For a screen in portrait orientation, the -smallestWidth is normally based on its width, while in landscape orientation it is based -on its height. In all cases, the smallestWidth is derived from a fixed characteristic of the -screen and the value does not change, regardless of orientation. The smallestWidth -is important for applications because it represents the shortest possible width -in which the application UI will need to be drawn, not including screen areas -reserved by the system. -
    • - -
    • In contrast, a screen's width and height represent the -current horizontal or vertical space available for application layout, measured -in "dp" units, not including screen areas reserved by the system. The width and -height of a screen change when the user switches orientation between landscape -and portrait.
    • - -
    - -

    The new screens support API is designed to let you manage application UI -according to the smallestWidth of the current screen. You can also manage the -UI according to current width or height, as needed. For those purposes, the API -provides these tools:

    - -
      -
    • New resource qualifiers for targeting layouts and other resources to a -minimum smallestWidth, width, or height, and
    • -
    • New manifest attributes, for specifying the app's maximum -screen compatibility range
    • -
    - -

    Additionally, applications can still query the system and manage UI and -resource loading at runtime, as in the previous versions of the platform.

    - -

    Since the new API lets you target screens more directly through smallestWidth, -width, and height, it's helpful to understand the typical -characteristics of the different screen types. The table below provides some -examples, measured in "dp" units.

    - -

    Table 1. Typical devices, with density -and size in dp.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    TypeDensity (generalized)Dimensions (dp)smallestWidth (dp)
    Baseline phonemdpi320x480320
    Small tablet/large phonemdpi480x800480
    7-inch tabletmdpi600x1024600
    10-inch tabletmdpi800x1280800
    - -

    The sections below provide more information about the new screen qualifiers -and manifest attributes. For complete information about how to use the screen -support API, see Supporting Multiple -Screens.

    - -

    New resource qualifiers for screens support

    - -

    The new resource qualifiers in Android 3.2 let you better target your layouts -for ranges of screen sizes. Using the qualifiers, you can create resource -configurations designed for a specific minimum smallestWidth, current width, or -current height, measured in density-independent pixels.

    - -

    The new qualifiers are:

    -
      -
    • swNNNdp — Specifies the minimum smallestWidth on which -the resource should be used, measured in "dp" units. As mentioned above, a -screen's smallestWidth is constant, regardless of orientation. Examples: -sw320dp, sw720dp, sw720dp.
    • - -
    • wNNNdp and hNNNdp — Specifies the minimum -width or height on which the resource should be used, measured in "dp" units. As -mentioned above, a screen's width and height are relative to the orientation of -the screen and change whenever the orientation changes. Examples: -w320dp, w720dp, h1024dp.

    • -
    - -

    You can also create multiple overlapping resource configurations if needed. -For example, you could tag some resources for use on any screen wider than 480 -dp, others for wider than 600 dp, and others for wider than 720 dp. When -multiple resource configurations are qualified for a given screen, the system -selects the configuration that is the closest match. For precise control over -which resources are loaded on a given screen, you can tag resources with one -qualifier or combine several new or existing qualifiers. - -

    Based on the typical dimensions listed earlier, here are some examples of how -you could use the new qualifiers:

    - -
    res/layout/main_activity.xml   # For phones
    -res/layout-sw600dp/main_activity.xml   # For 7” tablets
    -res/layout-sw720dp/main_activity.xml   # For 10” tablets
    -res/layout-w600dp/main_activity.xml   # Multi-pane when enough width
    -res/layout-sw600dp-w720dp/main_activity.xml   # For large width
    - -

    Older versions of the platform will ignore the new qualifiers, so you can -mix them as needed to ensure that your app looks great on any device. Here -are some examples:

    - -
    res/layout/main_activity.xml   # For phones
    -res/layout-xlarge/main_activity.xml   # For pre-3.2 tablets
    -res/layout-sw600dp/main_activity.xml   # For 3.2 and up tablets
    - -

    For complete information about how to use the new qualifiers, see Using new -size qualifiers.

    - -

    New manifest attributes for screen-size compatibility

    - -

    The framework offers a new set of <supports-screens> manifest attributes that let -you manage your app's support for different screen sizess. -Specifically, you can specify the largest and smallest screens on which your app -is designed to run, as well as the largest screen on which it is designed run -without needing the system's new screen -compatibility mode. Like the resource qualifiers described above, the new -manifest attributes specify the range of screens that the application supports, -as specified by the smallestWidth.

    - -

    The new manifest attributes for screen support are:

    - -
      -
    • android:compatibleWidthLimitDp="numDp" — This -attribute lets you specify the maximum smallestWidth on which the application -can run without needing compatibility mode. If the current screen is larger than -the value specified, the system displays the application in normal mode but -allows the user to optionally switch to compatibility mode through a setting in -the system bar.
    • - -
    • android:largestWidthLimitDp="numDp" — This -attribute lets you specify the maximum smallestWidth on which the application -is designed to run. If the current screen is larger than the value specified, -the system forces the application into screen compatibility mode, to ensure best -display on the current screen.
    • - -
    • android:requiresSmallestWidthDp="numDp" — This -attribute lets you specify the minimum smallestWidth on which the application -can run. If the current screen is smaller than the value specified, the system -considers the application incompatible with the device, but does not prevent it -from being installed and run.
    • -
    - -

    Note: Google Play does not currently filter -apps based on any of the attributes above. Support for filtering will be -added in a later platform release. Applications that require -filtering based on screen size can use the existing <supports-screens> -attributes.

    - -

    For complete information about how to use the new attributes, see Declaring -screen size support.

    - -

    Screen compatibility mode

    - -

    Android 3.2 provides a new screen compatibility mode for applications -explicitly declaring that they do not support screens as large as the one on -which they are running. This new "zoom" mode is a pixel-scaled — it -renders the application in a smaller screen area and then scales the pixels to -fill the current screen.

    - -

    By default, the system offers screen compatibility mode as an user option, for apps -that require it. Users can turn the zoom mode on and off using a control available -in the system bar.

    - -

    Because the new screen compatibility mode may not be appropriate for all -applications, the platform allows the application to disable it using manifest -attributes. When disabled by the app, the system does not offer "zoom" compatibility -mode as an option for users when the app is running.

    - -

    Note: For important information about how -to control compatibility mode in your applications, please review the New Mode for Apps on Large Screens article on the Android -Developers Blog.

    - -

    New screen density for 720p televisions and similar devices

    - -

    To meet the needs of applications running on 720p televisions or similar with -moderate density screens, Android 3.2 introduces a new generalized density, -tvdpi, with an approximate dpi of 213. Applications can query for -the new density in {@link android.util.DisplayMetrics#densityDpi} and can use -the new tvdpi qualifier to tag resources for televisions and -similar devices. For example:

    - -
    res/drawable-tvdpi/my_icon.png   # Bitmap for tv density
    - -

    In general, applications should not need to work with this density. For situations -where output is needed for a 720p screen, the UI elements can be scaled -automatically by the platform.

    - - -

    UI framework

    -
      -
    • Fragments -
        -
      • New {@link android.app.Fragment.SavedState} class holds the state - information retrieved from a fragment instance through - {@link android.app.FragmentManager#saveFragmentInstanceState(android.app.Fragment) saveFragmentInstanceState()}.
      • -
      • New method {@link android.app.FragmentManager#saveFragmentInstanceState(android.app.Fragment) saveFragmentInstanceState()} - saves the current instance state of - the given Fragment. The state can be used later when creating a new instance - of the Fragment that matches the current state.
      • -
      • New method {@link android.app.Fragment#setInitialSavedState(SavedState) setInitialSavedState()} - sets the initial saved state for a Fragment when first constructed.
      • -
      • New {@link android.app.Fragment#onViewCreated(android.view.View, android.os.Bundle) - onViewCreated()} callback method notifies the Fragment that - {@link android.app.Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle) onCreateView()} - has returned, but before any saved state has been restored in to the View.
      • -
      • {@link android.app.Fragment#isDetached()} method determines whether - the Fragment has been explicitly detached from the UI.
      • -
      • New {@link android.app.FragmentTransaction#attach(android.app.Fragment) attach()} - and {@link android.app.FragmentTransaction#detach(android.app.Fragment) detach()} - methods let an application re-attach or detach fragments in the UI.
      • -
      • A new {@link android.app.FragmentTransaction#setCustomAnimations(int, int, int, int) - setCustomAnimations()} overload method lets you set specific animation - resources to run for enter/exit operations and specifically when - popping the back stack. The existing implementation does not account - for the different behavior of fragments when popping the back stack.
      • -
      -
    • -
    • Screen size information in ActivityInfo and ApplicationInfo -
        -
      • {@link android.content.pm.ActivityInfo} adds {@link android.content.pm.ActivityInfo#CONFIG_SCREEN_SIZE} - and {@link android.content.pm.ActivityInfo#CONFIG_SMALLEST_SCREEN_SIZE} as bit masks - in {@link android.R.attr#configChanges}. The bits indicate whether an Activity can - itself handle the screen size and smallest screen size.
      • -
      • {@link android.content.pm.ApplicationInfo} adds - {@link android.content.pm.ApplicationInfo#largestWidthLimitDp}, {@link android.content.pm.ApplicationInfo#compatibleWidthLimitDp}, - and {@link android.content.pm.ApplicationInfo#requiresSmallestWidthDp} fields, - derived from the corresponding <supports-screens> attributes - in the application manifest file.
      • -
      -
    • -
    • Helpers for getting display size from WindowManager -
        -
      • New methods {@link android.view.Display#getSize(android.graphics.Point) - getSize()} and {@link android.view.Display#getRectSize(android.graphics.Rect) - getRectSize()} let applications get the raw size of the display.
      • -
      -
    • -
    • New public "holographic" styles -
        -
      • The platform now exposes a variety of public "holographic" styles - for text, actionbar widgets and tabs, and more. See - {@link android.R.style} for a full list.
      • -
      -
    • -
    • {@link android.app.LocalActivityManager}, {@link android.app.ActivityGroup}, and - {@link android.app.LocalActivityManager} are now deprecated -
        -
      • New applications should use Fragments instead of these classes. To - continue to run on older versions of the platform, you can use the v4 Support - Library (compatibility library), available in the Android SDK. The v4 Support - Library provides a version of the Fragment API that is compatible down to - Android 1.6 (API level 4). -
      • For apps developing against Android 3.0 (API level - 11) or higher, tabs are typically presented in the UI using the new - {@link android.app.ActionBar#newTab() ActionBar.newTab()} and related APIs - for placing tabs within their action bar area.

      • -
      -
    • -
    - -

    Media framework

    -
      -
    • Applications that use the platform's media provider ({@link - android.provider.MediaStore}) can now read media data directly from the - removeable SD card, where supported by the device. Applications can also - interact with the SD card files directly, using the MTP API.
    • - -
    -

    Graphics

    -
      -
    • Parcelable utilities in Point and PointF -
        -
      • {@link android.graphics.Point} and {@link android.graphics.PointF} - classes now include the {@link android.os.Parcelable} interface and utility methods {@link - android.graphics.Point#describeContents()}, {@link - android.graphics.Point#readFromParcel(android.os.Parcel) readFromParcel()}, and {@link - android.graphics.Point#writeToParcel(android.os.Parcel, int) writeToParcel()}.
      • -
      -
    • -
    - - -

    IME framework

    -
      -
    • New {@link android.view.KeyEvent#getModifiers()} method for - retrieving the current state of the modifier keys.
    • -
    - - -

    USB framework

    -
      -
    • New {@link - android.hardware.usb.UsbDeviceConnection#getRawDescriptors()} method for - retrieving the raw USB descriptors for the device. You can use the - method to access descriptors not supported directly via the higher - level APIs.
    • -
    - - -

    Network

    -
      -
    • Network type constants -
        -
      • {@link android.net.ConnectivityManager} adds the constants {@link - android.net.ConnectivityManager#TYPE_ETHERNET} and {@link - android.net.ConnectivityManager#TYPE_BLUETOOTH}.
      • -
      -
    • -
    - - -

    Telephony

    -
      -
    • New {@link android.telephony.TelephonyManager#NETWORK_TYPE_HSPAP} network type constant.
    • -
    - -

    Core utilities

    -
      -
    • Parcelable utilities -
        -
      • New interface {@link android.os.Parcelable.ClassLoaderCreator} allows - the application to receive the ClassLoader in which the object is being created.
      • -
      • New {@link android.os.ParcelFileDescriptor#adoptFd(int) adoptFd}, {@link - android.os.ParcelFileDescriptor#dup(java.io.FileDescriptor) dup()}, and {@link - android.os.ParcelFileDescriptor#fromFd(int) fromFd()} for managing - {@link android.os.ParcelFileDescriptor} objects.
      • -
      -
    • -
    • Binder and IBinder -
        -
      • New method {@link android.os.Binder#dumpAsync(java.io.FileDescriptor, java.lang.String[]) dumpAsync()} - in {@link android.os.Binder} and {@link android.os.IBinder} let applications - dump to a specified file, ensuring that the target executes asynchronously.
      • -
      • New {@link android.os.IBinder} protocol transaction code {@link - android.os.IBinder#TWEET_TRANSACTION} lets applications send a tweet - to the target object.
      • -
      -
    • -
    - - - - -

    New feature constants

    - -

    The platform adds new hardware feature constants that you can declare -in their application manifests, to inform external entities such as Google -Play of required hardware and software capabilities. You declare these -and other feature constants in {@code -<uses-feature>} manifest elements. - -

    Google Play filters applications based on their <uses-feature> attributes, to ensure that they are available only to devices on which their requirements are met.

    - -
      -
    • Feature constants for landscape or portrait requirements - -

      Android 3.2 introduces new feature constants that let applications specify whether they require display in landscape orientation, portrait orientation, or both. Declaring these constants indicates that the application must not be installed on a device that doesn't offer the associated orientation. Conversely, if one or both of the constants are not declared, it indicates that the application does not have a preference for the undeclared orientations and may be installed on a device that doesn't offer them.

      - -
        -
      • {@link android.content.pm.PackageManager#FEATURE_SCREEN_LANDSCAPE -android.hardware.screen.landscape} — The application requires display in -landscape orientation.
      • -
      • {@link android.content.pm.PackageManager#FEATURE_SCREEN_PORTRAIT -android.hardware.screen.portrait} — The application requires display in -portrait orientation.
      • -
      - -

      A typical application that functions properly in both landscape and portrait orientations would not normally need to declare an orientation requirement. Rather, an application designed primarily for one orientation, such as an app designed for a television, could declare one of the constants to ensure that it isn't available to devices that don't provide that orientation.

      - -

      If any of activities declared in the manifest request that they run in a specific orientation, -using the {@code -android:screenOrientation} attribute, then this also declares that the application -requires that orientation.

      - -
    • -
    • Other feature constants - -
        -
      • {@link android.content.pm.PackageManager#FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT -android.hardware.faketouch.multitouch.distinct} — The application requires support for emulated mulitouch input with distinct tracking of two or more points.
      • - -
      • {@link android.content.pm.PackageManager#FEATURE_FAKETOUCH_MULTITOUCH_JAZZHAND -android.hardware.faketouch.multitouch.jazzhand} — The application requires support for emulated mulitouch input with distinct tracking of five or more points.
      • -
      - -
    • -
    - - -

    API Differences Report

    - -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API -Level -{@sdkPlatformApiLevel}), see the API -Differences Report.

    - - - - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} platform delivers an updated version of -the framework API. The Android {@sdkPlatformVersion} API -is assigned an integer identifier — -{@sdkPlatformApiLevel} — that is -stored in the system itself. This identifier, called the "API Level", allows the -system to correctly determine whether an application is compatible with -the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, -you need compile the application against the Android library that is provided in -the Android {@sdkPlatformVersion} SDK platform. Depending on your needs, you -might -also need to add an android:minSdkVersion="{@sdkPlatformApiLevel}" -attribute to the <uses-sdk> element in the application's -manifest.

    - -

    For more information about how to use API Level, see the API Levels document.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • API Demos
    • -
    • Browser
    • -
    • Calculator
    • -
    • Camera
    • -
    • Clock
    • -
    • Contacts
    • -
    • Custom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    -
    -
      -
    • Gallery
    • -
    • Gestures Builder
    • -
    • Messaging
    • -
    • Music
    • -
    • Search
    • -
    • Settings
    • -
    • Spare Parts
    • -
    • Speech Recorder
    • -
    • Widget Preview
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety -of -built-in locales. In some cases, region-specific strings are available for the -locales. In other cases, a default version of the language is used. The -languages that are available in the Android 3.0 system -image are listed below (with language_country/region locale -descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, Zimbabwe (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian bokmål, Norway (nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes the following emulator skin:

    - -
      -
    • - WXGA (1280x800, medium density, xlarge screen) -
    • -
    - -

    For more information about how to develop an application that displays -and functions properly on all Android-powered devices, see Supporting Multiple -Screens.

    diff --git a/docs/html/sdk/android-4.0-highlights.jd b/docs/html/sdk/android-4.0-highlights.jd deleted file mode 100644 index 98f467d54813..000000000000 --- a/docs/html/sdk/android-4.0-highlights.jd +++ /dev/null @@ -1,1009 +0,0 @@ -page.title=Android 4.0 Platform Highlights - -@jd:body - - - - -
    - -
    - -

    Welcome to Android 4.0!

    - -

    Android 4.0 delivers a refined, unified UI for phones and tablets and -introduces innovative features for users and developers. This document provides -a glimpse of the many new features and technologies that make Android 4.0 -simple, beautiful, and beyond smart.

    - - - -

    Android 4.0 for Users

    - -
    - - -
    - - -

    Simple, beautiful, beyond smart

    - -

    Android 4.0 builds on the things people love most about Android — easy -multitasking, rich notifications, customizable home screens, resizable widgets, -and deep interactivity — and adds powerful new ways of communicating and -sharing.

    - -

    Refined, evolved UI

    - -

    Focused on bringing the power of Android to the surface, Android 4.0 makes -common actions more visible and lets users navigate with -simple, intuitive gestures. Refined animations and feedback -throughout the system make interactions engaging and interesting. An entirely -new typeface optimized for high-resolution screens improves -readability and brings a polished, modern feel to the user interface.

    - -

    Virtual buttons in the System Bar let users navigate instantly to Back, Home, -and Recent Apps. The System Bar and virtual buttons are present -across all apps, but can be dimmed by applications for full-screen viewing. -Users can access each application's contextual options in the Action -Bar, displayed at the top (and sometimes also at the bottom) of the -screen.

    - -

    Multitasking is a key strength of Android and it's made even -easier and more visual on Android 4.0. The Recent Apps button lets users jump -instantly from one task to another using the list in the System Bar. The list -pops up to show thumbnail images of apps used recently — tapping a -thumbnail switches to the app.

    - -
    -
    - - -
    The Recent Apps list makes multitasking simple.
    - - -
    Jump to the camera or see notifications without unlocking.
    - - - -
    For incoming calls, you can respond instantly by text.
    -
    -
    - -

    Rich and interactive notifications let users keep in -constant touch with incoming messages, play music tracks, see real-time updates -from apps, and much more. On smaller-screen devices, notifications appear at the -top of the screen, while on larger-screen devices they appear in the System -Bar.

    - -
    -
    - - - - -
    The All Apps launcher (left) and resizable widgets (right) give you apps and rich content from the home screen.
    -
    -
    - - -

    Home screen folders and -favorites tray

    - -

    New home screen folders offer a new way for users to group -their apps and shortcuts logically, just by dragging one onto another. Also, -in All Apps launcher, users can now simply drag an app to get -information about it or immediately uninstall it, or disable a pre-installed app.

    - -

    On smaller-screen devices, the home screen now includes a customizable -favorites tray visible from all home screens. Users can drag -apps, shortcuts, folders, and other priority items in or out of the favorites -tray for instant access from any home screen.

    - - -

    Resizable -widgets

    - -

    Home screens in Android 4.0 are designed to be content-rich and customizable. -Users can do much more than add shortcuts — they can embed live -application content directly through interactive widgets. -Widgets let users check email, flip through a calendar, play music, check social -streams, and more — right from the home screen, without having to launch -apps. Widgets are resizable, so users can expand them to show more content or -shrink them to save space.

    - - -

    New lock screen -actions

    - -

    The lock screens now let users do more without unlocking. From the slide lock -screen, users can jump directly to the camera for a picture or -pull down the notifications window to check for messages. When -listening to music, users can even manage music tracks and see album art.

    - - -

    Quick responses for -incoming calls

    - -

    When an incoming call arrives, users can now quickly respond by text -message, without needing to pick up the call or unlock the device. On -the incoming call screen, users simply slide a control to see a list of text -responses and then tap to send and end the call. Users can add their own -responses and manage the list from the Settings app.

    - - -

    Swipe to dismiss -notifications, tasks, and browser tabs

    - -

    Android 4.0 makes managing notifications, recent apps, and browser tabs even -easier. Users can now dismiss individual notifications, apps from the Recent -Apps list, and browser tabs with a simple swipe of a finger.

    - -
    -
    - - -
    A spell-checker lets you find errors and fix them faster.
    - - -
    A powerful voice input engine lets you dictate continously.
    -
    -
    - -

    Improved text input and -spell-checking

    - -

    The soft keyboard in Android 4.0 makes text input even faster and more -accurate. Error correction and word suggestion are improved through a new set of -default dictionaries and more accurate heuristics for handling cases such as -double-typed characters, skipped letters, and omitted spaces. Word suggestion -is also improved and the suggestion strip is simplified to show only three -words at a time.

    - -

    To fix misspelled words more easily, Android 4.0 adds a -spell-checker that locates and underlines errors and suggests -replacement words. With one tap, users can choose from multiple spelling -suggestions, delete a word, or add it to the dictionary. Users can even tap to -see replacement suggestions for words that are spelled correctly. For -specialized features or additional languages, users can now download and install -third-party dictionaries, spell-checkers, and other text services.

    - - -

    Powerful voice input -engine

    - -

    Android 4.0 introduces a powerful new voice input engine that offers a -continuous "open microphone" experience and streaming voice recognition. The new -voice input engine lets users dictate the text they want, for as long as they -want, using the language they want. Users can speak continously for a prolonged -time, even pausing for intervals if needed, and dictate punctuation to create -correct sentences. As the voice input engine enters text, it underlines possible -dictation errors in gray. After dictating, users can tap the underlined words to -quickly replace them from a list of suggestions.

    - -
    -
    - - - - -
    Data usage controls let you monitor total usage by network type and application and then set limits if needed.
    -
    -
    - -

    Control over network -data

    - -

    Mobile devices can make extensive use of network data for streaming content, -synchronizing data, downloading apps, and more. To meet the needs of users with -tiered or metered data plans, Android 4.0 adds new controls for -managing network data usage.

    - -

    In the Settings app, colorful charts show the total data usage on each -network type (mobile or Wi-Fi), as well as amount of data used by each running -application. Based on their data plans, users can optionally set warning levels -or hard limits on data usage or disable mobile data altogether. Users can also -manage the background data used by individual applications as needed.

    - - -

    Designed for -accessibility

    - -

    A variety of new features greatly enhance the accessibility of Android 4.0 -for blind or visually impaired users. Most important is a new -explore-by-touch mode that lets users navigate without having -to see the screen. Touching the screen once triggers audible feedback that -identifies the UI component below; a second touch in the same component -activates it with a full touch event. The new mode is especially important to -support users on new devices that use virtual buttons in the System Bar, rather -than dedicated hardware buttons or trackballs. Also, standard apps are updated -to offer an improved accessibility experience. The Browser -supports a script-based screen reader for reading favorite web content and -navigating sites. For improved readability, users can also increase the default -font size used across the system.

    - -

    The accessibility experience begins at first setup — a simple -touch gesture during setup (clockwise square from upper left) -activates all accessibility features and loads a setup tutorial. Once -accessibility features are active, everything visible on the screen can be -spoken aloud by the standard screen reader.

    - - -

    Communication and sharing

    - -
    -
    - - - - - - - - -
    Contacts and profiles are integrated across apps and social networks, for a consistent, personal experience everywhere — from incoming calls to emails.
    -
    -
    - -

    Designed for the way people live, Android 4.0 integrates rich social -communication and sharing touchpoints across the system, making it easy to talk, -email, text, and share.

    - - -

    People and -profiles

    - -

    Throughout the system, a user’s social groups, profiles, and contacts are -linked together and integrated for easy accessibility. At the center is a new -People app that offers richer profile information, including a -large profile picture, phone numbers, addresses and accounts, status updates, -events, stream items, and a new button for connecting on integrated social networks.

    - -

    The user's own contact information is stored in a new "Me" -profile, allowing easier sharing with apps and people. All of the -user's integrated contacts are displayed in an easy to manage list, including -controls over which contacts are shown from any integrated account or social -network. Wherever the user navigates across the system, tapping a profile photo -displays Quick Contacts, with large profile pictures, shortcuts to phone numbers, -text messaging, and more.

    - - -

    Unified calendar, visual -voicemail

    - -

    To help organize appointments and events, an updated Calendar -app brings together personal, work, school, and social agendas. With -user permission, other applications can contribute events to the calendar and -manage reminders, for an integrated view across multiple calendar providers. The -app is redesigned to let users manage events more easily. Calendars are -color-coded and users can swipe left or right to change dates -and pinch to zoom in or out agendas.

    - -

    In the phone app, a new visual voicemail features integrates -incoming messages, voice transcriptions, and audio files from one or more -providers. Third-party applications can integrate with the Phone app to add -their own voice messages, transcriptions, and more to the visual voicemail -inbox.

    - -
    -
    - - - - - - -
    Capture the picture you want, edit, and share instantly.
    -
    -
    - -

    Rich and versatile camera -capabilities

    - -

    The Camera app includes many new features that let users capture special moments -with great photos and videos. After capturing images, they can edit and share -them easily with friends.

    - -

    When taking pictures, continuous focus, zero shutter -lag exposure, and decreased shot-to-shot speed help capture clear, -precise images. Stabilized image zoom lets users compose photos -and video in the way they want, including while video is recording. For new -flexibility and convenience while shooting video, users can now take -snapshots at full video resolution just by tapping the screen -as video continues to record.

    - -

    To make it easier to take great pictures of people, built-in face -detection locates faces in the frame and automatically sets focus. For -more control, users can tap to focus anywhere in the preview -image.

    - -

    For capturing larger scenes, the Camera introduces a single-motion -panorama mode. In this mode, the user starts an exposure and then -slowly turns the Camera to encompass as wide a perspective as needed. The Camera -assembles the full range of continuous imagery into a single panoramic -photo.

    - -

    After taking a picture or video, users can quickly share it by email, text -message, bluetooth, social networks, and more, just by tapping the thumbnail in -the camera controls.

    - - -
    -
    - -
    A Photo Gallery widget on the home screen.
    -
    - -

    Redesigned Gallery app -with photo editor

    - -

    The Gallery app now makes it easier to manage, show, and share photos and -videos. For managing collections, a redesigned album layout -shows many more albums and offers larger thumbnails. There are many ways to sort -albums, including by time, location, people, and tags. To help pictures look -their best, the Gallery now includes a powerful photo editor. -Users can crop and rotate pictures, set levels, remove red eyes, add effects, -and much more. After retouching, users can select one or multiple pictures or -videos to share instantly over email, text messaging, bluetooth, social -networks, or other apps.

    - -

    An improved Picture Gallery widget lets users look at -pictures directly on their home screen. The widget can display pictures from a -selected album, shuffle pictures from all albums, or show a single image. After -adding the widget to the home screen, users can flick through the photo stacks -to locate the image they want, then tap to load it in Gallery.

    - -
    -
    - -
    Live Effects let you change backgrounds and use Silly Faces during video.
    -
    -
    - -

    Live Effects for transforming video

    - -

    Live Effects is a collection of graphical transformations that add interest -and fun to videos captured in the Camera app. For example, users can -change the background behind them to any stock or custom image, -for just the right setting when shooting videeo. Also available for video is -Silly Faces, a set of morphing effects that use state-of-the-art face -recognition and GPU filters to transform facial features. For example, you can -use effects such as small eyes, big mouth, big nose, face squeeze, and more. -Outside of the Camera app, Live Effects is available during video chat in the -Google Talk app.

    - -
    -
    - - -
    Snapping a screenshot.
    -
    -
    -
    - -

    Sharing with screenshots

    - -

    Users can now share what's on their screens more easily by taking -screenshots. Hardware buttons let them snap a screenshot and -store it locally. Afterward, they can view, edit, and share the screen shot in -Gallery or a similar app.

    - - -

    Cloud-connected experience

    - -
    -
    - - - - -
    The Browser tabs menu (left) lets you quickly switch browser tabs. The options menu (right) gives you new ways to manage your browsing experience.
    - -
    Benchmark comparisons of Android Browser.
    -
    -
    - -

    Android has always been cloud-connected, letting users browse the web and -sync photos, apps, games, email, and contacts — wherever they are and -across all of their devices. Android 4.0 adds new browsing and email -capabilities to let users take even more with them and keep communication -organized.

    - - -

    Powerful web -browsing

    - -

    The Android Browser offers an experience that’s as rich and convenient as a -desktop browser. It lets users instantly sync and manage Google Chrome -bookmarks from all of their accounts, jump to their favorite content -faster, and even save it for reading later in case there's no network -available.

    - -

    To get the most out of web content, users can now request full -desktop versions of web sites, rather than their mobile -versions. Users can set their preference for web sites separately for each -browser tab. For longer content, users can save a copy for -offline reading. To find and open saved pages, users can browse -a visual list that’s included with browser bookmarks and history. For better -readability and accessibility, users can increase the browser’s zoom -levels and override the system default text sizes.

    - -

    Across all types of content, the Android Browser offers dramatically improved -page rendering performance through updated versions of the -WebKit core and the V8 Crankshaft compilation engine for JavaScript. In -benchmarks run on a Nexus S device, the Android 4.0 browser showed an -improvement of nearly 220% over the Android 2.3 browser in the V8 Benchmark -Suite and more than 35% in the SunSpider 9.1 JavaScript Benchmark. When run on a -Galaxy Nexus device, the Android 4.0 browser showed improvement of nearly 550% -in the V8 benchmark and nearly 70% in the SunSpider benchmark.

    - - -

    Improved -email

    - -

    In Android 4.0, email is easier to send, read, and manage. For composing -email, improved auto-completion of recipients helps with -finding and adding frequent contacts more quickly. For easier input of frequent -text, users can now create quick responses and store them in -the app, then enter them from a convenient menu when composing. When replying to -a message, users can now toggle the message to Reply All and Forward without -changing screens.

    - -

    For easier browsing across accounts and labels, the app adds an -integrated menu of accounts and recent labels. To help users -locate and organize IMAP and Exchange email, the Email app now supports -nested mail subfolders, each with synchronization rules. Users -can also search across folders on the server, for faster results.

    - -

    For enterprises, the Email app supports EAS v14. It supports -EAS certificate authentication, provides ABQ strings for device type and mode, -and allows automatic sync to be disabled while roaming. Administrators can also -limit attachment size or disable attachments.

    - -

    For keeping track of incoming email more easily, a resizable Email -widget lets users flick through recent email right from the home -screen, then jump into the Email app to compose or reply.

    - - -
    -
    - - -
    Android Beam lets users share what they are using with a single tap.
    -
    -
    - -

    Innovation

    - -

    Android is continously driving innovation forward, pushing the boundaries of -communication and sharing with new capabilities and interactions.

    - -

    Android Beam for -NFC-based sharing

    - -

    Android Beam is an innovative, convenient feature for sharing across two -NFC-enabled devices, It lets people instantly exchange favorite apps, contacts, -music, videos — almost anything. It’s incredibly simple and convenient to -use — there’s no menu to open, application to launch, or pairing needed. -Just touch one Android-powered phone to another, then tap to send.

    - -

    For sharing apps, Android Beam pushes a link to the app's details page in -Google Play. On the other device, the Google Play client app launches and loads the -details page, for easy downloading of the app. Individual apps can build on -Android Beam to add other types of interactions, such as passing game scores, -initiating a multiplayer game or chat, and more.

    - -
    -
    - - -
    Face recognition lets you unlock your phone with your face.
    -
    -
    - -

    Face Unlock

    - -

    Android 4.0 introduces a completely new approach to securing a device, making -each person's device even more personal — Face Unlock is a new screen-lock -option that lets users unlock their devices with their faces. It takes advantage -of the device front-facing camera and state-of-the-art facial recognition -technology to register a face during setup and then to recognize it again when -unlocking the device. Users just hold their devices in front of their faces to -unlock, or use a backup PIN or pattern.

    - - -

    Wi-Fi Direct and Bluetooth HDP

    - -

    Support for Wi-Fi Direct lets users connect directly to -nearby peer devices over Wi-Fi, for more reliable, higher-speed communication. -No internet connection or tethering is needed. Through third-party apps, users -can connect to compatible devices to take advantage of new features such as -instant sharing of files, photos, or other media; streaming video or audio from -another device; or connecting to compatible printers or other devices.

    - -

    Android 4.0 also introduces built-in support for connecting to Bluetooth Health Device Profile (HDP) devices. With support from third-party apps, users can connect to wireless medical devices and sensors in hospitals, fitness centers, homes, and elsewhere.

    - - -

    New Developer Features

    - - - -

    Unified UI framework for phones, tablets, and more

    - -

    Android 4.0 brings a unified UI framework that lets developers create -elegant, innovative apps for phones, tablets, and more. It includes all of the -familiar Android 3.x interface elements and APIs — fragments, content -loaders, Action Bar, rich notifications, resizable home screen widgets, and more -— as well as new elements and APIs.

    - -

    For developers, the unified UI framework in Android 4.0 means new UI tools, -consistent design practices, simplified code and resources, and streamlined -development across the range of Android-powered devices.

    - - - -

    Communication and sharing

    - -

    Android 4.0 extends social and sharing features to any application on the -device. Applications can integrate contacts, profile data, stream items, -and calendar events from any of the user’s activities or social networks.

    - - -

    Social API

    - -

    A shared social provider and API provide a new unified store for contacts, -profile data, stream items, and photos. Any app or social network with user -permission can contribute raw contacts and make them accessible to other apps -and networks. Applications with user permission can also read profile data from -the provider and display it in their applications.

    - -

    The social API lets applications store standard contact data as well as new -types of content for any given contact, including large profile photos, stream -items, and recent activity feedback. Recent activity feedback is a standard way for -applications to “tag” a contact with common activity, such as when the user -calls the contact or sends an email or SMS message. The social provider uses the -recent activity feedback as a new signal in ranking, such as for name -auto-complete, to keep the most relevant contacts ranked closest to the top.

    - -

    Applications can also let users set up a social connection to a contact from -the People app. When the user touches Add Connection in a contact, the app -sends a public intent that other apps can handle, displaying any UI needed -to create the social connection.

    - -

    Building on the social API, developers can add powerful new interactions that -span multiple social networks and contacts sources.

    - - -

    Calendar API

    - -

    A shared calendar content provider and framework API make it easier for -developers to add calendar services to their apps.

    - -

    With user permission, any application can add events to the shared database -and manage dates, attendees, alerts, and reminders. Applications can also read -entries from the database, including events contributed by other applications, -and handle the display of event alerts and reminders. Using the calendar -provider, applications can take advantage of event data sourced from a variety -of apps and protocols, to offer innovative ways of viewing and managing a user’s -events. Apps can also use calendar data to improve the relevance of their -other content.

    - -

    For lighter-weight access to calendar services, the Calendar app defines a -set of public Intents for creating, viewing, and editing events. Rather than -needing to implement a calendar UI and integrate directly with the calendar -provider, applications can simply broadcast calendar Intents. When the Calendar -app receives the Intents, it launches the appropriate UI and stores any event -data entered. Using calendar Intents, for example, apps can let users add events -directly from lists, dialogs, or home screen widgets, such as for making -restaurant reservations or booking time with friends.

    - - -

    Visual voicemail -API

    - -

    A shared Voicemail provider and API allow developers to build applications -that contribute to a unified voicemail store. Voicemails are displayed and -played in the call log tab of the platform’s Phone app.

    - - -

    Android Beam

    - -

    Android Beam is an NFC-based feature that lets users instantly share -information about the apps they are using, just by touching two NFC-enabled -phones together. When the devices are in range — within a few centimeters -— the system sets up an NFC connection and displays a sharing UI. To share -whatever they are viewing with the other device, users just touch the screen. -

    - -

    For developers, Android Beam is a new way of triggering almost any type of -proximity-based interaction. For example, it can let users instantly exchange -contacts, set up multiplayer gaming, join a chat or video call, share a photo or -video, and more. The system provides the low-level NFC support and the sharing -UI, while the foreground app provides lightweight data to transfer to the other -device. Developers have complete control over the data that is shared and how it -is handled, so almost any interaction is possible. For larger payloads, -developers can even use Android Beam to initiate a connection and transfer the -data over Bluetooth, without the need for user-visible pairing.

    - -

    Even if developers do not add custom interactions based on Android Beam they -can still benefit from it being deeply integrated into Android. By default the -system shares the app’s Google Play URL, so it’s easy for the user to -download or purchase the app right away.

    - - -

    Modular sharing -widget

    - -

    The UI framework includes a new widget, ShareActionProvider, that lets -developers quickly embed standard share functionality and UI in the Action Bar -of their applications. Developers simply add ShareActionProvider to the menu and -set an intent that describes the desired sharing action. The system handles the -rest, building up the list of applications that can handle the share intent and -dispatching the intent when the user chooses from the menu.

    - - -

    New media capabilities

    - -

    Low-level streaming -multimedia

    - -

    Android 4.0 provides a direct, efficient path for low-level streaming -multimedia. The new path is ideal for applications that need to maintain -complete control over media data before passing it to the platform for -presentation. For example, media applications can now retrieve data from any -source, apply proprietary encryption/decryption, and then send the data to the -platform for display.

    - -

    Applications can now send processed data to the platform as a multiplexed -stream of audio/video content in MPEG-2 transport stream format. The platform -de-muxes, decodes, and renders the content. The audio track is rendered to the -active audio device, while the video track is rendered to either a Surface or a -SurfaceTexture. When rendering to a SurfaceTexture, the application can apply -subsequent graphics effects to each frame using OpenGL.

    - -

    To support this low-level streaming, the platform introduces a new native API -based on Khronos -OpenMAX AL 1.0.1. The API is implemented on the same underlying services as -the platform’s existing OpenSL ES API, so developers can make use of both APIs -together if needed. Tools support for low-level streaming multimedia will be -available in an upcoming release of the Android NDK.

    - - -

    New camera -capabilities

    - -

    Developers can take advantage of a variety of new camera features in Android -4.0. ZSL exposure, continuous focus, and image zoom let apps capture better -still and video images, including during video capture. Apps can even capture -full-resolution snapshots while shooting video. Apps can now set custom metering -regions in a camera preview, then manage white balance and exposure dynamically -for those regions. For easier focusing and image processing, a face-detection -service identifies and tracks faces in a preview and returns their screen -coordinates.

    - - -

    Media effects for -transforming images and video

    - -

    A set of high-performance transformation filters let developers apply rich -effects to any image passed as an OpenGL ES 2.0 texture. Developers can adjust -color levels and brightness, change backgrounds, sharpen, crop, rotate, add lens -distortion, and apply other effects. The transformations are processed by the -GPU, so they are fast enough for processing image frames loaded from disk, -camera, or video stream.

    - - -

    Audio remote -controls

    - -

    Android 4.0 adds a new audio remote control API that lets media applications -integrate with playback controls that are displayed in a remote view. Media -applications can integrate with a remote music playback control that’s built -into in the platform’s lock screen, allowing users to control song selection and -playback without having to unlock and navigate to the music app.

    - -

    Using the audio remote control API, any music or media app can register to -receive media button events from the remote control and then manage play state -accordingly. The application can also supply metadata to the remote control, -such as album art or image, play state, track number and description, duration, -genre, and more.

    - - -

    New media codecs and -containers

    - -

    Android 4.0 adds support for additional media types and containers to give -developers access to the formats they need. For high-quality compressed images, -the media framework adds support for WebP content. For video, the framework now -supports streaming VP8 content. For streaming multimedia, the framework supports -HTTP Live streaming protocol version 3 and encoding of ADTS-contained AAC -content. Additionally, developers can now use Matroska containers for Vorbis and -VP8 content.

    - - -

    New types of connectivity

    - -

    Wi-Fi Direct

    - -

    Developers can use a framework API to discover and connect directly to nearby -devices over a high-performance, secure Wi-Fi Direct connection. No internet -connection or hotspot is needed.

    - -

    Wi-Fi Direct opens new opportunities for developers to add innovative -features to their applications. Applications can use Wi-Fi Direct to share -files, photos, or other media between devices or between a desktop computer and -an Android-powered device. Applications could also use Wi-Fi Direct to stream -media content from a peer device such as a digital television or audio player, -connect a group of users for gaming, print files, and more.

    - - -

    Bluetooth Health Device -Profile (HDP)

    - -

    Developers can now build powerful medical applications that use Bluetooth to -communicate with wireless devices and sensors in hospitals, fitness centers, -homes, and elsewhere. Applications can collect and manage data from HDP source -devices and transmit it to backend medical applications such as records systems, -data analysis services, and others.

    - -

    Using a framework API, applications can use Bluetooth to discover nearby -devices, establish reliable or streaming data channels, and manage data -transmission. Applications can supply any IEEE 11073 Manager to retrieve and -interpret health data from Continua-certified devices such as heart-rate -monitors, blood meters, thermometers, and scales.

    - - -

    New UI components and capabilities

    - -

    Layout -enhancements

    - -

    A new layout, GridLayout, improves the performance of Android applications by -supporting flatter view hierarchies that are faster to layout and render. -Because hierarchies are flatter, developers can also manage alignments between -components that are visually related to each other even when they are not -logically related, for precise control over application UI. GridLayout is also -specifically designed to be configured by drag-and-drop design tools such as the -ADT Plug-in for Eclipse.

    - - -

    OpenGL ES texture -views

    - -

    A new TextureView object lets developers directly integrate OpenGL ES -textures as rendering targets in a UI hierarchy. The object lets developers -display and manipulate OpenGL ES rendering just as they would a normal view -object in the hierarchy, including moving, transforming, and animating the view -as needed. The TextureView object makes it easy for developers to embed camera -preview, decoded video, OpenGL game scenes, and more. TextureView can be viewed -as a more powerful version of the existing SurfaceView object, since it offers -the same benefits of access to a GL rendering surface, with the added advantage -of having that surface participate fully in the normal view hierarchy.

    - - -

    Hardware-accelerated 2D -drawing

    - -

    All Android-powered devices running Android 4.0 are required to support -hardware-accelerated 2D drawing. Developers can take advantage of this to add -great UI effects while maintaining optimal performance on high-resolution -screens, even on phones. For example, developers can rely on accelerated -scaling, rotation, and other 2D operations, as well as accelerated UI components -such as TextureView and compositing modes such as filtering, blending, and -opacity.

    - - -

    New input types and text services

    - -

    Stylus input, button -support, hover events

    - -

    Android 4.0 includes full support for stylus input events, including tilt and -distance axes, pressure, and related motion event properties. To help -applications distinguish motion events from different sources, the platform adds -distinct tool types for stylus, finger, mouse, and eraser. For improved input -from multi-button pointing devices, the platform now provides distinct primary, -secondary, and tertiary buttons, as well as back and forward buttons. -Hover-enter and hover-exit events are also added, for improved navigation and -accessibility. Developers can build on these new input features to add powerful -interactions to their apps, such as precise drawing and gesturing, handwriting -and shape recognition, improved mouse input, and others.

    - - -

    Text services API for -integrating spelling checkers

    - -

    Android 4.0 lets applications query available text services such as -dictionaries and spell checkers for word suggestions, corrections, and similar -data. The text services are external to the active IME, so developers can create -and distribute dictionaries and suggestion engines that plug into the platform. -When an application receives results from a text service — for example, -word suggestions — it can display them in a dedicated suggestion popup -window directly inside the text view, rather than relying on the IME to display -them.

    - - -

    Enhanced accessibility APIs

    - -

    Android 4.0 adds new accessibility features and an enhanced API to let -developers improve the user experience in their apps, especially on devices that -don’t have hardware buttons. For accessibility services such as screen readers -in particular, the platform offers new APIs to query window content, for easier -navigation, better feedback, and richer user interfaces.

    - - -

    Accessibility -API

    - -

    To let applications manage interactions more effectively when accessibility -features are enabled, the platform adds accessibility events for -explore-by-touch mode, scrolling, and text selection. For these and other -events, the platform can attach a new object called an accessibility record that -provides extra information about the event context.

    - -

    Using the accessibility record and related APIs, applications can now access -the view hierarchy associated with an event. Applications can query for key -properties such as parent and child nodes, available states, supported actions, -screen position, and more. Applications can also request changes to certain -properties to help manage focus and selected state. For example, an -accessibility service could use these new capabilities to add convenient -features such as screen-search by text.

    - - -

    Text-to-speech -API

    - -

    A new framework API lets developers write text-to-speech engines and make -them available to any app requesting TTS capabilities.

    - - -

    Efficient network usage

    - -

    In Android 4.0, users can see how much network data their running apps are -using. They can also set limits on data usage by network type and disable -background data usage for specific applications. In this context, developers -need to design their apps to run efficiently and follow best practices for -checking the network connection. Android 4.0 provides network APIs to let -applications meet those goals.

    - -

    As users move between networks or set limits on network data, the platform -lets applications query for connection type and availability. Developers can use -this information to dynamically manage network requests to ensure the best -experience for users. Developers can also build custom network and data-usage -options into their apps, then expose them to users directly from Settings by -means of a new system Intent.

    - - -

    Security for apps and content

    - -

    Secure management of -credentials

    - -

    Android 4.0 makes it easier for applications to manage authentication and -secure sessions. A new keychain API and underlying encrypted storage let -applications store and retrieve private keys and their corresponding certificate -chains. Any application can use the keychain API to install and store user -certificates and CAs securely.

    - - -

    Address Space Layout -Randomization

    - -

    Android 4.0 now provides address space layout randomization (ASLR) to help -protect system and third party applications from exploitation due to -memory-management issues.

    - - -

    Enhancements for Enterprise

    - -

    VPN client -API

    - -

    Developers can now build or extend their own VPN solutions on the platform -using a new VPN API and underlying secure credential storage. With user -permission, applications can configure addresses and routing rules, process -outgoing and incoming packets, and establish secure tunnels to a remote server. -Enterprises can also take advantage of a standard VPN client built into the -platform that provides access to L2TP and IPSec protocols.

    - - -

    Device policy management -for camera

    - -

    The platform adds a new policy control for administrators who manage devices -using an installed Device Policy Manager. Administrators can now remotely -disable the camera on a managed device for users working in sensitive -environments.

    - - - - - diff --git a/docs/html/sdk/android-4.0.3.jd b/docs/html/sdk/android-4.0.3.jd deleted file mode 100644 index f6dbee066a6e..000000000000 --- a/docs/html/sdk/android-4.0.3.jd +++ /dev/null @@ -1,555 +0,0 @@ -page.title=Android 4.0.3 Platform -sdk.platform.version=4.0.3 -sdk.platform.apiLevel=15 -@jd:body - - - -

    API Level: {@sdkPlatformApiLevel}

    - -

    Android {@sdkPlatformVersion} is an incremental release of the Android 4.x -(Ice Cream Sandwich) platform family. This release includes new features for -users and developers, API changes, and various bug fixes.

    - -

    For developers, the Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK. The development platform includes a -fully compliant Android library and system image as well as a set of emulator -skins, sample applications, and more. The downloadable platform includes no -external libraries.

    - -

    To start developing or testing against Android {@sdkPlatformVersion}, -use the Android SDK Manager to download the platform into your SDK. For more -information, see Adding SDK -Components. If you are new to Android, download the SDK Starter Package first.

    - -

    For a high-level overview of the new user and developer features, see the -Platform -Highlights.

    - - -

    Development Platform Revisions

    - -

    The sections below provide notes about successive revisions of the Android -{@sdkPlatformVersion} development platform for the Android SDK, as denoted by -revision number. To determine what revisions you have installed in your SDK -environment, refer to the "Installed Packages" listing in the Android SDK -Manager.

    - -

    Important: To download the new Android -4.0.x system components from the Android SDK Manager, you must first update the -SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, -the Android 4.0.x system components will not be available for download.

    - -
    - -

    - - Revision 3 (March 2012) -

    - -
    - -

    Maintenance update. The system version is 4.0.4.

    -

    Note: This system image includes support for emulator -hardware graphics acceleration when used with SDK Tools r17 or higher. -(more info)

    -
    -
    Dependencies:
    -
    SDK Tools r17 or higher is required.
    -
    - -
    -
    - -
    - -

    - - Revision 2 (January 2012) -

    - -
    - -

    Maintenance update. The system version is 4.0.3.

    -
    -
    Dependencies:
    -
    SDK Tools r14 or higher is required.
    -
    - -
    -
    - -
    - -

    - - Revision 1 (December 2011) -

    - -
    - -

    Initial release. The system version is 4.0.3.

    -
    -
    Dependencies:
    -
    SDK Tools r14 or higher is required.
    -
    - -
    -
    - -

    API Overview

    - -

    The sections below provide a technical overview of new APIs in Android 4.0.3.

    - - - - - - - -

    Social stream API in Contacts Provider

    - -

    Applications that use social stream data such as status updates and check-ins -can now sync that data with each of the user’s contacts, providing items in a -stream along with photos for each.

    - -

    The database table that contains an individual contact’s social stream is -defined by {@link android.provider.ContactsContract.StreamItems}, the Uri for -which is nested within the {@link android.provider.ContactsContract.RawContacts} -directory to which the stream items belong. Each social stream table includes -several columns for metadata about each stream item, such as an icon -representing the source (an avatar), a label for the item, the primary text -content, comments about the item (such as responses from other people), and -more. Photos associated with a stream are stored in another table, defined by -{@link android.provider.ContactsContract.StreamItemPhotos}, which is available -as a sub-directory of the {@link android.provider.ContactsContract.StreamItems} -Uri.

    - -

    See {@link android.provider.ContactsContract.StreamItems} and -{@link android.provider.ContactsContract.StreamItemPhotos} for more information.

    - -

    To read or write social stream items for a contact, an application must -request permission from the user by declaring <uses-permission -android:name="android.permission.READ_SOCIAL_STREAM"> and/or <uses-permission -android:name="android.permission.WRITE_SOCIAL_STREAM"> in their manifest files.

    - -

    Calendar Provider

    -
      -
    • Adds the class {@link android.provider.CalendarContract.Colors} to represent -a color table in the Calendar -Provider. The class provides fields for accessing -colors available for a given account. Colors are referenced by -{@link android.provider.CalendarContract.ColorsColumns#COLOR_KEY COLOR_KEY} -which must be unique for a given account name/type. These values can only be -updated by the sync adapter.
    • -
    • Adds {@link android.provider.CalendarContract.CalendarColumns#ALLOWED_AVAILABILITY ALLOWED_AVAILABILITY} -and -{@link android.provider.CalendarContract.CalendarColumns#ALLOWED_ATTENDEE_TYPES ALLOWED_ATTENDEE_TYPES} -for exchange/sync support.
    • -
    • Adds {@link android.provider.CalendarContract.AttendeesColumns#TYPE_RESOURCE} -(such as conference rooms) for attendees and -{@link android.provider.CalendarContract.EventsColumns#AVAILABILITY_TENTATIVE}, -as well as {@link android.provider.CalendarContract.EventsColumns#EVENT_COLOR_KEY} -for events.
    • -
    - -

    Home screen widgets

    - -

    Starting from Android 4.0, home screen widgets should no longer include their -own padding. Instead, the system now automatically adds padding for each widget, -based the characteristics of the current screen. This leads to a more uniform, -consistent presentation of widgets in a grid. To assist applications that host -home screen widgets, the platform provides a new method -{@link android.appwidget.AppWidgetHostView#getDefaultPaddingForWidget(android.content.Context, android.content.ComponentName, android.graphics.Rect) -getDefaultPaddingForWidget()}. Applications can call this method to get the -system-defined padding and account for it when computing the number of cells to -allocate to the widget.

    - -

    Spell-checking

    - -
      -
    • For apps that accessing spell-checker services, a new {@link -android.view.textservice.SpellCheckerSession#cancel() cancel()} method cancels -any pending and running spell-checker tasks in a session.
    • - -
    • For spell-checker services, a new suggestions flag, -{@link android.view.textservice.SuggestionsInfo#RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS}, -lets the services distinguish higher-confidence suggestions from -lower-confidence ones. For example, a spell-checker could set the flag if an -input word is not in the user dictionary but has likely suggestions, or not set -the flag if an input word is not in the dictionary and has suggestions that are -likely to be less useful. - -

      Apps connected to the spell-checker can use the {@link -android.view.textservice.SuggestionsInfo#RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS} -flag in combination with other suggestion attributes, as well as the {@link -android.view.textservice.SuggestionsInfo#getSuggestionsAttributes()} and {@link -android.view.textservice.SuggestionsInfo#getSuggestionsCount()} methods, to -determine whether to mark input words as typos and offer suggestions.

    • - -
    • A new {@link android.text.style.SuggestionSpan#FLAG_AUTO_CORRECTION} style -for text spans indicates that auto correction is about to be applied to a -word/text that the user is typing/composing. This type of suggestion is rendered -differently, to indicate the auto correction is happening.
    • -
    - -

    Bluetooth

    -

    New public methods {@link -android.bluetooth.BluetoothDevice#fetchUuidsWithSdp()} and {@link -android.bluetooth.BluetoothDevice#getUuids()} let apps determine the features -(UUIDs) supported by a remote device. In the case of {@link -android.bluetooth.BluetoothDevice#fetchUuidsWithSdp()}, the system performs a -service discovery on the remote device to get the UUIDs supported, then -broadcasts the result in an {@link -android.bluetooth.BluetoothDevice#ACTION_UUID} intent.

    - -

    UI toolkit

    - -

    New methods {@link android.app.Fragment#setUserVisibleHint(boolean) setUserVisibleHint()} and -{@link android.app.Fragment#getUserVisibleHint() getUserVisibleHint()} allow a -fragment to set a hint of whether or not it is currently user-visible. The -system defers the start of fragments that are not user-visible until the loaders -for visible fragments have run. The visibility hint is "true" by default. -

    - -

    Graphics

    - -
      -
    • New method {@link android.graphics.SurfaceTexture#setDefaultBufferSize(int -width, int height)} in {@link android.graphics.SurfaceTexture} sets the default size of the image -buffers. This method may be used to set the image size when producing images -with {@link android.graphics.Canvas} (via {@link -android.view.Surface#lockCanvas}), or OpenGL ES (via an EGLSurface).
    • -
    • Adds definitions for the enums of the GL_OES_EGL_image_external OpenGL ES extension — -{@link android.opengl.GLES11Ext#GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES}, -{@link android.opengl.GLES11Ext#GL_SAMPLER_EXTERNAL_OES}, -{@link android.opengl.GLES11Ext#GL_TEXTURE_BINDING_EXTERNAL_OES}, and -{@link android.opengl.GLES11Ext#GL_TEXTURE_EXTERNAL_OES}.
    • -
    - -

    Accessibility

    - -
      -
    • Clients of {@link android.widget.RemoteViews} can now use the method {@link -android.widget.RemoteViews#setContentDescription(int, java.lang.CharSequence) -setContentDescription()} to set and get the content description of any View in -the inflated layout.
    • - -
    • The methods {@link android.view.accessibility.AccessibilityRecord#getMaxScrollX()}, -{@link android.view.accessibility.AccessibilityRecord#getMaxScrollY()}, -{@link android.view.accessibility.AccessibilityRecord#setMaxScrollX(int) setMaxScrollX()}, and -{@link android.view.accessibility.AccessibilityRecord#setMaxScrollY(int) setMaxScrollY()} -allow apps to get and set the maximum scroll offset for an -{@link android.view.accessibility.AccessibilityRecord} object.
    • - -
    • When touch-exploration mode is enabled, a new secure setting -{@link android.provider.Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD} -indicates whether the user requests the IME to speak text entered in password fields, even when -a headset is not in use. By default, no password text is spoken unless a headset -is in use.
    • -
    - -

    Text-to-speech

    - -
      -
    • Adds the new method {@link -android.speech.tts.TextToSpeech.Engine#getFeatures(java.util.Locale) -getFeatures()}for querying and enabling network TTS support. -
    • Adds a new listener class, {@link -android.speech.tts.UtteranceProgressListener}, that engines can register to -receive notification of speech-synthesis errors.
    • -
    - -

    Database

    - -
      -
    • A new {@link android.database.CrossProcessCursorWrapper} class lets content -providers return results for a cross-process query more efficiently. The new -class is a useful building block for wrapping cursors that will be sent to -processes remotely. It can also transform normal {@link android.database.Cursor} -objects into {@link android.database.CrossProcessCursor} objects -transparently. - -

      The {@link android.database.CrossProcessCursorWrapper} class fixes common -performance issues and bugs that applications have encountered when -implementing content providers.

    • - -
    • The {@link android.database.CursorWindow#CursorWindow(java.lang.String)} -constructor now takes a name string as input. The system no longer distinguishes -between local and remote cursor windows, so {@link -android.database.CursorWindow#CursorWindow(boolean)} is now deprecated.
    • -
    - -

    Intents

    - -

    Adds new categories for targeting common types of applications on the -device, such as {@link android.content.Intent#CATEGORY_APP_BROWSER}, {@link -android.content.Intent#CATEGORY_APP_CALENDAR}, {@link -android.content.Intent#CATEGORY_APP_MAPS}, and more. - -

    Camera

    - -
      -
    • {@link android.media.MediaMetadataRetriever} adds the new constant -{@link android.media.MediaMetadataRetriever#METADATA_KEY_LOCATION} to let apps -access retrieve location information for an image or video.
    • - -
    • {@link android.media.CamcorderProfile} adds the QVGA (320x240) resolution -profiles. Quality level is represented by the -{@link android.media.CamcorderProfile#QUALITY_QVGA}.and -{@link android.media.CamcorderProfile#QUALITY_TIME_LAPSE_QVGA} constants.
    • - -
    • New methods {@link android.hardware.Camera.Parameters#setVideoStabilization(boolean) setVideoStabilization()}, -{@link android.hardware.Camera.Parameters#getVideoStabilization() setVideoStabilization()}, and {@link android.hardware.Camera.Parameters#isVideoStabilizationSupported() isVideoStabilizationSupported()} -let you check and manage video stabilization for a {@link android.hardware.Camera}.
    • -
    - -

    Permissions

    - -

    The following are new permissions:

    -
      -
    • {@link android.Manifest.permission#READ_SOCIAL_STREAM} and -{@link android.Manifest.permission#WRITE_SOCIAL_STREAM}: Allow a sync -adapter to read and write social stream data to a contact in the shared -Contacts Provider.
    • -
    - - -
    -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level -{@sdkPlatformApiLevel}), see the API Differences Report.

    -
    - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} API is assigned an integer -identifier—{@sdkPlatformApiLevel}—that is stored in the system itself. -This identifier, called the "API level", allows the system to correctly determine whether an -application is compatible with the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the -application against an Android platform that supports API level {@sdkPlatformApiLevel} or -higher. Depending on your needs, you might also need to add an -android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the -{@code <uses-sdk>} -element.

    - -

    For more information, see the API Levels -document.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • API Demos
    • -
    • Browser
    • -
    • Calculator
    • -
    • Calendar
    • -
    • Camera
    • -
    • Clock
    • -
    • Custom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    • Gallery
    • -
    -
    -
      -
    • Gestures Builder
    • -
    • Messaging
    • -
    • Music
    • -
    • People
    • -
    • Phone
    • -
    • Search
    • -
    • Settings
    • -
    • Speech Recorder
    • -
    • Widget Preview
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety of built-in -locales. In some cases, region-specific strings are available for the locales. In other cases, a -default version of the language is used. The languages that are available in the Android 3.0 system -image are listed below (with language_country/region locale descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian bokmål, Norway (nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes the following emulator skins:

    - -
      -
    • - QVGA (240x320, low density, small screen) -
    • -
    • - WQVGA400 (240x400, low density, normal screen) -
    • -
    • - WQVGA432 (240x432, low density, normal screen) -
    • -
    • - HVGA (320x480, medium density, normal screen) -
    • -
    • - WVGA800 (480x800, high density, normal screen) -
    • -
    • - WVGA854 (480x854 high density, normal screen) -
    • -
    • - WXGA720 (1280x720, extra-high density, normal screen) -
    • -
    • - WSVGA (1024x600, medium density, large screen) -
    • -
    • - WXGA (1280x800, medium density, xlarge screen) -
    • -
    - -

    To test your application on an emulator that represents the latest Android device, you can create -an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator -currently doesn't support the new on-screen navigation bar for devices without hardware navigation -buttons, so when using this skin, you must use keyboard keys Home for the Home button, -ESC for the Back button, and F2 or Page-up for the Menu button.

    - -

    However, due to performance issues in the emulator when running high-resolution screens such as -the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin -(hdpi, normal screen) to test your application.

    - diff --git a/docs/html/sdk/android-4.0.jd b/docs/html/sdk/android-4.0.jd deleted file mode 100644 index e3b13c847cdd..000000000000 --- a/docs/html/sdk/android-4.0.jd +++ /dev/null @@ -1,2059 +0,0 @@ -page.title=Android 4.0 Platform -sdk.platform.version=4.0 -sdk.platform.apiLevel=14 -@jd:body - - - - -

    API Level: {@sdkPlatformApiLevel}

    - -

    Android 4.0 is a major platform release that adds a variety of new features for users and app -developers. Besides all the new features and APIs discussed below, Android 4.0 is an important -platform release because it brings the extensive set of APIs and Holographic themes from Android 3.x -to smaller screens. As an app developer, you now have a single platform and unified API framework -that enables you to develop and publish your application with a single APK that provides an -optimized user experience for handsets, tablets, and more, when running the same version of -Android—Android 4.0 (API level 14) or greater.

    - -

    The Android {@sdkPlatformVersion} platform is available as a -downloadable component for the Android SDK so you can begin developing and testing your -applications on Android 4.0 with the Android emulator. The downloadable platform includes -an Android library and system image, as well as a set of emulator skins and -more. The downloadable platform does not include any external libraries.

    - -

    To start developing or testing against Android {@sdkPlatformVersion}, -use the Android SDK Manager to download the platform into your SDK. For more -information, see Adding SDK -Components. If you are new to Android, download the SDK Starter Package first.

    - -

    Reminder: If you've already published an -Android application, please test your application on Android {@sdkPlatformVersion} as -soon as possible to be sure your application provides the best -experience possible on the latest Android-powered devices.

    - -

    For a high-level overview of the new user and developer features in Android 4.0, see the -Platform Highlights.

    - - - -

    Revisions

    - -

    To determine what revision of the Android {@sdkPlatformVersion} platform you -have installed, refer to the "Installed Packages" listing in the Android SDK Manager.

    - -

    Important: To download the new Android -4.0 system components from the Android SDK Manager, you must first update the -SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, -the Android 4.0 system components will not be available for download.

    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 2 (December 2011) -

    - -
    -

    Maintenance update. The system version is 4.0.2.

    -
    -
    Dependencies:
    -
    SDK Tools r14 or higher is required.
    -
    -
    -
    - -
    - -

    - - Android {@sdkPlatformVersion}, Revision 1 (October 2011) -

    - -
    -

    Initial release. The system version is 4.0.1.

    -
    -
    Dependencies:
    -
    SDK Tools r14 or higher is required.
    -
    -
    -
    - - -

    API Overview

    - -

    The sections below provide a technical overview of new APIs in Android 4.0.

    - - - - - - - -

    Social APIs in Contacts Provider

    - -

    The contact APIs defined by the {@link android.provider.ContactsContract} provider have been -extended to support new social-oriented features such as a personal profile for the device owner and -the ability for users to invite individual contacts to social networks that are installed on the -device.

    - - -

    User Profile

    - -

    Android now includes a personal profile that represents the device owner, as defined by the -{@link android.provider.ContactsContract.Profile} table. Social apps that maintain a user identity -can contribute to the user's profile data by creating a new {@link -android.provider.ContactsContract.RawContacts} entry within the {@link -android.provider.ContactsContract.Profile}. That is, raw contacts that represent the device user do -not belong in the traditional raw contacts table defined by the {@link -android.provider.ContactsContract.RawContacts} Uri; instead, you must add a profile raw contact in -the table at {@link android.provider.ContactsContract.Profile#CONTENT_RAW_CONTACTS_URI}. Raw -contacts in this table are then aggregated into the single user-visible profile labeled "Me".

    - -

    Adding a new raw contact for the profile requires the {@link -android.Manifest.permission#WRITE_PROFILE} permission. Likewise, in order to read from the profile -table, you must request the {@link android.Manifest.permission#READ_PROFILE} permission. However, -most apps should not need to read the user profile, even when contributing data to the -profile. Reading the user profile is a sensitive permission and you should expect users to be -skeptical of apps that request it.

    - - -

    Invite Intent

    - -

    The {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent action allows an app -to invoke an action that indicates the user wants to add a contact to a social network. The app -receiving the app uses it to invite the specified contact to that -social network. Most apps will be on the receiving-end of this operation. For example, the -built-in People app invokes the invite intent when the user selects "Add connection" for a specific -social app that's listed in a person's contact details.

    - -

    To make your app visible as in the "Add connection" list, your app must provide a sync adapter to -sync contact information from your social network. You must then indicate to the system that your -app responds to the {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent by -adding the {@code inviteContactActivity} attribute to your app’s sync configuration file, with a -fully-qualified name of the activity that the system should start when sending the invite intent. -The activity that starts can then retrieve the URI for the contact in question from the intent’s -data and perform the necessary work to invite that contact to the network or add the person to the -user’s connections.

    - -

    See the Sample Sync -Adapter app for an example (specifically, see the contacts.xml -file).

    - - -

    Large photos

    - -

    Android now supports high resolution photos for contacts. Now, when you push a photo into a -contact record, the system processes it into both a 96x96 thumbnail (as it has previously) and a -256x256 "display photo" that's stored in a new file-based photo store (the exact dimensions that the -system chooses may vary in the future). You can add a large photo to a contact by putting a large -photo in the usual {@link android.provider.ContactsContract.CommonDataKinds.Photo#PHOTO} column of a -data row, which the system will then process into the appropriate thumbnail and display photo -records.

    - - -

    Contact Usage Feedback

    - -

    The new {@link android.provider.ContactsContract.DataUsageFeedback} APIs allow you to help track -how often the user uses particular methods of contacting people, such as how often the user uses -each phone number or e-mail address. This information helps improve the ranking for each contact -method associated with each person and provide better suggestions for contacting each person.

    - - - - - -

    Calendar Provider

    - -

    The new calendar APIs allow you to read, add, modify and delete calendars, events, attendees, -reminders and alerts, which are stored in the Calendar Provider.

    - -

    A variety of apps and widgets can use these APIs to read and modify calendar events. However, -some of the most compelling use cases are sync adapters that synchronize the user's calendar from -other calendar services with the Calendar Provider, in order to offer a unified location for all the -user's events. Google Calendar events, for example, are synchronized with the Calendar Provider by -the Google Calendar Sync Adapter, allowing these events to be viewed with Android's built-in -Calendar app.

    - -

    The data model for calendars and event-related information in the Calendar Provider is -defined by {@link android.provider.CalendarContract}. All the user’s calendar data is stored in a -number of tables defined by various subclasses of {@link android.provider.CalendarContract}:

    - -
      -
    • The {@link android.provider.CalendarContract.Calendars} table holds the calendar-specific -information. Each row in this table contains the details for a single calendar, such as the name, -color, sync information, and so on.
    • - -
    • The {@link android.provider.CalendarContract.Events} table holds event-specific information. -Each row in this table contains the information for a single event, such as the -event title, location, start time, end time, and so on. The event can occur one time or recur -multiple times. Attendees, reminders, and extended properties are stored in separate tables and -use the event’s {@code _ID} to link them with the event.
    • - -
    • The {@link android.provider.CalendarContract.Instances} table holds the start and end time for -occurrences of an event. Each row in this table represents a single occurrence. For one-time events -there is a one-to-one mapping of instances to events. For recurring events, multiple rows are -automatically generated to correspond to the multiple occurrences of that event.
    • - -
    • The {@link android.provider.CalendarContract.Attendees} table holds the event attendee or guest -information. Each row represents a single guest of an event. It specifies the type of guest the -person is and the person’s response for the event.
    • - -
    • The {@link android.provider.CalendarContract.Reminders} table holds the alert/notification data. -Each row represents a single alert for an event. An event can have multiple reminders. The number of -reminders per event is specified in {@code MAX_REMINDERS}, which is set by the sync adapter that -owns the given calendar. Reminders are specified in number-of-minutes before the event is -scheduled and specify an alarm method such as to use an alert, email, or SMS to remind -the user.
    • - -
    • The {@link android.provider.CalendarContract.ExtendedProperties} table hold opaque data fields -used by the sync adapter. The provider takes no action with items in this table except to delete -them when their related events are deleted.
    • -
    - -

    To access a user’s calendar data with the Calendar Provider, your application must request -the {@link android.Manifest.permission#READ_CALENDAR} permission (for read access) and -{@link android.Manifest.permission#WRITE_CALENDAR} (for write access).

    - - -

    Event intent

    - -

    If all you want to do is add an event to the user’s calendar, you can use an {@link -android.content.Intent#ACTION_INSERT} intent with the data defined by {@link -android.provider.CalendarContract.Events#CONTENT_URI Events.CONTENT_URI} in order to start an -activity in the Calendar app that creates new events. Using the intent does not require any -permission and you can specify event details with the following extras:

    - -
      -
    • {@link android.provider.CalendarContract.EventsColumns#TITLE Events.TITLE}: Name for the -event
    • -
    • {@link -android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME}: -Event begin time in milliseconds from the -epoch
    • -
    • {@link -android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME}: Event -end time in milliseconds from the epoch
    • -
    • {@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION}: -Location of the event
    • -
    • {@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION}: Event -description
    • -
    • {@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL}: Email addresses of those to -invite
    • -
    • {@link android.provider.CalendarContract.EventsColumns#RRULE Events.RRULE}: The recurrence -rule for the event
    • -
    • {@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL}: -Whether the event is private or public
    • -
    • {@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY}: -Whether the time period of this event allows for other events to be scheduled at the same time
    • -
    - - - - -

    Voicemail Provider

    - -

    The new Voicemail Provider allows applications to add voicemails to the -device, in order to present all the user's voicemails in a single visual presentation. For instance, -it’s possible that a user has multiple voicemail sources, such as -one from the phone’s service provider and others from VoIP or other alternative voice -services. These apps can use the Voicemail Provider APIs to add their voicemails to the device. The -built-in Phone application then presents all voicemails to the user in a unified presentation. -Although the system’s Phone application is the only application that can read all the voicemails, -each application that provides voicemails can read those that it has added to the system (but cannot -read voicemails from other services).

    - -

    Because the APIs currently do not allow third-party apps to read all the voicemails from the -system, the only third-party apps that should use the voicemail APIs are those that have voicemail -to deliver to the user.

    - -

    The {@link android.provider.VoicemailContract} class defines the content provider for the -Voicemail Provder. The subclasses {@link android.provider.VoicemailContract.Voicemails} and {@link -android.provider.VoicemailContract.Status} provide tables in which apps can -insert voicemail data for storage on the device. For an example of a voicemail provider app, see the -Voicemail Provider -Demo.

    - - - - - -

    Multimedia

    - -

    Android 4.0 adds several new APIs for applications that interact with media such as photos, -videos, and music.

    - - -

    Media Effects

    - -

    A new media effects framework allows you to apply a variety of visual effects to images and -videos. For example, image effects allow you to easily fix red-eye, convert an image to grayscale, -adjust brightness, adjust saturation, rotate an image, apply a fisheye effect, and much more. The -system performs all effects processing on the GPU to obtain maximum performance.

    - -

    For maximum performance, effects are applied directly to OpenGL textures, so your application -must have a valid OpenGL context before it can use the effects APIs. The textures to which you apply -effects may be from bitmaps, videos or even the camera. However, there are certain restrictions that -textures must meet:

    -
      -
    1. They must be bound to a {@link android.opengl.GLES20#GL_TEXTURE_2D} texture image
    2. -
    3. They must contain at least one mipmap level
    4. -
    - -

    An {@link android.media.effect.Effect} object defines a single media effect that you can apply to -an image frame. The basic workflow to create an {@link android.media.effect.Effect} is:

    - -
      -
    1. Call {@link android.media.effect.EffectContext#createWithCurrentGlContext -EffectContext.createWithCurrentGlContext()} from your OpenGL ES 2.0 context.
    2. -
    3. Use the returned {@link android.media.effect.EffectContext} to call {@link -android.media.effect.EffectContext#getFactory EffectContext.getFactory()}, which returns an instance -of {@link android.media.effect.EffectFactory}.
    4. -
    5. Call {@link android.media.effect.EffectFactory#createEffect createEffect()}, passing it an -effect name from @link android.media.effect.EffectFactory}, such as {@link -android.media.effect.EffectFactory#EFFECT_FISHEYE} or {@link -android.media.effect.EffectFactory#EFFECT_VIGNETTE}.
    6. -
    - -

    You can adjust an effect’s parameters by calling {@link android.media.effect.Effect#setParameter -setParameter()} and passing a parameter name and parameter value. Each type of effect accepts -different parameters, which are documented with the effect name. For example, {@link -android.media.effect.EffectFactory#EFFECT_FISHEYE} has one parameter for the {@code scale} of the -distortion.

    - -

    To apply an effect on a texture, call {@link android.media.effect.Effect#apply apply()} on the -{@link -android.media.effect.Effect} and pass in the input texture, it’s width and height, and the output -texture. The input texture must be bound to a {@link android.opengl.GLES20#GL_TEXTURE_2D} texture -image (usually done by calling the {@link android.opengl.GLES20#glTexImage2D glTexImage2D()} -function). You may provide multiple mipmap levels. If the output texture has not been bound to a -texture image, it will be automatically bound by the effect as a {@link -android.opengl.GLES20#GL_TEXTURE_2D} and with one mipmap level (0), which will have the same -size as the input.

    - -

    All effects listed in {@link android.media.effect.EffectFactory} are guaranteed to be supported. -However, some additional effects available from external libraries are not supported by all devices, -so you must first check if the desired effect from the external library is supported by calling -{@link android.media.effect.EffectFactory#isEffectSupported isEffectSupported()}.

    - - -

    Remote control client

    - -

    The new {@link android.media.RemoteControlClient} allows media players to enable playback -controls from remote control clients such as the device lock screen. Media players can also expose -information about the media currently playing for display on the remote control, such as track -information and album art.

    - -

    To enable remote control clients for your media player, instantiate a {@link -android.media.RemoteControlClient} with its constructor, passing it a {@link -android.app.PendingIntent} that broadcasts {@link -android.content.Intent#ACTION_MEDIA_BUTTON}. The intent must also declare the explicit {@link -android.content.BroadcastReceiver} component in your app that handles the {@link -android.content.Intent#ACTION_MEDIA_BUTTON} event.

    - -

    To declare which media control inputs your player can handle, you must call {@link -android.media.RemoteControlClient#setTransportControlFlags setTransportControlFlags()} on your -{@link android.media.RemoteControlClient}, passing a set of {@code FLAG_KEY_MEDIA_*} flags, such as -{@link android.media.RemoteControlClient#FLAG_KEY_MEDIA_PREVIOUS} and {@link -android.media.RemoteControlClient#FLAG_KEY_MEDIA_NEXT}.

    - -

    You must then register your {@link android.media.RemoteControlClient} by passing it to {@link -android.media.AudioManager#registerRemoteControlClient MediaManager.registerRemoteControlClient()}. -Once registered, the broadcast receiver you declared when you instantiated the {@link -android.media.RemoteControlClient} will receive {@link android.content.Intent#ACTION_MEDIA_BUTTON} -events when a button is pressed from a remote control. The intent you receive includes the {@link -android.view.KeyEvent} for the media key pressed, which you can retrieve from the intent with {@link -android.content.Intent#getParcelableExtra getParcelableExtra(Intent.EXTRA_KEY_EVENT)}.

    - -

    To display information on the remote control about the media playing, call {@link -android.media.RemoteControlClient#editMetadata editMetaData()} and add metadata to the returned -{@link android.media.RemoteControlClient.MetadataEditor}. You can supply a bitmap for media artwork, -numerical information such as elapsed time, and text information such as the track title. For -information on available keys see the {@code METADATA_KEY_*} flags in {@link -android.media.MediaMetadataRetriever}.

    - -

    For a sample implementation, see the Random Music Player, which -provides compatibility logic such that it enables the remote control client on Android 4.0 -devices while continuing to support devices back to Android 2.1.

    - - -

    Media player

    - -
      -
    • Streaming online media from {@link android.media.MediaPlayer} now requires the {@link -android.Manifest.permission#INTERNET} permission. If you use {@link android.media.MediaPlayer} to -play content from the Internet, be sure to add the {@link android.Manifest.permission#INTERNET} -permission to your manifest or else your media playback will not work beginning with Android -4.0.
    • - -
    • {@link android.media.MediaPlayer#setSurface(Surface) setSurface()} allows you define a {@link -android.view.Surface} to behave as the video sink.
    • - -
    • {@link android.media.MediaPlayer#setDataSource(Context,Uri,Map) setDataSource()} allows you to -send additional HTTP headers with your request, which can be useful for HTTP(S) live streaming
    • - -
    • HTTP(S) live streaming now respects HTTP cookies across requests
    • -
    - - -

    Media types

    - -

    Android 4.0 adds support for:

    -
      -
    • HTTP/HTTPS live streaming protocol version 3
    • -
    • ADTS raw AAC audio encoding
    • -
    • WEBP images
    • -
    • Matroska video
    • -
    -

    For more info, see Supported Media -Formats.

    - - - - - -

    Camera

    - -

    The {@link android.hardware.Camera} class now includes APIs for detecting faces and controlling -focus and metering areas.

    - - -

    Face detection

    - -

    Camera apps can now enhance their abilities with Android’s face detection APIs, which not -only detect the face of a subject, but also specific facial features, such as the eyes and mouth. -

    - -

    To detect faces in your camera application, you must register a {@link -android.hardware.Camera.FaceDetectionListener} by calling {@link -android.hardware.Camera#setFaceDetectionListener setFaceDetectionListener()}. You can then start -your camera surface and start detecting faces by calling {@link -android.hardware.Camera#startFaceDetection}.

    - -

    When the system detects one or more faces in the camera scene, it calls the {@link -android.hardware.Camera.FaceDetectionListener#onFaceDetection onFaceDetection()} callback in your -implementation of {@link android.hardware.Camera.FaceDetectionListener}, including an array of -{@link android.hardware.Camera.Face} objects.

    - -

    An instance of the {@link android.hardware.Camera.Face} class provides various information about -the face detected, including:

    -
      -
    • A {@link android.graphics.Rect} that specifies the bounds of the face, relative to the camera's -current field of view
    • -
    • An integer betwen 1 and 100 that indicates how confident the system is that the object is a -human face
    • -
    • A unique ID so you can track multiple faces
    • -
    • Several {@link android.graphics.Point} objects that indicate where the eyes and mouth are -located
    • -
    - -

    Note: Face detection may not be supported on some -devices, so you should check by calling {@link -android.hardware.Camera.Parameters#getMaxNumDetectedFaces()} and ensure the return -value is greater than zero. Also, some devices may not support identification of eyes and mouth, -in which case, those fields in the {@link android.hardware.Camera.Face} object will be null.

    - - -

    Focus and metering areas

    - -

    Camera apps can now control the areas that the camera uses for focus and for metering white -balance -and auto-exposure. Both features use the new {@link android.hardware.Camera.Area} class to specify -the region of the camera’s current view that should be focused or metered. An instance of the {@link -android.hardware.Camera.Area} class defines the bounds of the area with a {@link -android.graphics.Rect} and the area's weight—representing the level of importance of that -area, relative to other areas in consideration—with an integer.

    - -

    Before setting either a focus area or metering area, you should first call {@link -android.hardware.Camera.Parameters#getMaxNumFocusAreas} or {@link -android.hardware.Camera.Parameters#getMaxNumMeteringAreas}, respectively. If these return zero, then -the device does not support the corresponding feature.

    - -

    To specify the focus or metering areas to use, simply call {@link -android.hardware.Camera.Parameters#setFocusAreas setFocusAreas()} or {@link -android.hardware.Camera.Parameters#setMeteringAreas setMeteringAreas()}. Each take a {@link -java.util.List} of {@link android.hardware.Camera.Area} objects that indicate the areas to consider -for focus or metering. For example, you might implement a feature that allows the user to set the -focus area by touching an area of the preview, which you then translate to an {@link -android.hardware.Camera.Area} object and request that the camera focus on that area of the scene. -The focus or exposure in that area will continually update as the scene in the area changes.

    - - -

    Continuous auto focus for photos

    - -

    You can now enable continuous auto focusing (CAF) when taking photos. To enable CAF in your -camera app, pass {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE} -to {@link android.hardware.Camera.Parameters#setFocusMode setFocusMode()}. When ready to capture -a photo, call {@link android.hardware.Camera#autoFocus autoFocus()}. Your {@link -android.hardware.Camera.AutoFocusCallback} immediately receives a callback to indicate whether -focus was achieved. To resume CAF after receiving the callback, you must call {@link -android.hardware.Camera#cancelAutoFocus()}.

    - -

    Note: Continuous auto focus is also supported when capturing -video, using {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO}, which was -added in API level 9.

    - - -

    Other camera features

    - -
      -
    • While recording video, you can now call {@link android.hardware.Camera#takePicture -takePicture()} to save a photo without interrupting the video session. Before doing so, you should -call {@link android.hardware.Camera.Parameters#isVideoSnapshotSupported} to be sure the hardware -supports it.
    • - -
    • You can now lock auto exposure and white balance with {@link -android.hardware.Camera.Parameters#setAutoExposureLock setAutoExposureLock()} and {@link -android.hardware.Camera.Parameters#setAutoWhiteBalanceLock setAutoWhiteBalanceLock()} to prevent -these properties from changing.
    • - -
    • You can now call {@link android.hardware.Camera#setDisplayOrientation -setDisplayOrientation()} while the camera preview is running. Previously, you could call this -only before beginning the preview, but you can now change the orientation at any time.
    • -
    - - -

    Camera broadcast intents

    - -
      -
    • {@link android.hardware.Camera#ACTION_NEW_PICTURE Camera.ACTION_NEW_PICTURE}: -This indicates that the user has captured a new photo. The built-in Camera app invokes this -broadcast after a photo is captured and third-party camera apps should also broadcast this intent -after capturing a photo.
    • -
    • {@link android.hardware.Camera#ACTION_NEW_VIDEO Camera.ACTION_NEW_VIDEO}: -This indicates that the user has captured a new video. The built-in Camera app invokes this -broadcast after a video is recorded and third-party camera apps should also broadcast this intent -after capturing a video.
    • -
    - - - - - -

    Android Beam (NDEF Push with NFC)

    - -

    Android Beam is a new NFC feature that allows you to send NDEF messages from one device to -another (a process also known as “NDEF Push"). The data transfer is initiated when two -Android-powered devices that support Android Beam are in close proximity (about 4 cm), usually with -their backs touching. The data inside the NDEF message can contain any data that you wish to share -between devices. For example, the People app shares contacts, YouTube shares videos, and Browser -shares URLs using Android Beam.

    - -

    To transmit data between devices using Android Beam, you need to create an {@link -android.nfc.NdefMessage} that contains the information you want to share while your activity is in -the foreground. You must then pass the {@link android.nfc.NdefMessage} to the system in one of two -ways:

    - -
      -
    • Define a single {@link android.nfc.NdefMessage} to push while in the activity: -

      Call {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} at any time to set -the message you want to send. For instance, you might call this method and pass it your {@link -android.nfc.NdefMessage} during your activity’s {@link android.app.Activity#onCreate onCreate()} -method. Then, whenever Android Beam is activated with another device while the activity is in the -foreground, the system sends the {@link android.nfc.NdefMessage} to the other device.

    • - -
    • Define the {@link android.nfc.NdefMessage} to push at the time that Android Beam is initiated: -

      Implement {@link android.nfc.NfcAdapter.CreateNdefMessageCallback}, in which your -implementation of the {@link -android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} -method returns the {@link android.nfc.NdefMessage} you want to send. Then pass the {@link -android.nfc.NfcAdapter.CreateNdefMessageCallback} implementation to {@link -android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}.

      -

      In this case, when Android Beam is activated with another device while your activity is in the -foreground, the system calls {@link -android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} to retrieve -the {@link android.nfc.NdefMessage} you want to send. This allows you to define the {@link -android.nfc.NdefMessage} to deliver only once Android Beam is initiated, in case the contents -of the message might vary throughout the life of the activity.

    • -
    - -

    In case you want to run some specific code once the system has successfully delivered your NDEF -message to the other device, you can implement {@link -android.nfc.NfcAdapter.OnNdefPushCompleteCallback} and set it with {@link -android.nfc.NfcAdapter#setOnNdefPushCompleteCallback setNdefPushCompleteCallback()}. The system will -then call {@link android.nfc.NfcAdapter.OnNdefPushCompleteCallback#onNdefPushComplete -onNdefPushComplete()} when the message is delivered.

    - -

    On the receiving device, the system dispatches NDEF Push messages in a similar way to regular NFC -tags. The system invokes an intent with the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} -action to start an activity, with either a URL or a MIME type set according to the first {@link -android.nfc.NdefRecord} in the {@link android.nfc.NdefMessage}. For the activity you want to -respond, you can declare intent filters for the URLs or MIME types your app cares about. For more -information about Tag Dispatch see the NFC developer guide.

    - -

    If you want your {@link android.nfc.NdefMessage} to carry a URI, you can now use the convenience -method {@link android.nfc.NdefRecord#createUri createUri} to construct a new {@link -android.nfc.NdefRecord} based on either a string or a {@link android.net.Uri} object. If the URI is -a special format that you want your application to also receive during an Android Beam event, you -should create an intent filter for your activity using the same URI scheme in order to receive the -incoming NDEF message.

    - -

    You should also pass an “Android application record" with your {@link android.nfc.NdefMessage} in -order to guarantee that your application handles the incoming NDEF message, even if other -applications filter for the same intent action. You can create an Android application record by -calling {@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}, passing it -your application’s package name. When the other device receives the NDEF message with the -application record and multiple applications contain activities that handle the specified intent, -the system always delivers the message to the activity in your application (based on the matching -application record). If the target device does not currently have your application installed, the -system uses the Android application record to launch Google Play and take the user to the -application in order to install it.

    - -

    If your application doesn’t use NFC APIs to perform NDEF Push messaging, then Android provides a -default behavior: When your application is in the foreground on one device and Android Beam is -invoked with another Android-powered device, then the other device receives an NDEF message with an -Android application record that identifies your application. If the receiving device has the -application installed, the system launches it; if it’s not installed, Google Play opens and takes -the user to your application in order to install it.

    - -

    You can read more about Android Beam and other NFC features in the NFC Basics developer guide. For some example code -using Android Beam, see the Android -Beam Demo.

    - - - - - -

    Wi-Fi Direct

    - -

    Android now supports Wi-Fi Direct for peer-to-peer (P2P) connections between Android-powered -devices and other device types without a hotspot or Internet connection. The Android framework -provides a set of Wi-Fi P2P APIs that allow you to 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.

    - -

    A new package, {@link android.net.wifi.p2p}, contains all the APIs for performing peer-to-peer -connections with Wi-Fi. The primary class you need to work with is {@link -android.net.wifi.p2p.WifiP2pManager}, which you can acquire by calling {@link -android.app.Activity#getSystemService getSystemService(WIFI_P2P_SERVICE)}. The {@link -android.net.wifi.p2p.WifiP2pManager} includes APIs that allow you to:

    -
      -
    • Initialize your application for P2P connections by calling {@link -android.net.wifi.p2p.WifiP2pManager#initialize initialize()}
    • - -
    • Discover nearby devices by calling {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers -discoverPeers()}
    • - -
    • Start a P2P connection by calling {@link android.net.wifi.p2p.WifiP2pManager#connect -connect()}
    • -
    • And more
    • -
    - -

    Several other interfaces and classes are necessary as well, such as:

    -
      -
    • The {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} interface allows you to receive -callbacks when an operation such as discovering peers or connecting to them succeeds or fails.
    • - -
    • {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} interface allows you to receive -information about discovered peers. The callback provides a {@link -android.net.wifi.p2p.WifiP2pDeviceList}, from which you can retrieve a {@link -android.net.wifi.p2p.WifiP2pDevice} object for each device within range and get information such as -the device name, address, device type, the WPS configurations the device supports, and more.
    • - -
    • The {@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener} interface allows you to -receive information about a P2P group. The callback provides a {@link -android.net.wifi.p2p.WifiP2pGroup} object, which provides group information such as the owner, the -network name, and passphrase.
    • - -
    • {@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener} interface allows you to -receive information about the current connection. The callback provides a {@link -android.net.wifi.p2p.WifiP2pInfo} object, which has information such as whether a group has been -formed and who is the group owner.
    • -
    - -

    In order to use the Wi-Fi P2P APIs, your app must request the following user permissions:

    -
      -
    • {@link android.Manifest.permission#ACCESS_WIFI_STATE}
    • -
    • {@link android.Manifest.permission#CHANGE_WIFI_STATE}
    • -
    • {@link android.Manifest.permission#INTERNET} (although your app doesn’t technically connect -to the Internet, communicating to Wi-Fi Direct peers with standard java sockets requires Internet -permission).
    • -
    - -

    The Android system also broadcasts several different actions during certain Wi-Fi P2P events:

    -
      -
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}: The P2P -connection state has changed. This carries {@link -android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_P2P_INFO} with a {@link -android.net.wifi.p2p.WifiP2pInfo} object and {@link -android.net.wifi.p2p.WifiP2pManager#EXTRA_NETWORK_INFO} with a {@link android.net.NetworkInfo} -object.
    • - -
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}: The P2P state has -changed between enabled and disabled. It carries {@link -android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_STATE} with either {@link -android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_DISABLED} or {@link -android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_ENABLED}
    • - -
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}: The list of peer -devices has changed.
    • - -
    • {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}: The details for -this device have changed.
    • -
    - -

    See the {@link android.net.wifi.p2p.WifiP2pManager} documentation for more information. Also -look at the Wi-Fi Direct Demo -sample application.

    - - - - - -

    Bluetooth Health Devices

    - -

    Android now supports Bluetooth Health Profile devices, so you can create applications that use -Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, -blood meters, thermometers, and scales.

    - -

    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#HEALTH} profile type to establish a connection with the profile -proxy object.

    - -

    Once you’ve acquired the Health Profile proxy (the {@link android.bluetooth.BluetoothHealth} -object), connecting to and communicating with paired health devices involves the following new -Bluetooth classes:

    -
      -
    • {@link android.bluetooth.BluetoothHealthCallback}: 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.
    • -
    • {@link android.bluetooth.BluetoothHealthAppConfiguration}: During callbacks to your {@link -android.bluetooth.BluetoothHealthCallback}, you’ll receive an instance of this object, which -provides configuration information about the available Bluetooth health device, which you must use -to perform various operations such as initiate and terminate connections with the {@link -android.bluetooth.BluetoothHealth} APIs.
    • -
    - -

    For more information about using the Bluetooth Health Profile, see the documentation for {@link -android.bluetooth.BluetoothHealth}.

    - - - - - -

    Accessibility

    - -

    Android 4.0 improves accessibility for sight-impaired users with new explore-by-touch mode -and extended APIs that allow you to provide more information about view content or -develop advanced accessibility services.

    - - -

    Explore-by-touch mode

    - -

    Users with vision loss can now explore the screen by touching and dragging a finger across the -screen to hear voice descriptions of the content. Because the explore-by-touch mode works like a -virtual cursor, it allows screen readers to identify the descriptive text the same way that screen -readers can when the user navigates with a d-pad or trackball—by reading information provided -by {@link android.R.attr#contentDescription android:contentDescription} and {@link -android.view.View#setContentDescription setContentDescription()} upon a simulated "hover" event. So, -consider this is a reminder that you should provide descriptive text for the views in your -application, especially for {@link android.widget.ImageButton}, {@link android.widget.EditText}, -{@link android.widget.ImageView} and other widgets that might not naturally contain descriptive -text.

    - - -

    Accessibility for views

    - -

    To enhance the information available to accessibility services such as screen readers, you can -implement new callback methods for accessibility events in your custom {@link -android.view.View} components.

    - -

    It's important to first note that the behavior of the {@link -android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} method has changed in Android -4.0. As with previous version of Android, when the user enables accessibility services on the device -and an input event such as a click or hover occurs, the respective view is notified with a call to -{@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()}. Previously, the -implementation of {@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} would -initialize an {@link android.view.accessibility.AccessibilityEvent} and send it to {@link -android.view.accessibility.AccessibilityManager}. The new behavior involves some additional callback -methods that allow the view and its parents to add more contextual information to the event: -

      -
    1. When invoked, the {@link -android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} and {@link -android.view.View#sendAccessibilityEventUnchecked sendAccessibilityEventUnchecked()} methods defer -to {@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()}. -

      Custom implementations of {@link android.view.View} might want to implement {@link -android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} to -attach additional accessibility information to the {@link -android.view.accessibility.AccessibilityEvent}, but should also call the super implementation to -provide default information such as the standard content description, item index, and more. -However, you should not add additional text content in this callback—that happens -next.

    2. -
    3. Once initialized, if the event is one of several types that should be populated with text -information, the view then receives a call to {@link -android.view.View#dispatchPopulateAccessibilityEvent dispatchPopulateAccessibilityEvent()}, which -defers to the {@link android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} -callback. -

      Custom implementations of {@link android.view.View} should usually implement {@link -android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} to add additional -text content to the {@link android.view.accessibility.AccessibilityEvent} if the {@link -android.R.attr#contentDescription android:contentDescription} text is missing or -insufficient. To add more text description to the -{@link android.view.accessibility.AccessibilityEvent}, call {@link -android.view.accessibility.AccessibilityEvent#getText()}.{@link java.util.List#add add()}.

      -
    4. -
    5. At this point, the {@link android.view.View} passes the event up the view hierarchy by calling -{@link android.view.ViewGroup#requestSendAccessibilityEvent requestSendAccessibilityEvent()} on the -parent view. Each parent view then has the chance to augment the accessibility information by -adding an {@link android.view.accessibility.AccessibilityRecord}, until it -ultimately reaches the root view, which sends the event to the {@link -android.view.accessibility.AccessibilityManager} with {@link -android.view.accessibility.AccessibilityManager#sendAccessibilityEvent -sendAccessibilityEvent()}.
    6. -
    - -

    In addition to the new methods above, which are useful when extending the {@link -android.view.View} class, you can also intercept these event callbacks on any {@link -android.view.View} by extending {@link -android.view.View.AccessibilityDelegate AccessibilityDelegate} and setting it on the view with -{@link android.view.View#setAccessibilityDelegate setAccessibilityDelegate()}. -When you do, each accessibility method in the view defers the call to the corresponding method in -the delegate. For example, when the view receives a call to {@link -android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()}, it passes it to the -same method in the {@link android.view.View.AccessibilityDelegate}. Any methods not handled by -the delegate are given right back to the view for default behavior. This allows you to override only -the methods necessary for any given view without extending the {@link android.view.View} class.

    - - -

    If you want to maintain compatibility with Android versions prior to 4.0, while also supporting -the new the accessibility APIs, you can do so with the latest version of the v4 support -library (in Compatibility Package, r4) -using a set of utility classes that provide the new accessibility APIs in a backward-compatible -design.

    - - - - -

    Accessibility services

    - -

    If you're developing an accessibility service, the information about various accessibility events -has been significantly expanded to enable more advanced accessibility feedback for users. In -particular, events are generated based on view composition, providing better context information and -allowing accessibility services to traverse view hierarchies to get additional view information and -deal with special cases.

    - -

    If you're developing an accessibility service (such as a screen reader), you can access -additional content information and traverse view hierarchies with the following procedure:

    -
      -
    1. Upon receiving an {@link android.view.accessibility.AccessibilityEvent} from an application, -call the {@link android.view.accessibility.AccessibilityEvent#getRecord(int) -AccessibilityEvent.getRecord()} to retrieve a specific {@link -android.view.accessibility.AccessibilityRecord} (there may be several records attached to the -event).
    2. - -
    3. From either {@link android.view.accessibility.AccessibilityEvent} or an individual {@link -android.view.accessibility.AccessibilityRecord}, you can call {@link -android.view.accessibility.AccessibilityRecord#getSource() getSource()} to retrieve a {@link -android.view.accessibility.AccessibilityNodeInfo} object. -

      An {@link android.view.accessibility.AccessibilityNodeInfo} represents a single node -of the window content in a format that allows you to query accessibility information about that -node. The {@link android.view.accessibility.AccessibilityNodeInfo} object returned from {@link -android.view.accessibility.AccessibilityEvent} describes the event source, whereas the source from -an {@link android.view.accessibility.AccessibilityRecord} describes the predecessor of the event -source.

    4. - -
    5. With the {@link android.view.accessibility.AccessibilityNodeInfo}, you can query information -about it, call {@link -android.view.accessibility.AccessibilityNodeInfo#getParent getParent()} or {@link -android.view.accessibility.AccessibilityNodeInfo#getChild getChild()} to traverse the view -hierarchy, and even add child views to the node.
    6. -
    - -

    In order for your application to publish itself to the system as an accessibility service, it -must declare an XML configuration file that corresponds to {@link -android.accessibilityservice.AccessibilityServiceInfo}. For more information about creating an -accessibility service, see {@link -android.accessibilityservice.AccessibilityService} and {@link -android.accessibilityservice.AccessibilityService#SERVICE_META_DATA -SERVICE_META_DATA} for information about the XML configuration.

    - - -

    Other accessibility APIs

    - -

    If you're interested in the device's accessibility state, the {@link -android.view.accessibility.AccessibilityManager} has some new APIs such as:

    -
      -
    • {@link android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener} -is an interface that allows you to receive a callback whenever accessibility is enabled or -disabled.
    • -
    • {@link android.view.accessibility.AccessibilityManager#getEnabledAccessibilityServiceList - getEnabledAccessibilityServiceList()} provides information about which accessibility services - are currently enabled.
    • -
    • {@link android.view.accessibility.AccessibilityManager#isTouchExplorationEnabled()} tells - you whether the explore-by-touch mode is enabled.
    • -
    - - - - - - -

    Spell Checker Services

    - -

    A new spell checker framework allows apps to create spell checkers in a manner similar to the -input method framework (for IMEs). To create a new spell checker, you must implement a service that -extends -{@link android.service.textservice.SpellCheckerService} and extend the {@link -android.service.textservice.SpellCheckerService.Session} class to provide spelling suggestions based -on text provided by the interface's callback methods. In the {@link -android.service.textservice.SpellCheckerService.Session} callback methods, you must return the -spelling suggestions as {@link android.view.textservice.SuggestionsInfo} objects.

    - -

    Applications with a spell checker service must declare the {@link -android.Manifest.permission#BIND_TEXT_SERVICE} permission as required by the service. -The service must also declare an intent filter with {@code <action -android:name="android.service.textservice.SpellCheckerService" />} as the intent’s action and should -include a {@code <meta-data>} element that declares configuration information for the spell -checker.

    - -

    See the sample -Spell Checker Service app and -sample -Spell Checker Client app for example code.

    - - - - -

    Text-to-speech Engines

    - -

    Android’s text-to-speech (TTS) APIs have been significantly extended to allow applications to -more easily implement custom TTS engines, while applications that want to use a TTS engine have a -couple new APIs for selecting an engine.

    - - -

    Using text-to-speech engines

    - -

    In previous versions of Android, you could use the {@link android.speech.tts.TextToSpeech} class -to perform text-to-speech (TTS) operations using the TTS engine provided by the system or set a -custom engine using {@link android.speech.tts.TextToSpeech#setEngineByPackageName -setEngineByPackageName()}. In Android 4.0, the {@link -android.speech.tts.TextToSpeech#setEngineByPackageName setEngineByPackageName()} method has been -deprecated and you can now specify the engine to use with a new {@link -android.speech.tts.TextToSpeech} constructor that accepts the package name of a TTS engine.

    - -

    You can also query the available TTS engines with {@link -android.speech.tts.TextToSpeech#getEngines()}. This method returns a list of {@link -android.speech.tts.TextToSpeech.EngineInfo} objects, which include meta data such as the engine’s -icon, label, and package name.

    - - -

    Building text-to-speech engines

    - -

    Previously, custom engines required that the engine be built using an undocumented native header -file. In Android 4.0, there is a complete set of framework APIs for building TTS engines.

    - -

    The basic setup requires an implementation of {@link android.speech.tts.TextToSpeechService} that -responds to the {@link android.speech.tts.TextToSpeech.Engine#INTENT_ACTION_TTS_SERVICE} intent. The -primary work for a TTS engine happens during the {@link -android.speech.tts.TextToSpeechService#onSynthesizeText onSynthesizeText()} callback in a service -that extends {@link android.speech.tts.TextToSpeechService}. The system delivers this method two -objects:

    -
      -
    • {@link android.speech.tts.SynthesisRequest}: This contains various data including the text to -synthesize, the locale, the speech rate, and voice pitch.
    • -
    • {@link android.speech.tts.SynthesisCallback}: This is the interface by which your TTS engine -delivers the resulting speech data as streaming audio. First the engine must call {@link -android.speech.tts.SynthesisCallback#start start()} to indicate that the engine is ready to deliver -the audio, then call {@link android.speech.tts.SynthesisCallback#audioAvailable audioAvailable()}, -passing it the audio data in a byte buffer. Once your engine has passed all audio through the -buffer, call {@link android.speech.tts.SynthesisCallback#done()}.
    • -
    - -

    Now that the framework supports a true API for creating TTS engines, support for the native code -implementation has been removed. Look for a blog post about a compatibility layer -that you can use to convert your old TTS engines to the new framework.

    - -

    For an example TTS engine using the new APIs, see the Text To Speech Engine sample app.

    - - - - - - -

    Network Usage

    - -

    Android 4.0 gives users precise visibility of how much network data their applications are using. -The Settings app provides controls that allow users to manage set limits for network data usage and -even disable the use of background data for individual apps. In order to avoid users disabling your -app’s access to data from the background, you should develop strategies to use the data -connection efficiently and adjust your usage depending on the type of connection available.

    - -

    If your application performs a lot of network transactions, you should provide user settings that -allow users to control your app’s data habits, such as how often your app syncs data, whether to -perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, etc. With these -controls available to them, users are much less likely to disable your app’s access to data when -they approach their limits, because they can instead precisely control how much data your app uses. -If you provide a preference activity with these settings, you should include in its manifest -declaration an intent filter for the {@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} -action. For example:

    - -
    -<activity android:name="DataPreferences" android:label="@string/title_preferences">
    -    <intent-filter>
    -       <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
    -       <category android:name="android.intent.category.DEFAULT" />
    -    </intent-filter>
    -</activity>
    -
    - -

    This intent filter indicates to the system that this is the activity that controls your -application’s data usage. Thus, when the user inspects how much data your app is using from the -Settings app, a “View application settings" button is available that launches your -preference activity so the user can refine how much data your app uses.

    - -

    Also beware that {@link android.net.ConnectivityManager#getBackgroundDataSetting()} is now -deprecated and always returns true—use {@link -android.net.ConnectivityManager#getActiveNetworkInfo()} instead. Before you attempt any network -transactions, you should always call {@link android.net.ConnectivityManager#getActiveNetworkInfo()} -to get the {@link android.net.NetworkInfo} that represents the current network and query {@link -android.net.NetworkInfo#isConnected()} to check whether the device has a -connection. You can then check other connection properties, such as whether the device is -roaming or connected to Wi-Fi.

    - - - - - - - - -

    RenderScript

    - -

    Three major features have been added to RenderScript:

    - -
      -
    • Off-screen rendering to a framebuffer object
    • -
    • Rendering inside a view
    • -
    • RS for each from the framework APIs
    • -
    - -

    The {@link android.renderscript.Allocation} class now supports a {@link -android.renderscript.Allocation#USAGE_GRAPHICS_RENDER_TARGET} memory space, which allows you to -render things directly into the {@link android.renderscript.Allocation} and use it as a framebuffer -object.

    - -

    {@link android.renderscript.RSTextureView} provides a means to display RenderScript graphics -inside of a {@link android.view.View}, unlike {@link android.renderscript.RSSurfaceView}, which -creates a separate window. This key difference allows you to do things such as move, transform, or -animate an {@link android.renderscript.RSTextureView} as well as draw RenderScript graphics inside -a view that lies within an activity layout.

    - -

    The {@link android.renderscript.Script#forEach Script.forEach()} method allows you to call -RenderScript compute scripts from the VM level and have them automatically delegated to available -cores on the device. You do not use this method directly, but any compute RenderScript that you -write will have a {@link android.renderscript.Script#forEach forEach()} method that you can call in -the reflected RenderScript class. You can call the reflected {@link -android.renderscript.Script#forEach forEach()} method by passing in an input {@link -android.renderscript.Allocation} to process, an output {@link android.renderscript.Allocation} to -write the result to, and a {@link android.renderscript.FieldPacker} data structure in case the -RenderScript needs more information. Only one of the {@link android.renderscript.Allocation}s is -necessary and the data structure is optional.

    - - - - - - - - - -

    Enterprise

    - -

    Android 4.0 expands the capabilities for enterprise application with the following features.

    - -

    VPN services

    - -

    The new {@link android.net.VpnService} allows applications to build their own VPN (Virtual -Private Network), running as a {@link android.app.Service}. A VPN service creates an interface for a -virtual network with its own address and routing rules and performs all reading and writing with a -file descriptor.

    - -

    To create a VPN service, use {@link android.net.VpnService.Builder}, which allows you to specify -the network address, DNS server, network route, and more. When complete, you can establish the -interface by calling {@link android.net.VpnService.Builder#establish()}, which returns a {@link -android.os.ParcelFileDescriptor}.

    - -

    Because a VPN service can intercept packets, there are security implications. As such, if you -implement {@link android.net.VpnService}, then your service must require the {@link -android.Manifest.permission#BIND_VPN_SERVICE} to ensure that only the system can bind to it (only -the system is granted this permission—apps cannot request it). To then use your VPN service, -users must manually enable it in the system settings.

    - - -

    Device policies

    - -

    Applications that manage the device restrictions can now disable the camera using {@link -android.app.admin.DevicePolicyManager#setCameraDisabled setCameraDisabled()} and the {@link -android.app.admin.DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} property (applied with a {@code -<disable-camera />} element in the policy configuration file).

    - - -

    Certificate management

    - -

    The new {@link android.security.KeyChain} class provides APIs that allow you to import and access -certificates in the system key store. Certificates streamline the installation of both client -certificates (to validate the identity of the user) and certificate authority certificates (to -verify server identity). Applications such as web browsers or email clients can access the installed -certificates to authenticate users to servers. See the {@link android.security.KeyChain} -documentation for more information.

    - - - - - - - -

    Device Sensors

    - -

    Two new sensor types have been added in Android 4.0:

    - -
      -
    • {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE}: A temperature sensor that provides -the ambient (room) temperature in degrees Celsius.
    • -
    • {@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY}: A humidity sensor that provides the -relative ambient (room) humidity as a percentage.
    • -
    - -

    If a device has both {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} and {@link -android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY} sensors, you can use them to calculate the dew point -and the absolute humidity.

    - -

    The previous temperature sensor, {@link android.hardware.Sensor#TYPE_TEMPERATURE}, has been -deprecated. You should use the {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} sensor -instead.

    - -

    Additionally, Android’s three synthetic sensors have been greatly improved so they now have lower -latency and smoother output. These sensors include the gravity sensor ({@link -android.hardware.Sensor#TYPE_GRAVITY}), rotation vector sensor ({@link -android.hardware.Sensor#TYPE_ROTATION_VECTOR}), and linear acceleration sensor ({@link -android.hardware.Sensor#TYPE_LINEAR_ACCELERATION}). The improved sensors rely on the gyroscope -sensor to improve their output, so the sensors appear only on devices that have a gyroscope.

    - - - - - -

    Action Bar

    - -

    The {@link android.app.ActionBar} has been updated to support several new behaviors. Most -importantly, the system gracefully manages the action bar’s size and configuration when running on -smaller screens in order to provide an optimal user experience on all screen sizes. For example, -when the screen is narrow (such as when a handset is in portrait orientation), the action bar’s -navigation tabs appear in a “stacked bar," which appears directly below the main action bar. You can -also opt-in to a “split action bar," which places all action items in a separate bar at the bottom -of the screen when the screen is narrow.

    - - -

    Split action bar

    - -

    If your action bar includes several action items, not all of them will fit into the action bar on -a narrow screen, so the system will place more of them into the overflow menu. However, Android 4.0 -allows you to enable “split action bar" so that more action items can appear on the screen in a -separate bar at the bottom of the screen. To enable split action bar, add {@link -android.R.attr#uiOptions android:uiOptions} with {@code "splitActionBarWhenNarrow"} to either your -{@code <application>} -tag or -individual {@code -<activity>} tags -in your manifest file. When enabled, the system will add an additional bar at the bottom of the -screen for all action items when the screen is narrow (no action items will appear in the primary -action bar).

    - -

    If you want to use the navigation tabs provided by the {@link android.app.ActionBar.Tab} APIs, -but don’t need the main action bar on top (you want only the tabs to appear at the top), then enable -the split action bar as described above and also call {@link -android.app.ActionBar#setDisplayShowHomeEnabled setDisplayShowHomeEnabled(false)} to disable the -application icon in the action bar. With nothing left in the main action bar, it -disappears—all that’s left are the navigation tabs at the top and the action items at the -bottom of the screen.

    - - -

    Action bar styles

    - -

    If you want to apply custom styling to the action bar, you can use new style properties {@link -android.R.attr#backgroundStacked} and {@link android.R.attr#backgroundSplit} to apply a background -drawable or color to the stacked bar and split bar, respectively. You can also set these styles at -runtime with {@link android.app.ActionBar#setStackedBackgroundDrawable -setStackedBackgroundDrawable()} and {@link android.app.ActionBar#setSplitBackgroundDrawable -setSplitBackgroundDrawable()}.

    - - -

    Action provider

    - -

    The new {@link android.view.ActionProvider} class allows you to create a specialized handler for -action items. An action provider can define an action view, a default action behavior, and a submenu -for each action item to which it is associated. When you want to create an action item that has -dynamic behaviors (such as a variable action view, default action, or submenu), extending {@link -android.view.ActionProvider} is a good solution in order to create a reusable component, rather than -handling the various action item transformations in your fragment or activity.

    - -

    For example, the {@link android.widget.ShareActionProvider} is an extension of {@link -android.view.ActionProvider} that facilitates a “share" action from the action bar. Instead of using -traditional action item that invokes the {@link android.content.Intent#ACTION_SEND} intent, you can -use this action provider to present an action view with a drop-down list of applications that handle -the {@link android.content.Intent#ACTION_SEND} intent. When the user selects an application to use -for the action, {@link android.widget.ShareActionProvider} remembers that selection and provides it -in the action view for faster access to sharing with that app.

    - -

    To declare an action provider for an action item, include the {@code android:actionProviderClass} -attribute in the {@code -<item>} element for your activity’s options menu, with the class name of the action -provider as the value. For example:

    - -
    -<item android:id="@+id/menu_share"
    -      android:title="Share"
    -      android:showAsAction="ifRoom"
    -      android:actionProviderClass="android.widget.ShareActionProvider" />
    -
    - -

    In your activity’s {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} -callback method, retrieve an instance of the action provider from the menu item and set the -intent:

    - -
    -public boolean onCreateOptionsMenu(Menu menu) {
    -    getMenuInflater().inflate(R.menu.options, menu);
    -    ShareActionProvider shareActionProvider =
    -          (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider();
    -    // Set the share intent of the share action provider.
    -    shareActionProvider.setShareIntent(createShareIntent());
    -    ...
    -    return super.onCreateOptionsMenu(menu);
    -}
    -
    - -

    For an example using the {@link android.widget.ShareActionProvider}, see ActionBarShareActionProviderActivity in ApiDemos.

    - - -

    Collapsible action views

    - -

    Action items that provide an action view can now toggle between their action view state and -traditional action item state. Previously only the {@link android.widget.SearchView} supported -collapsing when used as an action view, but now you can add an action view for any action item and -switch between the expanded state (action view is visible) and collapsed state (action item is -visible).

    - -

    To declare that an action item that contains an action view be collapsible, include the {@code -“collapseActionView"} flag in the {@code android:showAsAction} attribute for the {@code -<item>} element in the menu’s XML file.

    - -

    To receive callbacks when an action view switches between expanded and collapsed, register an -instance of {@link android.view.MenuItem.OnActionExpandListener} with the respective {@link -android.view.MenuItem} by calling {@link android.view.MenuItem#setOnActionExpandListener -setOnActionExpandListener()}. Typically, you should do so during the {@link -android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback.

    - -

    To control a collapsible action view, you can call {@link -android.view.MenuItem#collapseActionView()} and {@link android.view.MenuItem#expandActionView()} on -the respective {@link android.view.MenuItem}.

    - -

    When creating a custom action view, you can also implement the new {@link -android.view.CollapsibleActionView} interface to receive callbacks when the view is expanded and -collapsed.

    - - -

    Other APIs for action bar

    -
      -
    • {@link android.app.ActionBar#setHomeButtonEnabled setHomeButtonEnabled()} allows you to specify -whether the icon/logo behaves as a button to navigate home or “up" (pass “true" to make it behave as -a button).
    • - -
    • {@link android.app.ActionBar#setIcon setIcon()} and {@link android.app.ActionBar#setLogo -setLogo()} allow you to define the action bar icon or logo at runtime.
    • - -
    • {@link android.app.Fragment#setMenuVisibility Fragment.setMenuVisibility()} allows you to enable -or disable the visibility of the options menu items declared by the fragment. This is useful if the -fragment has been added to the activity, but is not visible, so the menu items should be -hidden.
    • - -
    • {@link android.app.FragmentManager#invalidateOptionsMenu -FragmentManager.invalidateOptionsMenu()} -allows you to invalidate the activity options menu during various states of the fragment lifecycle -in which using the equivalent method from {@link android.app.Activity} might not be available.
    • -
    - - - - - - - - -

    User Interface and Views

    - -

    Android 4.0 introduces a variety of new views and other UI components.

    - - -

    GridLayout

    - -

    {@link android.widget.GridLayout} is a new view group that places child views in a rectangular -grid. Unlike {@link android.widget.TableLayout}, {@link android.widget.GridLayout} relies on a flat -hierarchy and does not make use of intermediate views such as table rows for providing structure. -Instead, children specify which row(s) and column(s) they should occupy (cells can span multiple -rows and/or columns), and by default are laid out sequentially across the grid’s rows and columns. -The {@link android.widget.GridLayout} orientation determines whether sequential children are by -default laid out horizontally or vertically. Space between children may be specified either by using -instances of the new {@link android.widget.Space} view or by setting the relevant margin parameters -on children.

    - -

    See ApiDemos -for samples using {@link android.widget.GridLayout}.

    - - - -

    TextureView

    - -

    {@link android.view.TextureView} is a new view that allows you to display a content stream, such -as a video or an OpenGL scene. Although similar to {@link android.view.SurfaceView}, {@link -android.view.TextureView} is unique in that it behaves like a regular view, rather than creating a -separate window, so you can treat it like any other {@link android.view.View} object. For example, -you can apply transforms, animate it using {@link android.view.ViewPropertyAnimator}, or -adjust its opacity with {@link android.view.View#setAlpha setAlpha()}.

    - -

    Beware that {@link android.view.TextureView} works only within a hardware accelerated window.

    - -

    For more information, see the {@link android.view.TextureView} documentation.

    - - -

    Switch widget

    - -

    The new {@link android.widget.Switch} widget is a two-state toggle that users can drag to one -side or the other (or simply tap) to toggle an option between two states.

    - -

    You can use the {@code android:textOn} and {@code android:textOff} attributes to specify the text -to appear on the switch when in the on and off setting. The {@code android:text} attribute also -allows you to place a label alongside the switch.

    - -

    For a sample using switches, see the switches.xml layout file -and respective Switches - activity.

    - - -

    Popup menus

    - -

    Android 3.0 introduced {@link android.widget.PopupMenu} to create short contextual menus that pop -up at an anchor point you specify (usually at the point of the item selected). Android 4.0 extends -the {@link android.widget.PopupMenu} with a couple useful features:

    -
      -
    • You can now easily inflate the contents of a popup menu from an XML menu resource with {@link -android.widget.PopupMenu#inflate inflate()}, passing it the menu resource ID.
    • -
    • You can also now create a {@link android.widget.PopupMenu.OnDismissListener} that receives a -callback when the menu is dismissed.
    • -
    - - -

    Preferences

    - -

    A new {@link android.preference.TwoStatePreference} abstract class serves as the basis for -preferences that provide a two-state selection option. The new {@link -android.preference.SwitchPreference} is an extension of {@link -android.preference.TwoStatePreference} that provides a {@link android.widget.Switch} widget in the -preference view to allow users to toggle a setting on or off without the need to open an additional -preference screen or dialog. For example, the Settings application uses a {@link -android.preference.SwitchPreference} for the Wi-Fi and Bluetooth settings.

    - - - -

    System themes

    - -

    The default theme for all applications that target Android 4.0 (by setting either {@code targetSdkVersion} or -{@code minSdkVersion} to -{@code “14"} or higher) is now the -"device default" theme: {@link android.R.style#Theme_DeviceDefault Theme.DeviceDefault}. This may be -the dark Holo theme or a different dark theme defined by the specific device.

    - -

    The {@link android.R.style#Theme_Holo Theme.Holo} family of themes are guaranteed to not change -from one device to another when running the same version of Android. If you explicitly -apply any of the {@link android.R.style#Theme_Holo Theme.Holo} themes to your activities, you can -rest assured that these themes will not change character on different devices within the same -platform version.

    - -

    If you wish for your app to blend in with the overall device theme (such as when different OEMs -provide different default themes for the system), you should explicitly apply themes from the {@link -android.R.style#Theme_DeviceDefault Theme.DeviceDefault} family.

    - - -

    Options menu button

    - -

    Beginning with Android 4.0, you'll notice that handsets no longer require a Menu hardware button. -However, there's no need for you to worry about this if your existing application provides an options menu and expects there to be a -Menu button. To ensure that existing apps continue to work as they expect, the system provides an -on-screen Menu button for apps that were designed for older versions of Android.

    - -

    For the best user experience, new and updated apps should instead use the {@link -android.app.ActionBar} to provide access to menu items and set {@code targetSdkVersion} to -{@code "14"} to take advantage of the latest framework default behaviors.

    - - - -

    Controls for system UI visibility

    - -

    Since the early days of Android, the system has managed a UI component known as the status -bar, which resides at the top of handset devices to deliver information such as the carrier -signal, time, notifications, and so on. Android 3.0 added the system bar for tablet -devices, which resides at the bottom of the screen to provide system navigation controls (Home, -Back, and so forth) and also an interface for elements traditionally provided by the status bar. In -Android 4.0, the system provides a new type of system UI called the navigation bar. You -might consider the navigation bar a re-tuned version of the system bar designed for -handsets—it provides navigation controls -for devices that don’t have hardware counterparts for navigating the system, but it leaves out the -system bar's notification UI and setting controls. As such, a device that provides the navigation -bar also has the status bar at the top.

    - -

    To this day, you can hide the status bar on handsets using the {@link -android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN} flag. In Android 4.0, the APIs that control -the system bar’s visibility have been updated to better reflect the behavior of both the system bar -and navigation bar:

    -
      -
    • The {@link android.view.View#SYSTEM_UI_FLAG_LOW_PROFILE} flag replaces the {@code -STATUS_BAR_HIDDEN} flag. When set, this flag enables “low profile" mode for the system bar or -navigation bar. Navigation buttons dim and other elements in the system bar also hide. Enabling -this is useful for creating more immersive games without distraction for the system navigation -buttons.
    • - -
    • The {@link android.view.View#SYSTEM_UI_FLAG_VISIBLE} flag replaces the {@code -STATUS_BAR_VISIBLE} flag to request the system bar or navigation bar be visible.
    • - -
    • The {@link android.view.View#SYSTEM_UI_FLAG_HIDE_NAVIGATION} is a new flag that requests -the navigation bar hide completely. Be aware that this works only for the navigation bar -used by some handsets (it does not hide the system bar on tablets). The navigation -bar returns to view as soon as the system receives user input. As such, this mode is useful -primarily for video playback or other cases in which the whole screen is needed but user input is -not required.
    • -
    - -

    You can set each of these flags for the system bar and navigation bar by calling {@link -android.view.View#setSystemUiVisibility setSystemUiVisibility()} on any view in your activity. The -window manager combines (OR-together) all flags from all views in your window and -apply them to the system UI as long as your window has input focus. When your window loses input -focus (the user navigates away from your app, or a dialog appears), your flags cease to have effect. -Similarly, if you remove those views from the view hierarchy their flags no longer apply.

    - -

    To synchronize other events in your activity with visibility changes to the system UI (for -example, hide the action bar or other UI controls when the system UI hides), you should register a -{@link android.view.View.OnSystemUiVisibilityChangeListener} to be notified when the visibility -of the system bar or navigation bar changes.

    - -

    See the -OverscanActivity class for a demonstration of different system UI options.

    - - - - - -

    Input Framework

    - -

    Android 4.0 adds support for cursor hover events and new stylus and mouse button events.

    - -

    Hover events

    - -

    The {@link android.view.View} class now supports “hover" events to enable richer interactions -through the use of pointer devices (such as a mouse or other devices that drive an on-screen -cursor).

    - -

    To receive hover events on a view, implement the {@link android.view.View.OnHoverListener} and -register it with {@link android.view.View#setOnHoverListener setOnHoverListener()}. When a hover -event occurs on the view, your listener receives a call to {@link -android.view.View.OnHoverListener#onHover onHover()}, providing the {@link android.view.View} that -received the event and a {@link android.view.MotionEvent} that describes the type of hover event -that occurred. The hover event can be one of the following:

    -
      -
    • {@link android.view.MotionEvent#ACTION_HOVER_ENTER}
    • -
    • {@link android.view.MotionEvent#ACTION_HOVER_EXIT}
    • -
    • {@link android.view.MotionEvent#ACTION_HOVER_MOVE}
    • -
    - -

    Your {@link android.view.View.OnHoverListener} should return true from {@link -android.view.View.OnHoverListener#onHover onHover()} if it handles the hover event. If your -listener returns false, then the hover event will be dispatched to the parent view as usual.

    - -

    If your application uses buttons or other widgets that change their appearance based on the -current state, you can now use the {@code android:state_hovered} attribute in a state list drawable to -provide a different background drawable when a cursor hovers over the view.

    - -

    For a demonstration of the new hover events, see the Hover class in -ApiDemos.

    - - -

    Stylus and mouse button events

    - -

    Android now provides APIs for receiving input from a stylus input device such as a digitizer -tablet peripheral or a stylus-enabled touch screen.

    - -

    Stylus input operates in a similar manner to touch or mouse input. When the stylus is in contact -with the digitizer, applications receive touch events just like they would when a finger is used to -touch the display. When the stylus is hovering above the digitizer, applications receive hover -events just like they would when a mouse pointer was being moved across the display when no buttons -are pressed.

    - -

    Your application can distinguish between finger, mouse, stylus and eraser input by querying the -“tool type" associated with each pointer in a {@link android.view.MotionEvent} using {@link -android.view.MotionEvent#getToolType getToolType()}. The currently defined tool types are: {@link -android.view.MotionEvent#TOOL_TYPE_UNKNOWN}, {@link android.view.MotionEvent#TOOL_TYPE_FINGER}, -{@link android.view.MotionEvent#TOOL_TYPE_MOUSE}, {@link android.view.MotionEvent#TOOL_TYPE_STYLUS}, -and {@link android.view.MotionEvent#TOOL_TYPE_ERASER}. By querying the tool type, your application -can choose to handle stylus input in different ways from finger or mouse input.

    - -

    Your application can also query which mouse or stylus buttons are pressed by querying the “button -state" of a {@link android.view.MotionEvent} using {@link android.view.MotionEvent#getButtonState -getButtonState()}. The currently defined button states are: {@link -android.view.MotionEvent#BUTTON_PRIMARY}, {@link android.view.MotionEvent#BUTTON_SECONDARY}, {@link -android.view.MotionEvent#BUTTON_TERTIARY}, {@link android.view.MotionEvent#BUTTON_BACK}, and {@link -android.view.MotionEvent#BUTTON_FORWARD}. For convenience, the back and forward mouse buttons are -automatically mapped to the {@link android.view.KeyEvent#KEYCODE_BACK} and {@link -android.view.KeyEvent#KEYCODE_FORWARD} keys. Your application can handle these keys to support -mouse button based back and forward navigation.

    - -

    In addition to precisely measuring the position and pressure of a contact, some stylus input -devices also report the distance between the stylus tip and the digitizer, the stylus tilt angle, -and the stylus orientation angle. Your application can query this information using {@link -android.view.MotionEvent#getAxisValue getAxisValue()} with the axis codes {@link -android.view.MotionEvent#AXIS_DISTANCE}, {@link android.view.MotionEvent#AXIS_TILT}, and {@link -android.view.MotionEvent#AXIS_ORIENTATION}.

    - -

    For a demonstration of tool types, button states and the new axis codes, see the TouchPaint - class in ApiDemos.

    - - - - - - -

    Properties

    - -

    The new {@link android.util.Property} class provides a fast, efficient, and easy way to specify a -property on any object that allows callers to generically set/get values on target objects. It also -allows the functionality of passing around field/method references and allows code to set/get values -of the property without knowing the details of what the fields/methods are.

    - -

    For example, if you want to set the value of field {@code bar} on object {@code foo}, you would -previously do this:

    -
    -foo.bar = value;
    -
    - -

    If you want to call the setter for an underlying private field {@code bar}, you would previously -do this:

    -
    -foo.setBar(value);
    -
    - -

    However, if you want to pass around the {@code foo} instance and have some other code set the -{@code bar} value, there is really no way to do it prior to Android 4.0.

    - -

    Using the {@link android.util.Property} class, you can declare a {@link android.util.Property} -object {@code BAR} on class {@code Foo} so that you can set the field on instance {@code foo} of -class {@code Foo} like this:

    -
    -BAR.set(foo, value);
    -
    - -

    The {@link android.view.View} class now leverages the {@link android.util.Property} class to -allow you to set various fields, such as transform properties that were added in Android 3.0 ({@link -android.view.View#ROTATION}, {@link android.view.View#ROTATION_X}, {@link -android.view.View#TRANSLATION_X}, etc.).

    - -

    The {@link android.animation.ObjectAnimator} class also uses the {@link android.util.Property} -class, so you can create an {@link android.animation.ObjectAnimator} with a {@link -android.util.Property}, which is faster, more efficient, and more type-safe than the string-based -approach.

    - - - - - - -

    Hardware Acceleration

    - -

    Beginning with Android 4.0, hardware acceleration for all windows is enabled by default if your -application has set either {@code targetSdkVersion} or -{@code minSdkVersion} to -{@code “14"} or higher. Hardware acceleration generally results in smoother animations, smoother -scrolling, and overall better performance and response to user interaction.

    - -

    If necessary, you can manually disable hardware acceleration with the {@code hardwareAccelerated} -attribute for individual {@code -<activity>} elements or the {@code <application>} -element. You can alternatively disable hardware acceleration for individual views by calling {@link -android.view.View#setLayerType setLayerType(LAYER_TYPE_SOFTWARE)}.

    - -

    For more information about hardware acceleration, including a list of unsupported drawing -operations, see the Hardware -Acceleration document.

    - - - -

    JNI Changes

    - -

    In previous versions of Android, JNI local references weren’t indirect handles; Android used -direct pointers. This wasn't a problem as long as the garbage collector didn't move objects, but it -seemed to work because it made it possible to write buggy code. In Android 4.0, the system now uses -indirect references in order to detect these bugs.

    - -

    The ins and outs of JNI local references are described in “Local and Global References" in JNI Tips. In Android 4.0, -CheckJNI has been enhanced to detect these errors. Watch the Android Developers Blog for an upcoming post -about common errors with JNI references and how you can fix them.

    - -

    This change in the JNI implementation only affects apps that target Android 4.0 by setting either -the {@code -targetSdkVersion} or {@code -minSdkVersion} to {@code “14"} or higher. If you’ve set these attributes to any lower value, -then JNI local references behave the same as in previous versions.

    - - - - - -

    WebKit

    -
      -
    • WebKit updated to version 534.30
    • -
    • Support for Indic fonts (Devanagari, Bengali, and Tamil, including the complex character support -needed for combining glyphs) in {@link android.webkit.WebView} and the built-in Browser
    • -
    • Support for Ethiopic, Georgian, and Armenian fonts in {@link android.webkit.WebView} and the -built-in Browser
    • -
    • Support for WebDriver makes -it easier for you to test apps that use {@link android.webkit.WebView}
    • -
    - - -

    Android Browser

    - -

    The Browser application adds the following features to support web applications:

    - - - - -

    Permissions

    - -

    The following are new permissions:

    -
      -
    • {@link android.Manifest.permission#ADD_VOICEMAIL}: Allows a voicemail service to add voicemail -messages to the device.
    • -
    • {@link android.Manifest.permission#BIND_TEXT_SERVICE}: A service that implements {@link -android.service.textservice.SpellCheckerService} must require this permission for itself.
    • -
    • {@link android.Manifest.permission#BIND_VPN_SERVICE}: A service that implements {@link -android.net.VpnService} must require this permission for itself.
    • -
    • {@link android.Manifest.permission#READ_PROFILE}: Provides read access to the {@link -android.provider.ContactsContract.Profile} provider.
    • -
    • {@link android.Manifest.permission#WRITE_PROFILE}: Provides write access to the {@link -android.provider.ContactsContract.Profile} provider.
    • -
    - - - -

    Device Features

    - -

    The following are new device features:

    -
      -
    • {@link android.content.pm.PackageManager#FEATURE_WIFI_DIRECT}: Declares that the application -uses -Wi-Fi for peer-to-peer communications.
    • -
    - - -
    -

    For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level -{@sdkPlatformApiLevel}), see the API Differences Report.

    -
    - - -

    Previous APIs

    - -

    In addition to everything above, Android 4.0 naturally supports all APIs from previous releases. -Because the Android 3.x platform is available only for large-screen devices, if you've -been developing primarily for handsets, then you might not be aware of all the APIs added to Android -in these recent releases.

    - -

    Here's a look at some of the most notable APIs you might have missed that are now available -on handsets as well:

    - -
    -
    Android 3.0
    -
    -
      -
    • {@link android.app.Fragment}: A framework component that allows you to separate distinct -elements of an activity into self-contained modules that define their own UI and lifecycle. See the -Fragments developer guide.
    • -
    • {@link android.app.ActionBar}: A replacement for the traditional title bar at the top of -the activity window. It includes the application logo in the left corner and provides a new -interface for menu items. See the -Action Bar developer guide.
    • -
    • {@link android.content.Loader}: A framework component that facilitates asynchronous -loading of data in combination with UI components to dynamically load data without blocking the -main thread. See the -Loaders developer guide.
    • -
    • System clipboard: Applications can copy and paste data (beyond mere text) to and from -the system-wide clipboard. Clipped data can be plain text, a URI, or an intent. See the -Copy and Paste developer guide.
    • -
    • Drag and drop: A set of APIs built into the view framework that facilitates drag and drop -operations. See the -Drag and Drop developer guide.
    • -
    • An all new flexible animation framework allows you to animate arbitrary properties of any -object (View, Drawable, Fragment, Object, or anything else) and define animation aspects such -as duration, interpolation, repeat and more. The new framework makes Animations in Android -simpler than ever. See the -Property Animation developer -guide.
    • -
    • RenderScript graphics and compute engine: RenderScript offers a high performance 3D -graphics rendering and compute API at the native level, which you write in the C (C99 standard), -providing the type of performance you expect from a native environment while remaining portable -across various CPUs and GPUs. See the -RenderScript developer -guide.
    • -
    • Hardware accelerated 2D graphics: You can now enable the OpenGL renderer for your -application by setting {android:hardwareAccelerated="true"} in your manifest element's <application> -element or for individual <activity> -elements. This results -in smoother animations, smoother scrolling, and overall better performance and response to user -interaction. -

      Note: If you set your application's {@code minSdkVersion} or {@code targetSdkVersion} to -{@code "14"} or higher, hardware acceleration is enabled by default.

    • -
    • And much, much more. See the Android 3.0 Platform -notes for more information.
    • -
    -
    - -
    Android 3.1
    -
    -
      -
    • USB APIs: Powerful new APIs for integrating connected peripherals with -Android applications. The APIs are based on a USB stack and services that are -built into the platform, including support for both USB host and device interactions. See the USB Host and Accessory developer guide.
    • -
    • MTP/PTP APIs: Applications can interact directly with connected cameras and other PTP -devices to receive notifications when devices are attached and removed, manage files and storage on -those devices, and transfer files and metadata to and from them. The MTP API implements the PTP -(Picture Transfer Protocol) subset of the MTP (Media Transfer Protocol) specification. See the -{@link android.mtp} documentation.
    • -
    • RTP APIs: Android exposes an API to its built-in RTP (Real-time Transport Protocol) stack, -which applications can use to manage on-demand or interactive data streaming. In particular, apps -that provide VOIP, push-to-talk, conferencing, and audio streaming can use the API to initiate -sessions and transmit or receive data streams over any available network. See the {@link -android.net.rtp} documentation.
    • -
    • Support for joysticks and other generic motion inputs.
    • -
    • See the Android 3.1 Platform -notes for many more new APIs.
    • -
    -
    - -
    Android 3.2
    -
    -
      -
    • New screens support APIs that give you more control over how your applications are -displayed across different screen sizes. The API extends the existing screen support model with the -ability to precisely target specific screen size ranges by dimensions, measured in -density-independent pixel units (such as 600dp or 720dp wide), rather than by their generalized -screen sizes (such as large or xlarge). For example, this is important in order to help you -distinguish between a 5" device and a 7" device, which would both traditionally be bucketed as -"large" screens. See the blog post, -New Tools for Managing Screen Sizes.
    • -
    • New constants for {@code <uses-feature>} to -declare landscape or portrait screen orientation requirements.
    • -
    • The device "screen size" configuration now changes during a screen orientation -change. If your app targets API level 13 or higher, you must handle the {@code "screenSize"} -configuration change if you also want to handle the {@code "orientation"} configuration change. See -{@code -android:configChanges} for more information.
    • -
    • See the Android 3.2 Platform -notes for other new APIs.
    • -
    -
    - -
    - - - - -

    API Level

    - -

    The Android {@sdkPlatformVersion} API is assigned an integer -identifier—{@sdkPlatformApiLevel}—that is stored in the system itself. -This identifier, called the "API level", allows the system to correctly determine whether an -application is compatible with the system, prior to installing the application.

    - -

    To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the -application against an Android platform that supports API level {@sdkPlatformApiLevel} or -higher. Depending on your needs, you might also need to add an -android:minSdkVersion="{@sdkPlatformApiLevel}" attribute to the -{@code <uses-sdk>} -element.

    - -

    For more information, see the API Levels -document.

    - - -

    Built-in Applications

    - -

    The system image included in the downloadable platform provides these -built-in applications:

    - - - - - - -
    -
      -
    • API Demos
    • -
    • Browser
    • -
    • Calculator
    • -
    • Calendar
    • -
    • Camera
    • -
    • Clock
    • -
    • Custom Locale
    • -
    • Dev Tools
    • -
    • Downloads
    • -
    • Email
    • -
    • Gallery
    • -
    -
    -
      -
    • Gestures Builder
    • -
    • Messaging
    • -
    • Music
    • -
    • People
    • -
    • Phone
    • -
    • Search
    • -
    • Settings
    • -
    • Speech Recorder
    • -
    • Widget Preview
    • -
    -
    - - -

    Locales

    - -

    The system image included in the downloadable SDK platform provides a variety of built-in -locales. In some cases, region-specific strings are available for the locales. In other cases, a -default version of the language is used. The languages that are available in the Android 3.0 system -image are listed below (with language_country/region locale descriptor).

    - - - - - - -
    -
      -
    • Arabic, Egypt (ar_EG)
    • -
    • Arabic, Israel (ar_IL)
    • -
    • Bulgarian, Bulgaria (bg_BG)
    • -
    • Catalan, Spain (ca_ES)
    • -
    • Czech, Czech Republic (cs_CZ)
    • -
    • Danish, Denmark(da_DK)
    • -
    • German, Austria (de_AT)
    • -
    • German, Switzerland (de_CH)
    • -
    • German, Germany (de_DE)
    • -
    • German, Liechtenstein (de_LI)
    • -
    • Greek, Greece (el_GR)
    • -
    • English, Australia (en_AU)
    • -
    • English, Canada (en_CA)
    • -
    • English, Britain (en_GB)
    • -
    • English, Ireland (en_IE)
    • -
    • English, India (en_IN)
    • -
    • English, New Zealand (en_NZ)
    • -
    • English, Singapore(en_SG)
    • -
    • English, US (en_US)
    • -
    • English, South Africa (en_ZA)
    • -
    • Spanish (es_ES)
    • -
    • Spanish, US (es_US)
    • -
    • Finnish, Finland (fi_FI)
    • -
    • French, Belgium (fr_BE)
    • -
    • French, Canada (fr_CA)
    • -
    • French, Switzerland (fr_CH)
    • -
    • French, France (fr_FR)
    • -
    • Hebrew, Israel (he_IL)
    • -
    • Hindi, India (hi_IN)
    • -
    -
    -
  • Croatian, Croatia (hr_HR)
  • -
  • Hungarian, Hungary (hu_HU)
  • -
  • Indonesian, Indonesia (id_ID)
  • -
  • Italian, Switzerland (it_CH)
  • -
  • Italian, Italy (it_IT)
  • -
  • Japanese (ja_JP)
  • -
  • Korean (ko_KR)
  • -
  • Lithuanian, Lithuania (lt_LT)
  • -
  • Latvian, Latvia (lv_LV)
  • -
  • Norwegian bokmål, Norway (nb_NO)
  • -
  • Dutch, Belgium (nl_BE)
  • -
  • Dutch, Netherlands (nl_NL)
  • -
  • Polish (pl_PL)
  • -
  • Portuguese, Brazil (pt_BR)
  • -
  • Portuguese, Portugal (pt_PT)
  • -
  • Romanian, Romania (ro_RO)
  • -
  • Russian (ru_RU)
  • -
  • Slovak, Slovakia (sk_SK)
  • -
  • Slovenian, Slovenia (sl_SI)
  • -
  • Serbian (sr_RS)
  • -
  • Swedish, Sweden (sv_SE)
  • -
  • Thai, Thailand (th_TH)
  • -
  • Tagalog, Philippines (tl_PH)
  • -
  • Turkish, Turkey (tr_TR)
  • -
  • Ukrainian, Ukraine (uk_UA)
  • -
  • Vietnamese, Vietnam (vi_VN)
  • -
  • Chinese, PRC (zh_CN)
  • -
  • Chinese, Taiwan (zh_TW)
  • -
    - -

    Note: The Android platform may support more -locales than are included in the SDK system image. All of the supported locales -are available in the Android Open Source -Project.

    - -

    Emulator Skins

    - -

    The downloadable platform includes the following emulator skins:

    - -
      -
    • - QVGA (240x320, low density, small screen) -
    • -
    • - WQVGA400 (240x400, low density, normal screen) -
    • -
    • - WQVGA432 (240x432, low density, normal screen) -
    • -
    • - HVGA (320x480, medium density, normal screen) -
    • -
    • - WVGA800 (480x800, high density, normal screen) -
    • -
    • - WVGA854 (480x854 high density, normal screen) -
    • -
    • - WXGA720 (1280x720, extra-high density, normal screen) new -
    • -
    • - WSVGA (1024x600, medium density, large screen) new -
    • -
    • - WXGA (1280x800, medium density, xlarge screen) -
    • -
    - -

    To test your application on an emulator that represents the latest Android device, you can create -an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator -currently doesn't support the new on-screen navigation bar for devices without hardware navigation -buttons, so when using this skin, you must use keyboard keys Home for the Home button, -ESC for the Back button, and F2 or Page-up for the Menu button.

    - -

    However, due to performance issues in the emulator when running high-resolution screens such as -the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin -(hdpi, normal screen) to test your application.

    - diff --git a/docs/html/sdk/api_diff/10/changes/changes-summary.html b/docs/html/sdk/api_diff/10/changes/changes-summary.html index dbb28813cf7a..ff0e47982522 100644 --- a/docs/html/sdk/api_diff/10/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/10/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/11/changes/changes-summary.html b/docs/html/sdk/api_diff/11/changes/changes-summary.html index b6af9ae7a321..18e9f5d30590 100644 --- a/docs/html/sdk/api_diff/11/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/11/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/12/changes/changes-summary.html b/docs/html/sdk/api_diff/12/changes/changes-summary.html index 2a630c25d5d0..e069d3d15776 100644 --- a/docs/html/sdk/api_diff/12/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/12/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/13/changes/changes-summary.html b/docs/html/sdk/api_diff/13/changes/changes-summary.html index 082fcfb64abc..3b1c55ad96ee 100644 --- a/docs/html/sdk/api_diff/13/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/13/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/14/changes/changes-summary.html b/docs/html/sdk/api_diff/14/changes/changes-summary.html index ccb5d26f5e1e..0cec8777bc5d 100644 --- a/docs/html/sdk/api_diff/14/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/14/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/15/changes/changes-summary.html b/docs/html/sdk/api_diff/15/changes/changes-summary.html index 0acb973bcc67..7f00168c1fbb 100644 --- a/docs/html/sdk/api_diff/15/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/15/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/3/changes/changes-summary.html b/docs/html/sdk/api_diff/3/changes/changes-summary.html index 65a37f8d3b31..4c0012a5ffe0 100644 --- a/docs/html/sdk/api_diff/3/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/3/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/4/changes/changes-summary.html b/docs/html/sdk/api_diff/4/changes/changes-summary.html index 88b8be6820fd..bbed016d3936 100644 --- a/docs/html/sdk/api_diff/4/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/4/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/5/changes/changes-summary.html b/docs/html/sdk/api_diff/5/changes/changes-summary.html index 3a06d9871cab..1f10f255d0d6 100644 --- a/docs/html/sdk/api_diff/5/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/5/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/6/changes/changes-summary.html b/docs/html/sdk/api_diff/6/changes/changes-summary.html index 77ceb255c35c..a1c39853509c 100644 --- a/docs/html/sdk/api_diff/6/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/6/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/7/changes/changes-summary.html b/docs/html/sdk/api_diff/7/changes/changes-summary.html index 330f7270e788..34d4d2543d60 100644 --- a/docs/html/sdk/api_diff/7/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/7/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/8/changes/changes-summary.html b/docs/html/sdk/api_diff/8/changes/changes-summary.html index f5fa7e64a112..504118258ac1 100644 --- a/docs/html/sdk/api_diff/8/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/8/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/api_diff/9/changes/changes-summary.html b/docs/html/sdk/api_diff/9/changes/changes-summary.html index f81cea152f9b..4bccfe5e3975 100644 --- a/docs/html/sdk/api_diff/9/changes/changes-summary.html +++ b/docs/html/sdk/api_diff/9/changes/changes-summary.html @@ -73,7 +73,7 @@ body{overflow:auto;}

    Android API Differences Report

    This report details the changes in the core Android framework API between two API Level +href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels" target="_top">API Level specifications. It shows additions, modifications, and removals for packages, classes, methods, and fields. The report also includes general statistics that characterize the extent and type of the differences.

    This report is based a comparison of the Android API specifications diff --git a/docs/html/sdk/compatibility-library.jd b/docs/html/sdk/compatibility-library.jd deleted file mode 100644 index f81e8aea2bfa..000000000000 --- a/docs/html/sdk/compatibility-library.jd +++ /dev/null @@ -1,484 +0,0 @@ -page.title=Support Package - -@jd:body - -

    - -

    Minimum API level supported: 4

    - -

    The Support Package includes static "support libraries" that you can add to your Android -application in order to use APIs that are either not available for older platform versions or that -offer "utility" APIs that aren't a part of the framework APIs. The goal is to simplify your -development by offering more APIs that you can bundle with your application so you can -worry less about platform versions.

    - -

    Note: The Support Package includes more than one support -library. Each one has a different minimum API level. For example, one library requires API -level 4 or higher, while another requires API level 13 or higher (v13 is a superset of v4 and -includes additional -support classes to work with v13 APIs). The minimum version is indicated -by the directory name, such as {@code v4/} and {@code v13/}.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the Support Package, as denoted by revision number.

    - -
    - -

    - - Support Package, revision 7 (March 2012) -

    - -
    -
    -
    Changes for v4 support library:
    -
    -
      -
    • Added {@link android.support.v4.app.ShareCompat}, which provides helper classes -for sending and receiving content for social sharing applications, including new metadata for -attributing shared data to the source app. This class also provides compatible integration with the -new {@link android.widget.ShareActionProvider} in Android 4.0.
    • -
    • Added {@link android.support.v4.app.NavUtils} and {@link -android.support.v4.app.TaskStackBuilder} to provide support for implementing the -Android Design guidelines for navigation. These -additions include a way to implement the action bar's Up button across versions. -For an example implementation of this pattern, see the AppNavigation sample in -({@code <sdk>/samples/<platform>/AppNavigation}).
    • -
    • Added {@link android.support.v4.app.NotificationCompat.Builder} to provide a -compatibility implementation of Android 3.0's {@link android.app.Notification.Builder} helper class -for creating standardized system notifications.
    • -
    -
    -
    -
    - -
    - -

    - - Support Package, revision 6 (December 2011) -

    - -
    -

    Note: Reference for support library APIs are now available with - the framework references, for example: {@link android.support.v4.app}.

    -
    -
    Changes for v4 support library:
    -
    -
      -
    • Changes to ViewPager: -
        -
      • Added extra decorative view support for {@link android.support.v4.view.ViewPager}. - Decorative views may be supplied as child views of a pager in XML layout.
      • -
      • Added {@link android.support.v4.view.PagerAdapter#getPageTitle - PagerAdapter.getPageTitle()} to supply title strings for pages, which defaults to no - title for each page.
      • -
      • Added {@link android.support.v4.view.PagerTitleStrip}, a non-interactive title - strip, that can be added as a child of ViewPager. Developers can supply text - appearance and color, as well as layout sizing and gravity information.
      • -
      • Updated {@link android.support.v4.view.PagerAdapter} methods to take ViewGroup - objects, rather than View to avoid class casting in adapter implementations.
      • -
      • Updated {@link android.support.v4.view.ViewPager} to use Launcher-style - fling behavior.
      • -
      • Bug fixes for user interface interaction and test automation.
      • -
      -
    • - -
    • Support for Fragments: -
        -
      • Changed {@code setStartDeferred()} method to {@link - android.support.v4.app.Fragment#setUserVisibleHint}.
      • -
      • Added deferred start for off-screen pages to improve performance.
      • -
      -
    • - -
    • Support for Accessiblity APIs: -
        -
      • Updated {@link android.support.v4.view.AccessibilityDelegateCompat} methods - to return empty lists instead of null.
      • -
      • Added new APIs needed by the v4 samples.
      • -
      -
    • - -
    -
    -
    -
    - -
    - -

    - - Support Package, revision 5 (December 2011) -

    - -
    -
    -
    Changes for v4 support library:
    -
    -
      -
    • Support for Accessiblity APIs: -
        -
      • Added {@link android.support.v4.view.AccessibilityDelegateCompat} - to support {@link android.view.View.AccessibilityDelegate}.
      • - -
      • Added {@link android.support.v4.view.accessibility.AccessibilityEventCompat} - to support {@link android.view.accessibility.AccessibilityEvent}.
      • - -
      • Added {@link android.support.v4.view.accessibility.AccessibilityManagerCompat} - to support {@link android.view.accessibility.AccessibilityManager}.
      • - -
      • Added {@link android.support.v4.view.accessibility.AccessibilityNodeInfoCompat} - to support {@link android.view.accessibility.AccessibilityNodeInfo}.
      • - -
      • Added {@link android.support.v4.view.accessibility.AccessibilityRecordCompat} - to support {@link android.view.accessibility.AccessibilityRecord}.
      • - -
      • Added {@link - android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat} - to support {@link android.accessibilityservice.AccessibilityServiceInfo}.
      • - -
      • Added {@link android.support.v4.view.ViewGroupCompat} - to support accessibility features in {@link android.view.ViewGroup}. -
      • - -
      • Modified {@link android.support.v4.view.ViewCompat} - to support accessibility features in {@link android.view.View}.
      • -
      -
    • - -
    • Changes to ViewPager: -
        -
      • Added support for margins between pages. - An optional {@link android.graphics.drawable.Drawable} can be provided - to fill the margins.
      • -
      • Added support for {@link android.widget.EdgeEffect}.
      • -
      • Added support for keyboard navigation
      • -
      • Added support to control how many pages are kept to either side - of the current page.
      • -
      • Improved touch physics.
      • -
      • Bug fixes for user interface behavior.
      • -
      -
    • -
    -
    -
    -
    - -
    - -

    - - Support Package, revision 4 (October 2011) -

    - -
    -
    -
    Changes for v4 support library:
    -
    -
      -
    • Added EdgeEffectCompat to - support {@link android.widget.EdgeEffect}.
    • - -
    • Added LocalBroadcastManager to allow applications to easily - register for and receive intents within a single application without - broadcasting them globally.
    • - -
    • Added support in ViewCompat to check for and set overscroll - modes for {@link android.view.View}s on Android 2.3 and later.
    • -
    • Changes to Fragment APIs: -
        -
      • Added new APIs to control the visibility of new menus.
      • -
      • Added custom animation APIs.
      • -
      • Added APIs in FragmentActivity to retain custom, - non-configuration instance data.
      • -
      • Various bug fixes.
      • -
      -
    • - -
    • Fixed a {@link android.content.Loader} bug that caused issues in - canceling {@link android.os.AsyncTask}s when running on Froyo and older - versions of the platform. The support - code now uses its own version of {@link android.os.AsyncTask} to keep the same - behavior on all platform versions.
    • - -
    -
    -
    -
    - - - -
    - - -
    - -

    - - Compatibility Package, revision 3 (July 2011) -

    - -
    -
    -
    Changes for v4 support library:
    -
    -
      -
    • Adds support for {@link android.app.Fragment.SavedState}
    • -
    • Adds {@code MotionEventCompat} to support newer {@link -android.view.MotionEvent} APIs
    • -
    • Adds {@code VelocityTrackerCompat} to support a newer {@link -android.view.VelocityTracker} APIs
    • -
    • Adds {@code ViewConfigurationCompat} to support a newer {@link -android.view.ViewConfiguration} APIs
    • -
    • All new APIs (available only in the support library) that allow you to create UIs -with horizontal paging, allowing users to swipe left and right between content views. Classes to -support this include: -
        -
      • {@code ViewPager}: A {@link android.view.ViewGroup} that manages the -layout for the child views, which the user can swipe between.
      • -
      • {@code PagerAdapter}: An adapter that populates the {@code ViewPager} with the -views that represent each page.
      • -
      • {@code FragmentPagerAdapter}: An extension of {@code PagerAdapter} for flipping -between fragments.
      • -
      • {@code FragmentStatePagerAdapter}: An extension of {@code PagerAdapter} for -flipping between fragments that uses the library's support for {@link -android.app.Fragment.SavedState}.
      • -
      -
    • -
    -
    -
    New v13 support library:
    -
    -
      -
    • Includes the {@code FragmentPagerAdapter} and {@code FragmentStatePagerAdapter} -to support the horizontal paging. -

      These are exactly the same as the APIs added to the v4 support library, but rely on -other platform components in Android 3.2. Use this library instead of v4 if you're developing for -Android 3.2 and higher (all other APIs in the v4 library are already available with API level -13).

      -
    • -
    -
    -
    -
    - -
    - - -
    - -

    - - Compatibility Package, revision 2 (May 2011) -

    - -
    -
    -
    Changes for v4 library:
    -
    -
      -
    • Support for fragment animations
    • -
    • Fix {@code android.support.v4.app.Fragment#onActivityResult Fragment.onActivityResult()} - bug
    • -
    -
    -
    -
    - -
    - - -
    - -

    - - Compatibility Package, revision 1 (March 2011) -

    - -
    -

    Initial release with the v4 library.

    -
    - -
    - - - -

    Downloading the Support Package

    - -

    The Support Package is provided as a downloadable package from the Android SDK -Manager. To install:

    - -
      -
    1. Launch the Android SDK Manager. -

      From Eclipse, you can select Window -> Android SDK Manager. Or, launch {@code SDK Manager.exe} from -the {@code <sdk>/} directory (on Windows only) or {@code android} from the {@code -<sdk>/tools/} directory.

    2. -
    3. Expand the Android Repository, check Android Support package -and click Install selected.
    4. -
    5. Proceed to install the package.
    6. -
    - -

    When done, all files (including source code, samples, and the {@code .jar} files) are saved -into the <sdk>/extras/android/support/ directory. This directory contains -each of the different support libraries, such as the library for API level 4 and up and the library -for API level 13 and up, each named with the respective version (such as {@code v4/}).

    - - -

    Setting Up a Project to Use a Library

    - -

    To add one of the libraries to your Android project:

    -
      -
    1. In your Android project, create a directory named {@code libs} at the root of your -project (next to {@code src/}, {@code res/}, etc.)
    2. -
    3. Locate the JAR file for the library you want to use and copy it into the {@code -libs/} directory. -

      For example, the library that supports API level 4 and up is located at {@code -<sdk>/extras/android/support/v4/android-support-v4.jar}.

      -
    4. -
    5. Add the JAR to your project build path. -

      In Eclipse, right-click the JAR file in the Package Explorer, select Build -Path > Add to Build Path.

      -
    6. -
    - -

    Your application is now ready to use the library APIs. All the -provided APIs are available in the {@code android.support} package (for -example, {@code android.support.v4}).

    - -

    Tip: To see the library APIs in action, take a look at the sample -apps in {@code <sdk>/extras/android/support/<version>/samples/}.

    - -

    Warning: Be certain that you not confuse the standard -{@code android} packages with those in {@code android.support} library. Some code completion tools -might -get this wrong, especially if you're building against recent versions of the platform. To be safe, -keep your build target set to the same version as you have defined for your {@code android:minSdkVersion} -and double check the import statements for classes that also exist in the support library, such as -{@code SimpleCursorAdapter}.

    - - -

    Using the v4 Library APIs

    - -

    The support library for v4 provides access to several classes introduced with Android 3.0 and -beyond, plus some updated version of existing classes, and even some APIs that currently don't -exist in the Android platform. Some of the most useful and notable classes that have -counterparts in the v4 support library are:

    - -
      -
    • {@link android.app.Fragment}
    • -
    • {@link android.app.FragmentManager}
    • -
    • {@link android.app.FragmentTransaction}
    • -
    • {@link android.app.ListFragment}
    • -
    • {@link android.app.DialogFragment}
    • -
    • {@link android.app.LoaderManager}
    • -
    • {@link android.content.Loader}
    • -
    • {@link android.content.AsyncTaskLoader}
    • -
    • {@link android.content.CursorLoader}
    • -
    - -

    For each of the classes above (and others not listed), the APIs work almost exactly the same -as the counterparts in the latest Android platform. Thus, you can usually refer to -the online documentation for information about the supported APIs. There are some -differences, however. Most notably:

    - -
      -
    • When creating an activity to use fragments, you must declare your activity to extend the -{@link android.support.v4.app.FragmentActivity} class (instead of the traditional -{@link android.app.Activity} class).
    • -
    • To manage your fragments and loaders, you must use the methods - {@link android.support.v4.app.FragmentActivity#getSupportFragmentManager - FragmentActivity.getSupportFragmentManager()} and - {@link android.support.v4.app.FragmentActivity#getSupportLoaderManager - FragmentActivity.getSupportLoaderManager()} (instead of the - {@link android.app.Activity#getFragmentManager()} and - {@link android.app.Activity#getLoaderManager()} methods).
    • -
    • The {@link android.app.ActionBar} is not supported by the library. -However, when creating your Options -Menu, you can declare which items should be added to the Action Bar when it's available (on -Android 3.0 or later). You can do so with the -{@link android.support.v4.view.MenuCompat#setShowAsAction MenuCompat.setShowAsAction()} method, for -example: -
      -public boolean onCreateOptionsMenu(Menu menu) {
      -    MenuInflater inflater = getMenuInflater();
      -    inflater.inflate(R.menu.options, menu);
      -    MenuCompat.setShowAsAction(menu.findItem(R.id.action_search), 1);
      -    return true;
      -}
      -
      -

      Also see the Action Bar -Compatibility sample for a demonstration of how to use {@link android.app.ActionBar} on Android -3.0+ and also support action bar functionality on older versions.

      -
    • -
    - -

    Tip: To enable the Holographic theme on devices -running Android 3.0 or higher, declare in your manifest file that your application targets -API level 11, for example:

    -
    -<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="11" />
    -
    -

    This way, your application automatically receives the Holographic theme and the Action Bar for -each activity when running on Android 3.0 and higher.

    -
    - -

    For more information about how you can optimize your application for the latest -Android-powered devices, read Optimizing -Apps for Android 3.0.

    - - -

    Reference Docs

    - -

    The reference documentation for the Support Packages is included as part of the Android -online developer documentation:

    - - - - -

    Samples

    - -

    If you want to see some code that uses the support libraries, samples are included with the -Support Package, inside each support library directory, for example; {@code -<sdk>/extras/android/support/v4/samples/}. You can also view these samples as part of the -Android online developer documentation:

    - - - -

    Additionally, the Google I/O App is a complete -application that uses the v4 support library to provide a single APK for both handsets and tablets -and also demonstrates some of Android's best practices in Android UI design.

    diff --git a/docs/html/sdk/download.jd b/docs/html/sdk/download.jd deleted file mode 100644 index af256096139c..000000000000 --- a/docs/html/sdk/download.jd +++ /dev/null @@ -1,93 +0,0 @@ -page.title=Download an Archived Android SDK -hide_license_footer=true - -@jd:body - - - -
    -

    Please carefully review the Android SDK License Agreement before downloading the SDK. -The License Agreement constitutes a contract between you and Google with respect to your use of the -SDK.

    -

    Note: You must agree to this license agreement in order to -download one of the archived SDKs, because these SDK packages contain Google software (whereas, the -current SDK packages do not require a -license agreement, because they contain only the open sourced SDK tools).

    - - - -

    - - -

    -

    - -

    -

    - -

    -
    - - - - - - - - - - - - diff --git a/docs/html/sdk/eclipse-adt.jd b/docs/html/sdk/eclipse-adt.jd deleted file mode 100644 index e117118b8d04..000000000000 --- a/docs/html/sdk/eclipse-adt.jd +++ /dev/null @@ -1,1413 +0,0 @@ -page.title=ADT Plugin for Eclipse -adt.zip.version=18.0.0 -adt.zip.download=ADT-18.0.0.zip -adt.zip.bytes=12834793 -adt.zip.checksum=b446fa157ed97af79d1e21629201efbb - -@jd:body - - - -

    Android Development Tools (ADT) is a plugin for the Eclipse IDE -that is designed to give you a powerful, integrated environment in which -to build Android applications.

    - -

    ADT extends the capabilities of Eclipse to let you quickly set up new Android -projects, create an application UI, add packages based on the Android -Framework API, debug your applications using the Android SDK tools, and even -export signed (or unsigned) {@code .apk} files in order to distribute your application.

    - -

    Developing in Eclipse with ADT is highly recommended and is the fastest way -to get started. With the guided project setup it provides, as well as tools -integration, custom XML editors, and debug output pane, ADT gives you an -incredible boost in developing Android applications.

    - -

    This document provides step-by-step instructions on how to download the ADT -plugin and install it into your Eclipse development environment. Note that -before you can install or use ADT, you must have compatible versions of both the -Eclipse IDE and the Android SDK installed. For details, make sure to read Installing the ADT Plugin, below.

    - -

    If you are already using ADT, this document also provides instructions on -how to update ADT to the latest version or how to uninstall it, if necessary. -

    - -

    For information about the features provided by the ADT plugin, such as code -editor features, SDK tool integration, and the graphical layout editor (for drag-and-drop layout -editing), see the Android Developer Tools -document.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the ADT Plugin, as denoted by revision number.

    - -

    For a summary of all known issues in ADT, see http://tools.android.com/knownissues.

    - - - - - -
    - - -ADT 18.0.0 (April 2012) -
    -
    -
    Dependencies:
    - -
    -
      -
    • Java 1.6 or higher is required for ADT 18.0.0.
    • -
    • Eclipse Helios (Version 3.6.2) or higher is required for ADT 18.0.0.
    • -
    • ADT 18.0.0 is designed for use with SDK Tools - r18. If you haven't already installed SDK Tools r18 into your SDK, use the Android SDK - Manager to do so.
    • -
    -
    - -
    Bug fixes:
    -
    -
      -
    • Fixed problem where exporting release package does not recompile libraries in release - mode. - (Issue 27940)
    • -
    -
    - -
    - -
    -
    - - -
    - - -ADT 17.0.0 (March 2012) -
    -
    -
    Dependencies:
    - -
    -
      -
    • Java 1.6 or higher is required for ADT 17.0.0.
    • -
    • Eclipse Helios (Version 3.6.2) or higher is required for ADT 17.0.0.
    • -
    • ADT 17.0.0 is designed for use with SDK Tools - r17. If you haven't already installed SDK Tools r17 into your SDK, use the Android SDK - Manager to do so.
    • -
    -
    - -
    General improvements:
    -
    -
      -
    • New build features -
        -
      • Added feature to automatically setup JAR dependencies. Any {@code .jar} files in the - {@code /libs} folder are added to the build configuration (similar to how the Ant build - system works). Also, {@code .jar} files needed by library projects are also automatically - added to projects that depend on those library projects. - (more - info)
      • -
      • Added a feature that allows you to run some code only in debug mode. Builds now -generate a class called {@code BuildConfig} containing a {@code DEBUG} constant that is -automatically set according to your build type. You can check the ({@code BuildConfig.DEBUG}) -constant in your code to run debug-only functions.
      • -
      • Added support for custom views with custom attributes in libraries. Layouts using -custom attributes must use the namespace URI {@code http://schemas.android.com/apk/res-auto} instead -of the URI that includes the app package name. This URI is replaced with the app specific one at -build time.
      • -
      -
    • -
    • Improved Lint features. See the SDK Tools r17 -release notes.
    • -
    • Improved the Lint user interface -
        -
      • Added Run Lint toolbar action with a dropdown menu for selecting -specific (or all) projects, clearing results and other actions.
      • -
      • Updated the results window to be organized as a tree rather than a flat list. Each -issue type has a single top level item, which makes it easier to quickly scan through the reported -issues and narrow down to the issues you are most interested in.
      • -
      • Added many new toolbar actions to the results window, including expand/collapse, -ignore in file, ignore in project, ignore everywhere, show options, and configure columns.
      • -
      • Added new column options for the Lint Warnings tab, such as -category, priority, project, file and line. The column selection (as well as the column sizes) are -persisted. You can also click on columns to sort by those values.
      • -
      • Added Enable All and Disable All buttons to the Lint Options dialog, and a search -filter textbox to filter by issue id, summary and severity.
      • -
      -
    • -
    • Added Quick Outline for XML editors (Ctrl-O, Command-O). This feature shows the structure -of the current file including icons and ids, lets you filter and quickly jump to specific ids.
    • -
    • Updated the resource chooser to shows the resolved value for resources. For example, -when selecting {@code @string/hello} the chooser displays a resolved value such as "Hello World"). -The resource chooser also now allows you to edit the chosen value directly.
    • -
    • Updated Layout Editor so that it does not assign default ids to layouts, includes and -merge tags. This behavior tended to pollute the namespace with a lot of unused resources since -layouts are not usually manipulated via code, or referenced from XML. (The RelativeLayout editor -automatically assigns ids to views without ids when pointing to them.)
    • -
    • Added ability to export screenshots from the Layout Editor
    • -
    -
    - -
    Bug fixes:
    -
    -
      -
    • Fixed problem using Layout Editor with {@link android.widget.SlidingDrawer} which could - not be dragged into the layout on some platforms.
    • -
    • Fixed preview rendering for {@link android.widget.SlidingDrawer} and - {@link android.widget.TabHost}. - (Issue 23022).
    • -
    • Fixed issues that could prevent layout rendering due to unresolvable resources. - (Issue 21046, - Issue 21051)
    • -
    • Fixed a bug in resource chooser which made some types of framework resources impossible to -select. (Issue 20589)
    • -
    • Fixed a bug in the formatter where a certain whitespace pattern could result in a - non-space character getting deleted. - (Issue 23940)
    • -
    • Fixed a locale bug affecting Turkish locales in particular. - (Issue 23747)
    • -
    • Fixed issue where dex complains about duplicate classes in cases where a Library - Project depends on the same jar files or Java-only projects.
    • -
    • Fixed issue where test projects had to independently reference the library projects used - by an app project. Now referencing only the app project is enough.
    • -
    -
    - -
    - -
    -
    - -
    - - -ADT 16.0.1 (December 2011) -
    -
    -
    Dependencies:
    - -
    -
      -
    • Eclipse Helios (Version 3.6) or higher is required for ADT 16.0.1.
    • -
    • ADT 16.0.1 is designed for use with SDK Tools - r16. If you haven't already installed SDK Tools r16 into your SDK, use the Android SDK - Manager to do so.
    • -
    -
    - -
    Bug fixes:
    -
    -
      -
    • Fixed build issue where the 9-patch could be packaged as normal bitmap in some cases.
    • -
    • Fixed minor issues in the Lint - tool.
    • -
    • Fixed minor issues in the SDK Manager.
    • -
    -
    -
    - -
    -
    - - -
    - - -ADT 16.0.0 (December 2011) -
    -
    -
    Dependencies:
    - -
    -
      -
    • Eclipse Helios (Version 3.6) or higher is required for ADT -16.0.0.
    • -
    • ADT 16.0.0 is designed for use with SDK Tools r16. If you haven't already installed SDK Tools -r16 into your SDK, use the Android SDK Manager to do so.
    • -
    -
    - -
    General improvements:
    -
    -
      -
    • Added Lint tool to detect common errors in Android projects. (more info)
    • -
    -
    -
    - -
    -
    - - -
    - - -ADT 15.0.1 (November 2011) -
    -
    -
    Dependencies:
    - -
    ADT 15.0.1 is designed for use with SDK Tools r15. - If you haven't already installed SDK Tools r15 into your SDK, use the Android SDK Manager to - do so.
    - -
    Bug fixes:
    -
    -
      -
    • Fixed how source files are attached to library project .jar files.
    • -
    • Fixed how the bin/ folder for library projects are refreshed. This ensures that parent projects pick up changes in library projects.
    • -
    • Fixed how a parent project's library container is updated when a library project is recompiled. This ensures that parent projects are - recompiled when code in a library project changes.
    • -
    • Fixed how res/ folders are checked in library projects. This ensures that all res folders are properly included - even if Eclipse is not aware of them due to refresh issues.
    • -
    • Fixed issue that prevented aapt from running when editing certain XML files.
    • -
    • Fixed minor XML formatting issues.
    • -
    -
    -
    - -
    -
    - - - -
    - - -ADT 15.0.0 (October 2011) -
    -
    - -
    Dependencies:
    - -
    ADT 15.0.0 is designed for use with SDK Tools r15. -If you haven't already installed SDK Tools r15 into your SDK, use the Android SDK Manager to -do so.
    - -
    Bug fixes:
    -
    -
      -
    • Fixed build issue when using Renderscript in projects that target API levels 11-13 - (Issue 21006).
    • -
    • Fixed issue when creating projects from existing source code.
    • -
    • Fixed issues in the SDK Manager - (Issue 20939, - Issue 20607).
    • -
    • Fixed scrolling issue in the new Logcat panel of DDMS.
    • -
    -
    -
    - -
    -
    - -
    - - -ADT 14.0.0 (October 2011) -
    -
    - -
    Dependencies:
    - -
    ADT 14.0.0 is designed for use with SDK Tools r14. -If you haven't already installed SDK Tools r14 into your SDK, use the Android SDK Manager to -do so.
    - -
    Build system:
    -
    -
      -
    • Changed default.properties to project.properties and - build.properties to ant.properties. ADT automatically - renames these files, if necessary, when you open a project in Eclipse.
    • -
    • Changed how library projects are built in Eclipse.
    • -
    • Changed output of javac from bin/ to bin/classes - in Eclipse.
    • -
    • Improved incremental builds so that resource compilation runs less frequently. Builds no - longer run when you edit strings or layouts (unless you add a new id) and no longer - run once for each library project.
    • -
    • Introduced a "PNG crunch cache" that only runs on modified PNG files, instead of - crunching all existing PNG files, all the time.
    • -
    • Modified resource compilation so it no longer happens for normal save operations. It only - happens when running or debugging (the build option that lets you disable the packaging - step, which was introduced in ADT 12, is now on by default.)
    • -
    -

    For a complete overview of the build system changes and what you need to do to support them, -see the Android Tools Project -site.

    -
    - -
    General improvements:
    -
    -
      - - -
    • Added a Welcome Wizard to help with the initial setup of the Android -development environment (more -info).
    • -
    • Integrated the Android Asset Studio, which helps you create icons for things -like the launcher, menus, and tabs. (more -info).
    • -
    • Revamped the Logcat view and added support to display and filter logs by - application names as well as PIDs (more info).
    • -
    • Revamped the SDK Manager UI (more -info).
    • -
    • Revamped the New Project and the New XML File wizards to have -multiple pages. Sample projects are now copied into the workspace such that they can be modified -and deleted without affecting the master copy -(more info).
    • -
    • Removed the dependency on Eclipse GEF.
    • -
    -
    - -
    XML and Java editors:
    -
    -
      -
    • Added a new XML formatter that formats all XML files according to the - standard Android coding style. The formatter can also reorder - attributes to follow a recommended order and processes any changes made in the Layout editor. -(more info).
    • -
    • Added the "Go to Matching" (Ctrl-Shift-P) feature, which lets you jump -between opening and closing tags in XML files.
    • -
    • Added support for the "Select Enclosing Element" feature on Mac.
    • -
    • Added a Quickfix for extracting Strings when the caret is inside a String (see -more).
    • -
    • Improved "smart indent", which allows automatic indentation and un-indentation - when pressing the Return key in XML editors (more info).
    • - -
    -
    - -
    Layout editor:
    -
    -
      -
    • Added tooltip feedback for dragging and resizing operations. For - example, when dragging in a relative layout, the proposed - constraints are shown. When resizing, the new dimensions are - shown (more -info).
    • -
    • Added the ability to suppress rendering fidelity warnings (more info).
    • -
    • Added "Remove Container" visual refactoring that removes the - children of a container up to the top level and transfers - namespace and layout attributes if necessary (more info).
    • -
    • Added pull-right menus to the context menu for accessing - properties of the parents, which is useful when the children fully - cover the parent and make it hard to select on their own.
    • -
    • Improved access to properties in the context menu. The most - frequently set attributes for each view are listed at the top of - the menu. The Properties menu offers access to the most - recently set attributes, attributes organized by their defining - view, and layout attributes only or all attributes alphabetically (more info).
    • -
    -
    - -
    Bug fixes:
    -
    Fixed many bugs and added minor improvements, in -particular some critical bug fixes on -Linux.
    - -
    -
    - - - -
    - - -ADT 12.0.0 (July 2011) -
    -
    - -
    Dependencies:
    - -
    ADT 12.0.0 is designed for use with SDK Tools r12. If you haven't -already installed SDK Tools r12 into your SDK, use -the Android SDK Manager to do so.
    - -
    Visual Layout Editor:
    -
    -
      -
    • New RelativeLayout drop support with guideline suggestions for - attachments and cycle prevention - (more info).
    • -
    • Resize support in most layouts along with - guideline snapping to the sizes dictated by wrap_content and match_parent. - In LinearLayout, sizes are mapped to weights instead of pixel widths. - (more info).
    • -
    • Previews of drawables and colors in the resource chooser dialogs - (more info).
    • -
    • Improved error messages and links for rendering errors including - detection of misspelled class names - (more info).
    • -
    -
    - -
    Build system:
    -
    -
      -
    • A new option lets you disable the packaging step in the automatic - builders. This improves performance when saving files by not - performing a full build, which can take a long time for large projects. - If the option is enabled, the APK is packaged when the - application is deployed to a device or emulator or when the - release APK is exported (more info).
    • -
    -
    - -
    Bug fixes:
    -
    Many bug fixes are part of this release -(more info).
    - -
    -
    - - -
    - - -ADT 11.0.0 (June 2011) -
    - -
    - -
    Dependencies:
    - -
    ADT 11.0.0 is designed for use with SDK Tools r11. If you haven't -already installed SDK Tools r11 into your SDK, use the Android SDK Manager to do -so.
    - -
    Visual Refactoring:
    -
    -
      -
    • "Extract Style" feature pulls out style-related attributes from your layout and extracts -them as a new style defined in {@code styles.xml} (more info).
    • -
    • "Wrap in Container" feature lets you select a group of views then surround them - in a new layout (a new view group, such as a LinearLayout), and transfers namespace and layout - parameters to the new parent (more -info).
    • -
    • "Change Layout" feature changes layouts from one type - to another, and can also flatten a layout hierarchy (more -info).
    • -
    • "Change Widget Type" feature changes the type of the - selected views to a new type. Also, a new selection context menu - in the visual layout editor makes it easy to select siblings as - well as views anywhere in the layout that have the same type (more -info).
    • -
    • "Extract as Include" feature finds identical collections of views - in other layouts and offers to combine them into a single layout that you can then include in - each layout (more info).
    • -
    • Quick Assistant in Eclipse can be invoked - from the XML editor (with Ctrl-1) to apply any of the above - refactorings (and Extract String) to the current selection (more info).
    • -
    -
    - -
    Visual Layout Editor:
    -
    -
      -
    • This is the update to the layout editor you've been waiting for! It includes (almost) all -the goodies demonstrated at Google I/O. Watch -the video on YouTube.
    • -
    • The palette now supports different configurations for supported widgets. That is, a single -view is presented in various different configurations that you can drag into your layout. For -example, there is a Text Fields palette category where you can drag an {@link -android.widget.EditText} widget in as a password field, an e-mail field, a phone field, or other -types of text boxes. Similarly, {@link android.widget.TextView} widgets are preconfigured -with large, normal and small theme sizes, and {@link android.widget.LinearLayout} elements are -preconfigured in horizontal and vertical configurations (more info).
    • -
    • The palette supports custom views. You can pick up any custom - implementations of the View class you've created in your project or from included libraries and -drag them into your layout (more info).
    • -
    • Fragments are available in the palette for placement in your layout. In the tool, you can -choose which layout to show rendered for a given fragment tag. Go to declaration works for fragment -classes (more info).
    • -
    • The layout editor automatically applies a "zoom to fit" for newly - opened files as well as on device size and orientation changes to - ensure that large layouts are always fully visible unless you - manually zoom in.
    • -
    • You can drop in an {@code <include>} element from the palette, which will pop up - a layout chooser. When you select the layout to include, it is added with an {@code -<include>}. Similarly, dropping images or image buttons will pop up image - resource choosers (more info).
    • -
    • The configuration chooser now applies the "Render Target" and - "Locale" settings project wide, making it trivial to check the - layouts for different languages or render targets without having - to configure these individually for each layout.
    • -
    • The layout editor is smarter about picking a default theme to - render a layout with, consulting factors like theme registrations - in the manifest, the SDK version, and other factors.
    • -
    • The layout editor is smarter about picking a default configuration to render a layout -with, defaulting to the currently visible configuration in the previous file. It also considers the -SDK target to determine whether to default to a tablet or phone screen size.
    • -
    • Basic focus support. The first text field dropped in a layout is assigned focus, and there -are Request Focus and Clear Focus context menu items on text -fields to change the focus.
    • -
    -
    - -
    XML editors:
    -
    -
      -
    • Code completion has been significantly improved. It now works - with {@code <style>} elements, completes dimensional units, - sorts resource paths in values based on the attribute name, and more. There are also many fixes to -handle text replacement (more info).
    • -
    • AAPT errors are handled better. They are now underlined for the - relevant range in the editor, and a new quickfix makes it trivial - to create missing resources.
    • -
    • Code completion for drawable, animation and color XML files (more -info).
    • -
    -
    - -
    DDMS:
    -
    -
      -
    • "New Folder" action in the File Explorer.
    • -
    • The screenshot dialog will add timestamps to the filenames and preserve the orientation on -snapshot refresh.
    • -
    -
    - -
    General notes:
    -
    -
      -
    • TraceView supports zooming with the mouse-wheel in the timeline.
    • -
    • The New Android Project wizard now supports Eclipse working sets.
    • -
    -
    -
    -

    More information about tool changes are available on the Android Tools Project Site.

    -
    -
    - - - - - -
    - - -ADT 10.0.1 (March 2011) -
    - -
    - -
    Dependencies:
    - -
    ADT 10.0.1 is designed for use with SDK Tools r10. If you haven't -already installed SDK Tools r10 into your SDK, use the Android SDK Manager to do -so.
    - -
    General notes:
    -
    -
      -
    • Temporary work-around to resolve the rare cases in which the layout editor will -not open.
    • -
    • Fix issue in which ADT 10.0.0 would install on Eclipse 3.4 and lower, even though ADT -requires Eclipse 3.5 or higher (as of 10.0.0).
    • -
    -
    -
    -
    -
    - - - -
    - - -ADT 10.0.0 (February 2011) -
    - -
    - -
    Dependencies:
    - -
    ADT 10.0.0 is designed for use with SDK Tools r10. If you haven't -already installed SDK Tools r10 into your SDK, use the Android SDK Manager to do -so.
    - -
    General notes:
    -
    -
      -
    • The tools now automatically generate Java Programming Language source files (in the gen/ directory) and - bytecode (in the res/raw/ directory) from your .rs files.
    • -
    • A Binary XML editor has been added (details).
    • -
    • Traceview is now integrated into the Eclipse UI (details).
    • -
    • The "Go To Declaration" feature for XML and .java files quickly show all the matches in the project - and allows you jump to specific items such as string translations or onClick handlers - (details).
    • -
    • The Resource Chooser can create items such as dimensions, integers, ids, and booleans - (details).
    • -
    • Improvements to the Visual Layout Editor: -
        -
      • A new Palette with categories and rendering previews - (details).
      • -
      • A Layout Actions bar that provides quick access to common layout operations - (details).
      • -
      • When the Android 3.0 rendering library is selected, layouts render more like they do on devices. - This includes rendering of status and title bars to more accurately reflect the actual - screen space available to applications - (details).
      • -
      • Zoom improvements such as fit to view, persistent scale, and keyboard access. - (details).
      • -
      • Further improvements to <merge> layouts, as well as layouts with gesture overlays - (details).
      • -
      • Improved rendering error diagnostics.
      • -
      -
    • -
    -
    -
    -
    -
    - -
    - - -ADT 9.0.0 (January 2011) -
    - -
    - -
    Dependencies:
    - -
    ADT 9.0.0 is designed for use with SDK Tools r9. If you haven't -already installed SDK Tools r9 into your SDK, use the Android SDK Manager to do -so.
    - -
    General notes:
    -
    -
      -
    • "Go To Declaration" hyperlink support: You can jump directly from code references (such as - R.id.main) to the corresponding XML declaration, or from XML attributes (such as - @string) to the corresponding resource definition, or from manifest XML - registrations to activities and services.
    • -
    • Improvements were made to name refactoring.
    • -
    • AVDs now automatically save their state, so they can restart almost instantly. You can enable this feature when - creating an AVD or by editing an AVD with the AVD Manager.
    • -
    • Improvements to the Visual Layout Editor: -
        -
      • Support for rendering targets: You can now choose an arbitrary Android platform to - render the current page, regardless of the project's minimum platform. This makes it - easy to verify the layout and appearance of your activity on different versions of - the platform. -
      • -
      • Improved support for empty and nested layouts: Dragging items over nested and - invisible layouts automatically enlarges and highlights these layouts, so that they - can receive drops. -
      • -
      • XML formatting improvements: The editor generates cleaner XML and you can now enable - XML auto-formatting in the Preferences menu.
      • -
      • Improved Outline labels: The Outline tab now displays additional information about each - View. Textual Views display a snippet of the actual text. Views with a source - (such as ImageView) displays the resource name. Included Views display the name of the View. -
      • -
      • When you right click a View in the Layout Editor, - the context menu now contains Edit ID... and Edit Text... - items. The Properties... context menus now list all of the properties and - provide a way to edit them - (Details). -
      • -
      • The layout editor now properly handles - <include> - and <merge> - tags (Details).
      • -
      • "Extract as Include" refactoring: The Layout Editor has a new refactoring that allows - you to select one or more views in a layout, and extract it into a separate layout - (Details).
      • -
      • Improved diagnostics for class loading and rendering errors: Class loading and rendering - error messages are more useful and provide better information about the root cause of the - error.
      • -
      • Improved error handling to prevent drag and reordering operations from adding children - into an {@link android.widget.AdapterView}.
      • -
      • Outline reordering: Reordering your views in the Outline tab is much easier - (Details).
      • -
      • Fix for keybinding bug where keyboard shortcuts did not work (Issues - 13231 and - 13134).
      • -
      • Fix for problems with Custom layout attribute menu (Issue - 13134).
      • -
      • Automatic configuration for various view types: Certain views have properties configured - by default. For example, the width of an {@link android.widget.EditText} object is set to - match_parent when added to a vertical {@link android.widget.LinearLayout} - or a default image is added to an {@link android.widget.ImageButton}.
      • -
      • Previews during dragging: Dragging from the palette or dragging within the layout editor - now shows live previews of the dragged item.
      • -
      • Navigation improvements: In the Layout Editor, double-clicking Views jumps to the - corresponding XML element. In the Outline view, double-clicking opens the Properties view.
      • -
      • The editor has Honeycomb style animation preview support.
      • -
      • Improved rendering support for various Views (such as TabHosts and SlidingDrawers) in - Honeycomb (Issues 3162 - and 13092).
      • -
      • Included layouts can be rendered and edited in the context of the layouts that include - them. From a layout using an - <include> tag, double-clicking on the - - <include> element edits the referenced layout in the context of the - current layout. Additionally, when editing a layout that is included by other layouts, - you can quickly change between context layouts, by right clicking in the editor and choosing - Show included in.... This feature is only available in Honeycomb.
      • -
      -
    • -
    • This release fixes many other bugs, but the most important ones are listed below: -
        -
      • Fixed issue that prevented launching debug builds on productions devices when - debuggable=true was not set in the Android manifest.
      • -
      • The LogCat view in DDMS properly handles UTF-8 characters.
      • -
      • The SDK Manager is more reliable on Windows - (Details).
      • -
      • A JUnit initialization bug that prevented you from working with JUnit tests was fixed - (Issue 12411).
      • -
      -
    • -
    -
    -
    -
    -
    - - - - -
    - - -ADT 8.0.1 (December 2010) -
    - -
    - -
    Dependencies:
    - -

    ADT 8.0.1 is designed for use with SDK Tools r8. If you haven't -already installed SDK Tools r8 into your SDK, use the Android SDK Manager to do -so.

    - -
    General notes:
    -
    -
      -
    • This is a quick follow-up to ADT 8.0.0 to fix some bugs.
    • -
    • Fixes an issue in which projects failed to compile, citing a dex error.
    • -
    • Better ProGuard error reporting when exporting applications for release.
    • -
    -

    Also see the recent release notes for 8.0.0, below.

    -
    -
    -
    -
    - - -
    - - -ADT 8.0.0 (December 2010) -
    - -
    - -
    Dependencies:
    - -

    ADT 8.0.0 is designed for use with SDK Tools r8. If you haven't -already installed SDK Tools r8 into your SDK, use the Android SDK Manager to do -so.

    - -
    General notes:
    -
    -
      -
    • New version number scheme that follows the SDK Tools revision number. The major version -number for your ADT plugin should now always match the revision number of your SDK Tools. For -example, ADT 8.x is for SDK Tools r8.
    • -
    • Support for true debug build. You no longer need to change the value of the - debuggable attribute in the Android Manifest. -

      Incremental builds automatically insert debuggable="true", but if you perform - "export signed/unsigned application package", ADT does not insert it. - If you manually set debuggable="true" in the manifest file, then release builds will - actually create a debug build (it does not remove it if you placed it there).

    • -
    • Automatic ProGuard support in - release builds. For it to work, you need to have a proguard.config - property in the default.properties file that points to a ProGuard config file.
    • -
    • Completely rewritten Visual Layout Editor. (This is still a work in progress.) Now includes: -
        -
      • Full drag and drop from palette to layout for all Layout classes.
      • -
      • Move widgets inside a Layout view, from one Layout view to another and from one layout file to another.
      • -
      • Contextual menu with enum/flag type properties.
      • -
      • New zoom controls.
      • -
    • -
    • New HierarchyViewer plug-in integrated in Eclipse.
    • -
    • Android launch configurations don't recompile the whole workspace on launch anymore.
    • -
    • android.jar source and javadoc location can now be configured.
    • -
    -
    -
    -
    -
    - - -
    - - -ADT 0.9.9 (September 2010) -
    - -
    - -
    Dependencies:
    - -

    ADT 0.9.9 replaces ADT 0.9.8 and is designed for use with SDK Tools r7 -and later. ADT 0.9.9 includes the ADT 0.9.8 features as well as an important -bugfix, so we recommend that you upgrade as soon as possible. If you haven't -already installed SDK Tools r7 into your SDK, use the Android SDK Manager to do -so.

    - -
    General notes:
    -
    -
      -
    • Fixes a problem in project import, in which source files were deleted in some cases.
    • -
    • Includes all other ADT 0.9.8 features (see below).
    • -
    -
    -
    -
    -
    - -
    - - -ADT 0.9.8 (September 2010) -
    - - - - - -
    - -
    Dependencies:
    - -

    ADT 0.9.8 is now deprecated. Please use ADT 0.9.9 instead.

    - -
    General notes:
    -
    -
      -
    • Adds a new Action, "Rename Application Package", to the Android Tools -contextual menu. The Action does a full application package refactoring. -
    • Adds support for library projects that don't have a source folder -called src/. There is now support for any number of source folders, -with no name restriction. They can even be in subfolder such as -src/java. If you are already working with library projects created -in ADT 0.9.7, see Migrating -library projects to ADT 0.9.8 for important information about moving -to the new ADT environment.
    • -
    • Adds support for library projects that depend on other library -projects.
    • -
    • Adds support for additional resource qualifiers: -car/desk, night/notnight and -navexposed/navhidden.
    • -
    • Adds more device screen types in the layout editor. All screen -resolution/density combinations listed in the Supporting -Multiple Screens are now available.
    • -
    • Fixes problems with handling of library project names that -contain characters that are incompatible with the Eclipse path variable. -Now properly sets up the link between the main project and the library -project.
    • -
    -
    -
    -
    -
    - - -
    - - -ADT 0.9.7 (May 2010) -
    - -
    -
    Library projects:
    -
    -

    The ADT Plugin now supports the use of library projects during -development, a capability that lets you store shared Android application -code and resources in a separate development project. You can then reference the -library project from other Android projects and, at build time, the tools -compile the shared code and resources as part of the dependent applications. -More information about this feature is available in the Creating and Managing Projects document.

    -

    If you are not developing in Eclipse, SDK Tools r6 provides the equivalent library -project support through the Ant build system.

    -
    -
    -
    -
    - - -
    - - -ADT 0.9.6 (March 2010) -
    - -
    -
    Dependencies:
    - -

    ADT 0.9.6 is designed for use with SDK Tools r5 and later. Before -updating to ADT 0.9.6, we highly recommend that you use the Android SDK Manager to install SDK -Tools r5 into your SDK.

    - -
    General Notes:
    -
    -
      -
    • Editing default.properties outside of Eclipse will now -automatically update the project.
    • -
    • Loads the SDK content only when a project requires it. This will make -Eclipse use less resources when the SDK contains many versions of Android.
    • -
    • Resolves potential deadlock between modal dialogs, when launching ADT the -first time with the SDK Usage panel.
    • -
    • Fixes issues with the New Project Wizard when selecting samples.
    • -
    -
    -
    AVD/SDK Manager:
    -
    -
      -
    • Adds support for platform samples packages.
    • -
    • Improves support for dependency between packages.
    • -
    • AVDs now sorted by API level.
    • -
    • The AVD creation dialog now enforces a minimum SD card size of 9MB.
    • -
    • Prevents deletion of running AVDs.
    • -
    -
    -
    DDMS:
    -
    -
      -
    • DDMS plug-in now contains the Allocation Tracker view.
    • -
    • New action in the Logcat view: "Go to problem" lets you go directly from an -exception trace output to the code.
    • -
    -
    -
    Editors:
    -
    -
      -
    • Explode mode in the Visual Layout Editor adds a margin to all layout objects -so that it's easier to see embedded or empty layouts.
    • -
    • Outline mode in the Visual Layout Editor draws layout outline to make it -easier to see layout objects.
    • -
    • Several fixes in the configuration selector of the Visual Layout -Editor.
    • -
    -
    -
    Application launching:
    -
    -
      -
    • Applications launched from ADT now behave as if they were clicked from the -Home screen.
    • -
    • Fixes issue where add-on with no optional library would not show up as valid -targets for application launches.
    • -
    • Resolves possible crash when launching applications.
    • -
    -
    -
    -
    -
    - -
    - - -ADT 0.9.5 (December 2009) -
    -
    -
    Dependencies:
    - -

    ADT 0.9.5 requires features provided in SDK Tools r4 or higher. If you install -ADT 0.9.5, which is highly recommended, you should use the Android SDK -Manager to download the latest SDK Tools into your SDK. For more information, -see Adding SDK Packages.

    -
    - -
    General notes:
    -
    -
      -
    • AVD Launch dialog now shows scale value.
    • -
    • Fixes potential NPE in SDK Manager on AVD launch, for older AVD with no skin name specified.
    • -
    • Fixes XML validation issue in on older Java versions.
    • -
    • .apk packaging now properly ignores vi swap files as well as hidden files.
    • -
    -
    -
    -
    -
    - -
    - - -ADT 0.9.4 (October 2009) -
    -
    -
    Dependencies:
    - -

    ADT 0.9.4 requires features provided in SDK Tools r3 or higher. If you install -ADT 0.9.4, which is highly recommended, you should use the Android SDK -Manager to download the latest SDK Tools into your SDK. For more information, -see Adding SDK Packages.

    -
    - -
    Project Creation Wizard:
    -
    -
      -
    • New option to create a project from a sample by choosing it from a list.
    • -
    -
    - -
    Layout Editor:
    -
    -
      -
    • Improved Configuration selector that lets you see how your layout will -render on different devices. Default device descriptions include ADP1 -and Google Ion, while SDK add-ons can also provide new descriptions. -A new UI allows you to create custom descriptions.
    • -
    • Adds a new clipping toggle, to let you see your full layout even if it's -bigger than the screen.
    • -
    -
    - -
    DDMS integration:
    -
    -
      -
    • Includes the improvements from the standlone DDMS, revision 3.
    • -
    • Adds an option to open HPROF files into eclipse instead of writing them on -disk. If a profiler such as MAT (Memory Analyzer -Tool) is installed, it'll open the file.
    • -
    -
    - -
    Android SDK and AVD Manager integration:
    -
    -
      -
    • Includes the improvements from the standalone Android SDK and AVD Manager, -revision 3.
    • -
    -
    -
    -
    -
    - - - -

    Installing the ADT Plugin

    - -

    The sections below provide instructions on how to download and install -ADT into your Eclipse environment. If you encounter problems, see the Troubleshooting section.

    - - -

    Preparing Your Development Computer

    - -

    ADT is a plugin for the Eclipse IDE. Before you can install or use ADT, -you must have a compatible version of Eclipse installed on your development -computer. Check the System Requirements document for -a list of Eclipse versions that are compatible with the Android SDK.

    - -
      -
    • If Eclipse is already installed on your computer, make sure that it is -a version that is compatible with ADT and the Android SDK. - -
    • If you need to install or update Eclipse, you can download it from this -location: - -

      http://www.eclipse.org/downloads/ -

      - -

      The "Eclipse Classic" version is recommended. Otherwise, a Java or RCP -version of Eclipse is recommended.

    • -
    - -

    Additionally, before you can configure or use ADT, you must install the -Android SDK starter package, as described in Downloading the SDK Starter Package. -Specifically, you need to install a compatible version of the Android SDK Tools -and at least one development platform. To simplify ADT setup, we recommend -installing the Android SDK prior to installing ADT.

    - -

    When your Eclipse and Android SDK environments are ready, continue with the -ADT installation as described in the steps below.

    - -

    Downloading the ADT Plugin

    - -

    Use the Update Manager feature of your Eclipse installation to install the latest -revision of ADT on your development computer.

    - -

    Assuming that you have a compatible version of the Eclipse IDE installed, as -described in Preparing for Installation, above, follow -these steps to download the ADT plugin and install it in your Eclipse -environment.

    - - -
      -
    1. Start Eclipse, then select Help > Install New -Software....
    2. -
    3. Click Add, in the top-right corner.
    4. -
    5. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the -following URL for the Location: -
      https://dl-ssl.google.com/android/eclipse/
      -
    6. -
    7. Click OK -

      Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, -instead of "https" (https is preferred for security reasons).

    8. -
    9. In the Available Software dialog, select the checkbox next to Developer Tools and click -Next.
    10. -
    11. In the next window, you'll see a list of the tools to be downloaded. Click -Next.
    12. -
    13. Read and accept the license agreements, then click Finish. -

      Note: If you get a security warning saying that the authenticity or validity of -the software can't be established, click OK.

    14. -
    15. When the installation completes, restart Eclipse.
    16. -
    - -

    Configuring the ADT Plugin

    - -

    After you've successfully downloaded the ADT as described above, the next step -is to modify your ADT preferences in Eclipse to point to the Android SDK directory:

    - -
      -
    1. Select Window > Preferences... to open the Preferences - panel (Mac OS X: Eclipse > Preferences).
    2. -
    3. Select Android from the left panel.
    4. -

      You may see a dialog asking whether you want to send usage statistics to Google. If so, -make your choice and click Proceed. You cannot continue with this procedure until -you click Proceed.

      -
    5. For the SDK Location in the main panel, click Browse... and - locate your downloaded SDK directory.
    6. -
    7. Click Apply, then OK.
    8. -
    - -

    Done! If you haven't encountered any problems, then the installation is -complete. If you're installing the Android SDK for the first time, return to Installing the SDK to complete your setup. -

    - - -

    Troubleshooting ADT Installation

    - -

    If you are having trouble downloading the ADT plugin after following the -steps above, here are some suggestions:

    - -
      -
    • If Eclipse can not find the remote update site containing the ADT plugin, -try changing the remote site URL to use http, rather than https. That is, set -the Location for the remote site to: -
      http://dl-ssl.google.com/android/eclipse/
    • -
    • If you are behind a firewall (such as a corporate firewall), make sure that -you have properly configured your proxy settings in Eclipse. In Eclipse, -you can configure proxy information from the main Eclipse menu in -Window (on Mac OS X, Eclipse) > -Preferences > General > Network -Connections.
    • -
    - -

    If you are still unable to use Eclipse to download the ADT plugin as a -remote update site, you can download the ADT zip file to your local machine and -manually install it:

    - -
      -
    1. Download the current ADT Plugin zip file from the table below (do not unpack it). - - - - - - - - - - - - - - -
      NamePackageSizeMD5 Checksum
      ADT {@adtZipVersion} - {@adtZipDownload} - {@adtZipBytes} bytes{@adtZipChecksum}
      -
    2. - - -
    3. Follow steps 1 and 2 in the default install - instructions (above).
    4. -
    5. In the Add Site dialog, click Archive.
    6. -
    7. Browse and select the downloaded zip file.
    8. -
    9. Enter a name for the local update site (e.g., - "Android Plugin") in the "Name" field.
    10. -
    11. Click OK. -
    12. Follow the remaining procedures as listed for - default installation above, - starting from step 4.
    13. -
    - -

    To update your plugin once you've installed using the zip file, you will have -to follow these steps again instead of the default update instructions.

    - -

    Other install errors

    - -

    Note that there are features of ADT that require some optional -Eclipse packages (for example, WST). If you encounter an error when -installing ADT, your Eclipse installion might not include these packages. -For information about how to quickly add the necessary packages to your -Eclipse installation, see the troubleshooting topic -ADT -Installation Error: "requires plug-in org.eclipse.wst.sse.ui".

    - -

    For Linux users

    -

    If you encounter this error when installing the ADT Plugin for Eclipse: -

    -An error occurred during provisioning.
    -Cannot connect to keystore.
    -JKS
    -

    -...then your development machine lacks a suitable Java VM. Installing Sun -Java 6 will resolve this issue and you can then reinstall the ADT -Plugin.

    - - -

    Updating the ADT Plugin

    - -

    From time to time, a new revision of the ADT Plugin becomes available, with -new features and bug fixes. Generally, when a new revision of ADT is available, -you should update to it as soon as convenient.

    - -

    In some cases, a new revision of ADT will have a dependency on a specific -revision of the Android SDK Tools. If such dependencies exist, you will need to -update the SDK Tools package of the SDK after installing the new revision of -ADT. To update the SDK Tools package, use the Android SDK Manager, as -described in Adding SDK Packages.

    - -

    To learn about new features of each ADT revision and also any dependencies on -the SDK Tools, see the listings in the Revisions -section. To determine the version currently installed, open the -Eclipse Installed Software window using Help -> Software Updates and refer to the version listed for -"Android Development Tools".

    - -

    Follow the steps below to check whether an update is available and, if so, -to install it.

    - -
      -
    1. Select Help > Check for Updates. -

      If there are no updates available, a dialog will say so and you're done.

    2. -
    3. If there are updates available, select Android DDMS, Android Development Tools, - and Android Hierarchy Viewer, then click Next.
    4. -
    5. In the Update Details dialog, click Next.
    6. -
    7. Read and accept the license agreement and then click Finish. - This will download and install the latest version of Android DDMS and - Android Development Tools.
    8. -
    9. Restart Eclipse.
    10. -
    - - -

    If you encounter problems during the update, remove the existing ADT plugin from Eclipse, then -perform a fresh installation, using the instructions for Installing the ADT -Plugin.

    - diff --git a/docs/html/sdk/exploring.jd b/docs/html/sdk/exploring.jd new file mode 100644 index 000000000000..8272b061a0c9 --- /dev/null +++ b/docs/html/sdk/exploring.jd @@ -0,0 +1,166 @@ +page.title=Exploring the SDK +walkthru=1 + +@jd:body + + +

    The Android SDK is composed of modular packages that you can download separately using +the Android SDK Manager. For example, when the SDK Tools are updated or a new version of +the Android platform is released, you can use the SDK Manager to quickly download them to +your environment. Simply follow the procedures described in Adding Platforms and Packages.

    + +

    There are several different packages available for the Android SDK. The table below describes +most of the available packages and where they're located once you download them.

    + + +

    Available Packages

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageDescriptionFile Location
    SDK ToolsContains tools for debugging and testing, plus other +utilities that are required to develop an app. If you've just installed the SDK starter package, +then you already have the latest version of this package. Make sure you keep this up to date.{@code <sdk>/tools/}
    SDK Platform-toolsContains platform-dependent tools for developing and debugging +your application. These tools support the latest features of the Android platform and are typically +updated only when a new platform becomes available. These tools are always backward compatible with +older platforms, but you must be sure that you have the latest version of these tools when you +install a new SDK platform.{@code <sdk>/platform-tools/}
    DocumentationAn offline copy of the latest documentation for the Android +platform APIs.{@code <sdk>/docs/}
    SDK PlatformThere's one SDK Platform available for each version of Android. It includes an {@code +android.jar} file with a fully compliant Android library. In order to build an Android app, you must +specify an SDK platform as your build target.{@code <sdk>/platforms/<android-version>/}
    System ImagesEach platform version offers one or more different system images (such as for ARM +and x86). The Android emulator requires a system image to operate. You should always test your +app on the latest version of Android and using the emulator with the latest system image is a +good way to do so.{@code <sdk>/platforms/<android-version>/}
    Sources for Android SDKA copy of the Android platform source code that's useful for +stepping through the code while debugging your app.{@code <sdk>/sources/}
    Samples for SDKA collection of sample apps that demonstrate a variety of the +platform APIs. These are a great resource to browse Android app code. The API Demos app in +particular provides a huge number of small demos you should explore.{@code <sdk>/platforms/<android-version>/samples/}
    Google APIsAn SDK add-on that provides both a platform you can use to develop an app +using special Google APIs and a system image for the emulator so you can test your app using the +Google APIs.{@code <sdk>/add-ons/}
    Android SupportA static library you can include in your app sources in order to use powerful +APIs that aren't available in the standard platform. For example, the support library +contains versions of the {@link android.support.v4.app.Fragment} class that's compatible with +Android 1.6 and higher (the class was originally introduced in Android 3.0) and the {@link +android.support.v4.view.ViewPager} APIs that allow you to easily build a side-swipeable UI.{@code <sdk>/extras/android/support/}
    Google Play BillingProvides the static libraries and samples that allow you to +integrate billing services in your app with Google Play.{@code <sdk>/extras/google/}
    Google Play LicensingProvides the static libraries and samples that allow you to perform license verification for +your app when distributing with Google Play.{@code <sdk>/extras/google/}
    + +

    The above table is not comprehensive and you can add new sites to download additional packages from third-parties.

    + +

    In some cases, an SDK package may require a specific minimum revision of +another package or SDK tool. For example, there may be a dependency between the ADT Plugin for +Eclipse and +the SDK Tools package. When you install the SDK Tools +package, you should also upgrade to the required version of ADT (if you +are developing in Eclipse). In this case, the major version number for your ADT plugin should +always match the revision number of your SDK Tools (for example, ADT 8.x requires SDK Tools r8). +

    + +

    The development tools will notify you with debug warnings if there is dependency that you need to +address. The Android SDK Manager also enforces dependencies by requiring that you download any +packages that are needed by those you have selected.

    + + + + + +

    Adding New Sites

    + +

    By default, Available Packages displays packages available from the +Android Repository and Third party Add-ons. You can add other sites that host +their own Android SDK add-ons, then download the SDK add-ons +from those sites.

    + +

    For example, a mobile carrier or device manufacturer might offer additional +API libraries that are supported by their own Android-powered devices. In order +to develop using their libraries, you must install their Android SDK add-on, if it's not already +available under Third party Add-ons.

    + +

    If a carrier or device manufacturer has hosted an SDK add-on repository file +on their web site, follow these steps to add their site to the Android SDK +Manager:

    + +
      +
    1. Select Available Packages in the left panel.
    2. +
    3. Click Add Add-on Site and enter the URL of the +repository.xml file. Click OK.
    4. +
    +

    Any SDK packages available from the site will now be listed under a new item named +User Add-ons.

    + + + + +

    Troubleshooting

    + +

    Problems connecting to the SDK repository

    + +

    If you are using the Android SDK Manager to download packages and are encountering +connection problems, try connecting over http, rather than https. To switch the +protocol used by the Android SDK Manager, follow these steps:

    + +
      +
    1. With the Android SDK Manager window open, select "Settings" in the + left pane.
    2. +
    3. On the right, in the "Misc" section, check the checkbox labeled "Force + https://... sources to be fetched using http://..."
    4. +
    5. Click Save & Apply.
    6. +
    + + + + diff --git a/docs/html/sdk/images/4.0/contact-call.xcf b/docs/html/sdk/images/4.0/contact-call.xcf deleted file mode 100644 index 3046e928cd64..000000000000 Binary files a/docs/html/sdk/images/4.0/contact-call.xcf and /dev/null differ diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd index b56ccdbd83f0..e788ffeb9673 100644 --- a/docs/html/sdk/index.jd +++ b/docs/html/sdk/index.jd @@ -1,6 +1,6 @@ page.title=Android SDK +header.hide=1 page.metaDescription=Download the official Android SDK to develop apps for Android-powered devices. -sdk.redirect=0 sdk.win_installer=installer_r18-windows.exe sdk.win_installer_bytes=37456234 @@ -20,28 +20,119 @@ sdk.linux_checksum=6cd716d0e04624b865ffed3c25b3485c @jd:body -
    -

    Here's an overview of the steps you must follow to set up the Android SDK:

    + -
      -
    1. Prepare your development computer and ensure it meets the system requirements.
    2. -
    3. Install the SDK starter package from the table above. (If you're on Windows, download the -installer for help with the initial setup.)
    4. -
    5. Install the ADT Plugin for Eclipse (if you'll be developing in Eclipse).
    6. -
    7. Add Android platforms and other packages to your SDK.
    8. -
    9. Explore the contents of the Android SDK (optional).
    10. -
    +
    -

    To get started, download the appropriate package from the table above, -then read the guide to Installing the SDK.

    +
     
    + +
    + +
    + + +
    + +
    +

    Get the Android SDK

    + + +

    The Android SDK provides you the API libraries and developer tools necessary to build, test, + and debug apps for Android.

    + + +

    +To get the latest Android SDK, please visit the web site at developer.android.com/sdk/ +

    + + + + +
    - - -

    For more information about how to set up your -development environment, read the guide to Installing the SDK.

    + + +
    + + +
     
    + + + + + + +
    + diff --git a/docs/html/sdk/installing.jd b/docs/html/sdk/installing.jd deleted file mode 100644 index 7461eb0c427a..000000000000 --- a/docs/html/sdk/installing.jd +++ /dev/null @@ -1,590 +0,0 @@ -page.title=Installing the SDK - -@jd:body - - - - - - - -

    This page describes how to install the Android SDK -and set up your development environment for the first time.

    - -

    If you encounter any problems during installation, see the -Troubleshooting section at the bottom of -this page.

    - -

    Updating?

    - -

    If you already have an Android SDK, use the Android SDK Manager tool to install -updated tools and new Android platforms into your existing environment. For information about how to -do that, see Adding SDK Packages.

    - - -

    Step 1. Preparing Your Development Computer

    - -

    Before getting started with the Android SDK, take a moment to confirm that -your development computer meets the System -Requirements. In particular, you might need to install the JDK, if you don't have it already.

    - -

    If you will be developing in Eclipse with the Android Development -Tools (ADT) Plugin—the recommended path if you are new to -Android—make sure that you have a suitable version of Eclipse -installed on your computer as described in the -System Requirements document. -If you need to install Eclipse, you can download it from this location:

    - -

    http://www.eclipse.org/downloads/

    - -

    The "Eclipse Classic" version is recommended. Otherwise, a Java or -RCP version of Eclipse is recommended.

    - - -

    Step 2. Downloading the SDK Starter Package

    - -

    The SDK starter package is not a full -development environment—it includes only the core SDK Tools, which you can -use to download the rest of the SDK packages (such as the latest Android platform).

    - -

    If you haven't already, get the latest version of the SDK starter package from the SDK download page.

    - -

    If you downloaded a {@code .zip} or {@code .tgz} package (instead of the SDK installer), unpack -it to a safe location on your machine. By default, the SDK files are unpacked -into a directory named android-sdk-<machine-platform>.

    - -

    If you downloaded the Windows installer ({@code .exe} file), run it now and it will check -whether the proper Java SE Development Kit (JDK) is installed (installing it, if necessary), then -install the SDK Tools into a default location (which you can modify).

    - -

    Make a note of the name and location of the SDK directory on your system—you will need to -refer to the SDK directory later, when setting up the ADT plugin and when using -the SDK tools from the command line.

    - - -

    Step 3. Installing the ADT Plugin for Eclipse

    - -

    Android offers a custom plugin for the Eclipse IDE, called Android -Development Tools (ADT), that is designed to give you a powerful, integrated -environment in which to build Android applications. It extends the capabilites -of Eclipse to let you quickly set up new Android projects, create an application -UI, debug your applications -using the Android SDK tools, and even export signed (or unsigned) APKs in order -to distribute your application. In general, developing in Eclipse with ADT is a -highly recommended approach and is the fastest way to get started with Android. -

    - -

    If you'd like to use ADT for developing Android applications, install it now. -Read Installing the ADT Plugin for -step-by-step installation instructions, then return here to continue the -last step in setting up your Android SDK.

    - -

    If you prefer to work in a different IDE, you do not need to -install Eclipse or ADT. Instead, you can directly use the SDK tools to build and -debug your application. The Introduction -to Android application development outlines the major steps that you need to complete when -developing in Eclipse or other IDEs.

    - - - -

    Step 4. Adding Platforms and Other Packages

    - -

    The last step in setting up your SDK is using the Android SDK Manager (a -tool included in the SDK starter package) to download essential SDK packages into your development -environment.

    - -

    The SDK uses a modular structure that separates the major parts of the SDK—Android platform -versions, add-ons, tools, samples, and documentation—into a set of separately installable -packages. The SDK starter package, which you've already downloaded, includes only a single -package: the latest version of the SDK Tools. To develop an Android application, you also need to -download at least one Android platform and the associated platform tools. You can add other -packages and platforms as well, which is highly recommended.

    - -

    If you used the Windows installer, when you complete the installation wizard, it will launch the -Android SDK Manager with a default set of platforms and other packages selected -for you to install. Simply click Install to accept the recommended set of -packages and install them. You can then skip to Step 5, but we -recommend you first read the section about the Available Packages to -better understand the packages available from the Android SDK Manager.

    - -

    You can launch the Android SDK Manager in one of the following ways:

    -
      -
    • From within Eclipse, select Window > Android SDK Manager.
    • -
    • On Windows, double-click the SDK Manager.exe file at the root of the Android -SDK directory.
    • -
    • On Mac or Linux, open a terminal and navigate to the tools/ directory in the -Android SDK, then execute:
      android
    • -
    - -

    To download packages, use the graphical UI of the Android SDK -Manager to browse the SDK repository and select new or updated -packages (see figure 1). The Android SDK Manager installs the selected packages in -your SDK environment. For information about which packages you should download, see Recommended Packages.

    - - -

    Figure 1. The Android SDK Manager's -Available Packages panel, which shows the SDK packages that are -available for you to download into your environment.

    - - -

    Available Packages

    - -

    By default, there are two repositories of packages for your SDK: Android -Repository and Third party Add-ons.

    - -

    The Android Repository offers these types of packages:

    - -
      -
    • SDK Tools — Contains tools for debugging and testing your application -and other utility tools. These tools are installed with the Android SDK starter package and receive -periodic updates. You can access these tools in the <sdk>/tools/ directory of -your SDK. To learn more about -them, see SDK Tools in the -developer guide.
    • - -
    • SDK Platform-tools — Contains platform-dependent tools for developing -and debugging your application. These tools support the latest features of the Android platform and -are typically updated only when a new platform becomes available. You can access these tools in the -<sdk>/platform-tools/ directory. To learn more about them, see Platform Tools in the -developer guide.
    • - -
    • Android platforms — An SDK platform is -available for every production Android platform deployable to Android-powered devices. Each -SDK platform package includes a fully compliant Android library, system image, sample code, -and emulator skins. To learn more about a specific platform, see the list of platforms that appears -under the section "Downloadable SDK Packages" on the left part of this page.
    • - -
    • USB Driver for Windows (Windows only) — Contains driver files -that you can install on your Windows computer, so that you can run and debug -your applications on an actual device. You do not need the USB driver unless -you plan to debug your application on an actual Android-powered device. If you -develop on Mac OS X or Linux, you do not need a special driver to debug -your application on an Android-powered device. See Using Hardware Devices for more information -about developing on a real device.
    • - -
    • Samples — Contains the sample code and apps available -for each Android development platform. If you are just getting started with -Android development, make sure to download the samples to your SDK.
    • - -
    • Documentation — Contains a local copy of the latest -multiversion documentation for the Android framework API.
    • -
    - -

    The Third party Add-ons provide packages that allow you to create a development -environment using a specific Android external library (such as the Google Maps library) or a -customized (but fully compliant) Android system image. You can add additional Add-on repositories by -clicking Add Add-on Site.

    - - -

    Recommended Packages

    - -

    The SDK repository contains a range of packages that you can download. -Use the table below to determine which packages you need, based on whether you -want to set up a basic, recommended, or full development environment: -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    EnvironmentSDK PackageComments
    BasicSDK ToolsIf you've just installed -the SDK starter package, then you already have the latest version of this package. The -SDK Tools package is required to develop an Android application. Make sure you keep this up to -date.
    SDK Platform-toolsThis includes more tools that are required -for application development. These tools are platform-dependent and typically update only when -a new SDK platform is made available, in order to support new features in the platform. These -tools are always backward compatible with older platforms, but you must be sure that you have -the latest version of these tools when you install a new SDK platform.
    SDK platformYou need to download at least one platform into your environment, so that -you will be able to compile your application and set up an Android Virtual -Device (AVD) to run it on (in the emulator). To start with, just download the -latest version of the platform. Later, if you plan to publish your application, -you will want to download other platforms as well, so that you can test your -application on the full range of Android platform versions that your application supports.
    +
    Recommended
    (plus Basic)
    DocumentationThe Documentation package is useful because it lets you work offline and -also look up API reference information from inside Eclipse.
    SamplesThe Samples packages give you source code that you can use to learn about -Android, load as a project and run, or reuse in your own app. Note that multiple -samples packages are available — one for each Android platform version. When -you are choosing a samples package to download, select the one whose API Level -matches the API Level of the Android platform that you plan to use.
    Usb DriverThe Usb Driver package is needed only if you are developing on Windows and -have an Android-powered device on which you want to install your application for -debugging and testing. For Mac OS X and Linux platforms, no -special driver is needed.
    +
    Full
    (plus Recommended)
    Google APIsThe Google APIs add-on gives your application access to the Maps external -library, which makes it easy to display and manipulate Maps data in your -application.
    Additional SDK PlatformsIf you plan to publish your application, you will want to download -additional platforms corresponding to the Android platform versions on which you -want the application to run. The recommended approach is to compile your -application against the lowest version you want to support, but test it against -higher versions that you intend the application to run on. You can test your -applications on different platforms by running in an Android Virtual Device -(AVD) on the Android emulator.
    - -

    Once you've installed at least the basic configuration of SDK packages, you're ready to start -developing Android apps. The next section describes the contents of the Android SDK to familiarize -you with the packages you've just installed.

    - -

    For more information about using the Android SDK Manager, see the Adding SDK Packages document.

    - - -

    Step 5. Exploring the SDK (Optional)

    - -

    Once you've installed the SDK and downloaded the platforms, documentation, -and add-ons that you need, we suggest that you open the SDK directory and take a look at what's -inside.

    - -

    The table below describes the full SDK directory contents, with packages -installed.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameDescription
    add-ons/Contains add-ons to the Android SDK development -environment, which let you develop against external libraries that are available on some -devices.
    docs/A full set of documentation in HTML format, including the Developer's Guide, -API Reference, and other information. To read the documentation, load the -file offline.html in a web browser.
    platform-tools/Contains platform-dependent development tools that may be updated with each platform release. -The platform tools include the Android Debug Bridge ({@code adb}) as well as other tools that you -don't typically use directly. These tools are separate from the development tools in the {@code -tools/} directory because these tools may be updated in order to support new -features in the latest Android platform.
    platforms/Contains a set of Android platform versions that you can develop -applications against, each in a separate directory.
    <platform>/Platform version directory, for example "android-11". All platform version directories contain -a similar set of files and subdirectory structure. Each platform directory also includes the -Android library (android.jar) that is used to compile applications against the -platform version.
    samples/Sample code and apps that are specific to platform version.
    tools/Contains the set of development and profiling tools that are platform-independent, such -as the emulator, the Android SDK Manager, the AVD Manager, ddms, -hierarchyviewer -and more. The tools in this directory may be updated at any time using the Android SDK -Manager and are independent of platform releases.
    SDK Readme.txtA file that explains how to perform the initial setup of your SDK, -including how to launch the Android SDK Manager tool on all -platforms.
    SDK Manager.exeWindows SDK only. A shortcut that launches the Android SDK -Manager tool, which you use to add packages to your SDK.
    - - -

    Optionally, you might want to add the location of the SDK's tools/ and -platform-tools to your PATH environment variable, to provide easy -access to the tools.

    - - -
    - - - How to update your PATH -
    - -

    Adding both tools/ and platform-tools/ to your PATH lets you run -command line tools without needing to -supply the full path to the tool directories. Depending on your operating system, you can -include these directories in your PATH in the following way:

    - -
      - -
    • On Windows, right-click on My Computer, and select Properties. - Under the Advanced tab, hit the Environment Variables button, and in the - dialog that comes up, double-click on Path (under System Variables). Add the full path to the - tools/ and platform-tools/ directories to the path.
    • - -
    • On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look - for a line that sets the PATH environment variable and add the - full path to the tools/ and platform-tools/ directories to it. If you - don't see a line setting the path, you can add one: -
      export PATH=${PATH}:<sdk>/tools:<sdk>/platform-tools
      -
    • - -
    • On a Mac OS X, look in your home directory for .bash_profile and - proceed as for Linux. You can create the .bash_profile if - you don't already have one.
    • -
    - -
    -
    - - -

    Next Steps

    -

    Once you have completed installation, you are ready to -begin developing applications. Here are a few ways you can get started:

    - -

    Set up the Hello World application

    -
      -
    • If you have just installed the SDK for the first time, go to the Hello - World tutorial. The tutorial takes you step-by-step through the process - of setting up your first Android project, including setting up an Android - Virtual Device (AVD) on which to run the application. -
    • -
    - -

    Following the Hello World tutorial is an essential -first step in getting started with Android development.

    - -

    Learn about Android

    -
      -
    • Take a look at the Dev - Guide and the types of information it provides.
    • -
    • Read an introduction to Android as a platform in What is - Android?
    • -
    • Learn about the Android framework and how applications run on it in - Application - Fundamentals.
    • -
    • Take a look at the Android framework API specification in the Reference tab.
    • -
    - -

    Explore the development tools

    - - -

    Follow the Notepad tutorial

    - -
      -
    • The - Notepad Tutorial shows you how to build a full Android application - and provides helpful commentary on the Android system and API. The - Notepad tutorial helps you bring together the important design - and architectural concepts in a moderately complex application. -
    • -
    -

    Following the Notepad tutorial is an excellent -second step in getting started with Android development.

    - -

    Explore some code

    - -
      -
    • The Android SDK includes sample code and applications for each platform -version. You can browse the samples in the Resources tab or download them -into your SDK using the Android SDK Manager. Once you've downloaded the -samples, you'll find them in -<sdk>/samples/<platform>/.
    • -
    - -

    Visit the Android developer groups

    -
      -
    • Take a look at the Community pages to see a list of - Android developers groups. In particular, you might want to look at the - Android - Developers group to get a sense for what the Android developer - community is like.
    • -
    - -

    Troubleshooting

    - -

    Ubuntu Linux Notes

    - -
      -
    • If you need help installing and configuring Java on your - development machine, you might find these resources helpful: - -
    • -
    • Here are the steps to install Java and Eclipse, prior to installing - the Android SDK and ADT Plugin. -
        -
      1. If you are running a 64-bit distribution on your development - machine, you need to install the ia32-libs package using - apt-get:: -
        apt-get install ia32-libs
        -
      2. -
      3. Next, install Java:
        apt-get install sun-java6-jdk
      4. -
      5. The Ubuntu package manager does not currently offer an Eclipse 3.3 - version for download, so we recommend that you download Eclipse from - eclipse.org (http://www.eclipse.org/ - downloads/). A Java or RCP version of Eclipse is recommended.
      6. -
      7. Follow the steps given in previous sections to install the SDK - and the ADT plugin.
      8. -
      -
    • -
    - -

    Other Linux Notes

    - -
      -
    • If JDK is already installed on your development computer, please - take a moment to make sure that it meets the version requirements listed - in the System Requirements. - In particular, note that some Linux distributions may include JDK 1.4 or Gnu - Compiler for Java, both of which are not supported for Android development.
    • -
    diff --git a/docs/html/sdk/installing/adding-packages.jd b/docs/html/sdk/installing/adding-packages.jd new file mode 100644 index 000000000000..7765343b2e50 --- /dev/null +++ b/docs/html/sdk/installing/adding-packages.jd @@ -0,0 +1,78 @@ +page.title=Adding Platforms and Packages +walkthru=1 + +@jd:body + + +

    The Android SDK separates different parts of the SDK into separately downloadable packages. The +SDK starter package that you've installed includes only the SDK Tools. To develop an Android app, +you also need to download at least one Android platform and the latest SDK Platform-tools.

    + +

    You can update and install SDK packages at any time using the Android SDK Manager.

    + +

    If you've used the Windows installer to install the SDK tools, you should already have the +Android SDK Manager open. Otherwise, you can launch the Android SDK Manager in one of the following +ways:

    +
      +
    • On Windows, double-click the SDK Manager.exe file at the root of the Android +SDK directory.
    • +
    • On Mac or Linux, open a terminal and navigate to the tools/ directory in the +Android SDK, then execute android sdk.
    • +
    + +

    When you open the Android SDK Manager, it automatically selects a set of recommended packages. +Simply click Install to install the recommended packages. The Android SDK Manager +installs the selected packages into +your Android SDK environment. The following sections describe some of the available SDK +packages and more about which ones we recommend you install.

    + +

    Once you have installed your packages, continue to the next page.

    + + +

    Figure 1. The Android SDK Manager shows the +SDK packages that are available, already installed, or for which an update is available.

    + + + + + + +

    Here's an outlines of the packages required and those we recommend you use: +

    + +
    +
    SDK Tools
    +
    Required. Your new SDK installation already has the latest version. Make sure +you keep this up to date.
    +
    SDK Platform-tools
    +
    Required. You must install this package when you install the SDK for +the first time.
    +
    SDK Platform
    +
    Required.You need to download at least one platform into your environment so you're +able to compile your application. In order to provide the best user experience on the latest +devices, we recommend that you use the latest platform version as your build target. You'll +still be able to run your app on older versions, but you must build against the latest version +in order to use new features when running on devices with the latest version of Android.
    +
    System Image
    +
    Recommended. Although you might have one or more Android-powered devices on which to test + your app, it's unlikely you have a device for every version of Android your app supports. It's +a good practice to download a system image for each version of Android you support and use them +to test your app on the Android emulator.
    +
    SDK Samples
    +
    Recommended. The samples give you source code that you can use to learn about +Android, load as a project and run, or reuse in your own app. Note that multiple +samples packages are available — one for each Android platform version. When +you are choosing a samples package to download, select the one whose API Level +matches the API Level of the Android platform that you plan to use.
    +
    Android Support
    +
    Recommended. The APIs available in this static library allow you to use a variety of new +framework features (including some not available in even the latest version) on devices running +a platform version as old as Android 1.6. For more information, read Support Library.
    +
    + + +

    Tip: For easy access to the SDK tools from a command line, add the +location of the SDK's tools/ and +platform-tools to your PATH environment variable.

    diff --git a/docs/html/sdk/installing/index.jd b/docs/html/sdk/installing/index.jd new file mode 100644 index 000000000000..2ae6bedeb151 --- /dev/null +++ b/docs/html/sdk/installing/index.jd @@ -0,0 +1,133 @@ +page.title=Installing the SDK +walkthru=1 + +@jd:body + + +

    You should have already downloaded the Android SDK. Now +you need to set up your development environment.

    + +

    The SDK you've downloaded is not the complete SDK environment. It includes only the core SDK tools, which you can +use to download the rest of the SDK packages (such as the latest system image).

    + + + + + + + + + + + + + +

    Other platforms

    + + diff --git a/docs/html/sdk/installing/installing-adt.jd b/docs/html/sdk/installing/installing-adt.jd new file mode 100644 index 000000000000..29252728d72d --- /dev/null +++ b/docs/html/sdk/installing/installing-adt.jd @@ -0,0 +1,206 @@ +page.title=Installing the Eclipse Plugin +walkthru=1 +adt.zip.version=18.0.0 +adt.zip.download=ADT-18.0.0.zip +adt.zip.bytes=12834793 +adt.zip.checksum=b446fa157ed97af79d1e21629201efbb + +@jd:body + + + +

    Android offers a custom plugin for the Eclipse IDE, called Android +Development Tools (ADT). This plugin is designed to give you a powerful, integrated +environment in which to develop Android apps. It extends the capabilites +of Eclipse to let you quickly set up new Android projects, build an app +UI, debug your app, and export signed (or unsigned) app packages (APKs) for distribution. +

    + +

    If you will be developing in Eclipse with the ADT Plugin, first make sure that you have a +suitable version of Eclipse +installed on your computer as described by the +system requirements.

    + +

    If you need to install Eclipse, you can download it from http://www.eclipse.org/downloads/. +We recommend the "Eclipse Classic" version. Otherwise, you should use a Java or +RCP version of Eclipse.

    + + +

    Note: If you prefer to work in a different IDE, you do not need to +install Eclipse or ADT. Instead, you can directly use the SDK tools to build and +debug your application. So if you're not using Eclipse, continue to the next page by clicking +the Next link on the right.

    + + + +

    Download the ADT Plugin

    + + +
      +
    1. Start Eclipse, then select Help > Install New +Software....
    2. +
    3. Click Add, in the top-right corner.
    4. +
    5. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the +following URL for the Location: +
      https://dl-ssl.google.com/android/eclipse/
      +
    6. +
    7. Click OK +

      Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, +instead of "https" (https is preferred for security reasons).

    8. +
    9. In the Available Software dialog, select the checkbox next to Developer Tools and click +Next.
    10. +
    11. In the next window, you'll see a list of the tools to be downloaded. Click +Next.
    12. +
    13. Read and accept the license agreements, then click Finish. +

      Note: If you get a security warning saying that the authenticity or validity of +the software can't be established, click OK.

    14. +
    15. When the installation completes, restart Eclipse.
    16. +
    + + + + +

    Configure the ADT Plugin

    + +

    After you've installed ADT and restarted Eclipse, you + must specify the location of your Android SDK directory:

    + +
      +
    1. Select Window > Preferences... to open the Preferences + panel (on Mac OS X, select Eclipse > Preferences).
    2. +
    3. Select Android from the left panel.
    4. +

      You may see a dialog asking whether you want to send usage statistics to Google. If so, +make your choice and click Proceed.

      +
    5. For the SDK Location in the main panel, click Browse... and + locate your downloaded Android SDK directory (such as android-sdk-windows).
    6. +
    7. Click Apply, then OK.
    8. +
    + + +

    If you haven't encountered any errors, you're done setting up ADT + and can continue to the next step of the SDK installation.

    + + + + +

    Updating the ADT Plugin

    + +

    From time to time, a new revision of the ADT Plugin becomes available, with +new features and bug fixes. Generally, when a new revision of ADT is available, +you should update to it as soon as convenient.

    + +

    In some cases, a new revision of ADT will have a dependency on a specific +revision of the Android SDK Tools. If such dependencies exist, you will need to +update the SDK Tools package of the SDK after installing the new revision of +ADT. To update the SDK Tools package, use the Android SDK Manager, as +described in Exploring the SDK.

    + +

    To learn about new features of each ADT revision and also any dependencies on +the SDK Tools, see the listings in the Revisions +section. To determine the version currently installed, open the +Eclipse Installed Software window using Help +> Software Updates and refer to the version listed for +"Android Development Tools".

    + +

    Follow the steps below to check whether an update is available and, if so, +to install it.

    + +
      +
    1. Select Help > Check for Updates. +

      If there are no updates available, a dialog will say so and you're done.

    2. +
    3. If there are updates available, select Android DDMS, Android Development Tools, + and Android Hierarchy Viewer, then click Next.
    4. +
    5. In the Update Details dialog, click Next.
    6. +
    7. Read and accept the license agreement and then click Finish. + This will download and install the latest version of Android DDMS and + Android Development Tools.
    8. +
    9. Restart Eclipse.
    10. +
    + + +

    If you encounter problems during the update, remove the existing ADT plugin from Eclipse, then +perform a fresh installation, using the instructions for Installing the ADT +Plugin.

    + + + +

    Troubleshooting

    + +

    If you are having trouble downloading the ADT plugin after following the +steps above, here are some suggestions:

    + +
      +
    • If Eclipse can not find the remote update site containing the ADT plugin, +try changing the remote site URL to use http, rather than https. That is, set +the Location for the remote site to: +
      http://dl-ssl.google.com/android/eclipse/
    • +
    • If you are behind a firewall (such as a corporate firewall), make sure that +you have properly configured your proxy settings in Eclipse. In Eclipse, +you can configure proxy information from the main Eclipse menu in +Window (on Mac OS X, Eclipse) > +Preferences > General > Network +Connections.
    • +
    + +

    If you are still unable to use Eclipse to download the ADT plugin as a +remote update site, you can download the ADT zip file to your local machine and +manually install it:

    + +
      +
    1. Download the current ADT Plugin zip file from the table below (do not unpack it). + + + + + + + + + + + + + + +
      NamePackageSizeMD5 Checksum
      ADT {@adtZipVersion} + {@adtZipDownload} + {@adtZipBytes} bytes{@adtZipChecksum}
      +
    2. + + +
    3. Follow steps 1 and 2 in the default install + instructions (above).
    4. +
    5. In the Add Site dialog, click Archive.
    6. +
    7. Browse and select the downloaded zip file.
    8. +
    9. Enter a name for the local update site (e.g., + "Android Plugin") in the "Name" field.
    10. +
    11. Click OK. +
    12. Follow the remaining procedures as listed for + default installation above, + starting from step 4.
    13. +
    + +

    To update your plugin once you've installed using the zip file, you will have +to follow these steps again instead of the default update instructions.

    + +

    Other install errors

    + +

    Note that there are features of ADT that require some optional +Eclipse packages (for example, WST). If you encounter an error when +installing ADT, your Eclipse installion might not include these packages. +For information about how to quickly add the necessary packages to your +Eclipse installation, see the troubleshooting topic +ADT +Installation Error: "requires plug-in org.eclipse.wst.sse.ui".

    + +

    For Linux users

    +

    If you encounter this error when installing the ADT Plugin for Eclipse: +

    +An error occurred during provisioning.
    +Cannot connect to keystore.
    +JKS
    +

    +...then your development machine lacks a suitable Java VM. Installing Sun +Java 6 will resolve this issue and you can then reinstall the ADT +Plugin.

    diff --git a/docs/html/sdk/installing/next.jd b/docs/html/sdk/installing/next.jd new file mode 100644 index 000000000000..b1da7c69dc24 --- /dev/null +++ b/docs/html/sdk/installing/next.jd @@ -0,0 +1,52 @@ +page.title=Next Steps +walkthru=1 + +@jd:body + + +

    Now that you've installed the Android SDK, here are are a few ways to learn Android +and start developing:

    + +

    Start coding

    +
      +
    • Follow the training class for Building Your First App. +

      This class is an essential first step for new Android developers.

      +

      It gives you step by step instructions for building a simple app. You’ll learn how to +create an Android project and run a debuggable version of the app. You'll also learn some +fundamentals of Android app design, including how to build a simple user interface and handle user +input.

      +
    • +
    + + +

    Learn how to design your app

    +
      +
    • Learn the best practices for Android design and user experience by reading the Android Design guidelines.
    • +
    + + +

    Read up on the API framework

    +
      +
    • Start reading about fundamental framework topics in the collection of API Guides.
    • +
    • Browse the API specifications in the Reference.
    • +
    + + +

    Explore the development tools

    +
      +
    • Learn about developing an app with the Android Developer Tools plugin for Eclipse + and other tools from the Workflow.
    • +
    + + +

    Explore some code

    + +
      +
    • Browse the sample apps available from the Android SDK Manager. You'll find them in +<sdk>/samples/<platform-version>/.
    • +
    diff --git a/docs/html/sdk/ndk/1.5_r1/index.jd b/docs/html/sdk/ndk/1.5_r1/index.jd deleted file mode 100644 index 4c70a8a6f91e..000000000000 --- a/docs/html/sdk/ndk/1.5_r1/index.jd +++ /dev/null @@ -1,6 +0,0 @@ -page.title=Android 1.5 NDK, Release 1 -sdk.redirect=true -sdk.redirect.path=ndk/index.html - -@jd:body - diff --git a/docs/html/sdk/ndk/1.6_r1/index.jd b/docs/html/sdk/ndk/1.6_r1/index.jd deleted file mode 100644 index 090dcdc37867..000000000000 --- a/docs/html/sdk/ndk/1.6_r1/index.jd +++ /dev/null @@ -1,5 +0,0 @@ -page.title=Android 1.6 NDK, Release 1 -sdk.redirect=true -sdk.redirect.path=ndk/index.html - -@jd:body diff --git a/docs/html/sdk/ndk/index.jd b/docs/html/sdk/ndk/index.jd deleted file mode 100644 index fddbcc7e713b..000000000000 --- a/docs/html/sdk/ndk/index.jd +++ /dev/null @@ -1,1055 +0,0 @@ -ndk=true - -ndk.win_download=android-ndk-r7c-windows.zip -ndk.win_bytes=80361003 -ndk.win_checksum=e86184cdc4bf71d32fa9185fad8544e2 - -ndk.mac_download=android-ndk-r7c-darwin-x86.tar.bz2 -ndk.mac_bytes=73836512 -ndk.mac_checksum=025f57feb5f32ed993a5fa7f5996477d - -ndk.linux_download=android-ndk-r7c-linux-x86.tar.bz2 -ndk.linux_bytes=63432410 -ndk.linux_checksum=0bc21b78823dcf6f86b988203626b1fe - -page.title=Android NDK - -@jd:body - -

    Revisions

    - -

    The sections below provide information and notes about successive releases of -the NDK, as denoted by revision number.

    - - - - -
    - - Android NDK, Revision 7c (April 2012) - -
    -

    This release of the NDK includes an important fix for Tegra2-based devices, and a few -additional fixes and improvements:

    - -
    -
    Important bug fixes:
    - -
    -
      -
    • Fixed GNU STL armeabi-v7a binaries to not crash on non-NEON - devices. The files provided with NDK r7b were not configured properly, - resulting in crashes on Tegra2-based devices and others when trying to use - certain floating-point functions (e.g., {@code cosf}, {@code sinf}, {@code expf}).
    • -
    -
    - -
    Important changes:
    - -
    -
      -
    • Added support for custom output directories through the {@code NDK_OUT} - environment variable. When defined, this variable is used to store all - intermediate generated files, instead of {@code $PROJECT_PATH/obj}. The variable is - also recognized by {@code ndk-gdb}.
    • -
    • Added support for building modules with hundreds or even thousands of source - files by defining {@code LOCAL_SHORT_COMMANDS} to {@code true} in your {@code Android.mk}. -

      This change forces the NDK build system to put most linker or archiver options - into list files, as a work-around for command-line length limitations. - See {@code docs/ANDROID-MK.html} for details.

      -
    • -
    -
    - -
    Other bug fixes:
    - -
    -
      -
    • Fixed {@code android_getCpuCount()} implementation in the {@code cpufeatures} -helper library. On certain devices, where cores are enabled dynamically by the system, the previous -implementation would report the total number of active cores the first time the function -was called, rather than the total number of physically available cores.
    • -
    -
    -
    -
    -
    - - -
    - - Android NDK, Revision 7b (February 2012) - -
    -

    This release of the NDK includes fixes for native Windows builds, Cygwin and many other - improvements:

    - -
    -
    Important bug fixes:
    - -
    -
      -
    • Updated {@code sys/atomics.h} to avoid correctness issues - on some multi-core ARM-based devices. Rebuild your unmodified sources with this - version of the NDK and this problem should be completely eliminated. - For more details, read {@code docs/ANDROID-ATOMICS.html}.
    • -
    • Reverted to {@code binutils} 2.19 to fix debugging issues that - appeared in NDK r7 (which switched to {@code binutils} 2.20.1).
    • -
    • Fixed {@code ndk-build} on 32-bit Linux. A packaging error put a 64-bit version - of the {@code awk} executable under {@code prebuilt/linux-x86/bin} in NDK r7.
    • -
    • Fixed native Windows build ({@code ndk-build.cmd}). Other build modes were not - affected. The fixes include: -
        -
      • Removed an infinite loop / stack overflow bug that happened when trying - to call {@code ndk-build.cmd} from a directory that was not the top of - your project path (e.g., in any sub-directory of it).
      • -
      • Fixed a problem where the auto-generated dependency files were ignored. This - meant that updating a header didn't trigger recompilation of sources that included - it.
      • -
      • Fixed a problem where special characters in files or paths, other than spaces and - quotes, were not correctly handled.
      • -
      -
    • -
    • Fixed the standalone toolchain to generate proper binaries when using - {@code -lstdc++} (i.e., linking against the GNU {@code libstdc++} C++ runtime). You - should use {@code -lgnustl_shared} if you want to link against the shared library - version or {@code -lstdc++} for the static version. - -

      See {@code docs/STANDALONE-TOOLCHAIN.html} for more details about this fix.

      -
    • -
    • Fixed {@code gnustl_shared} on Cygwin. The linker complained that it couldn't find - {@code libsupc++.a} even though the file was at the right location.
    • -
    • Fixed Cygwin C++ link when not using any specific C++ runtime through - {@code APP_STL}.
    • -
    -
    -
    - -
    -
    Other changes:
    - -
    -
      -
    • When your application uses the GNU {@code libstdc++} runtime, the compiler will - no longer forcibly enable exceptions and RTTI. This change results in smaller code. -

      If you need these features, you must do one of the following:

      -
        -
      • Enable exceptions and/or RTTI explicitly in your modules or - {@code Application.mk}. (recommended)
      • -
      • Define {@code APP_GNUSTL_FORCE_CPP_FEATURES} to {@code 'exceptions'}, - {@code 'rtti'} or both in your {@code Application.mk}. See - {@code docs/APPLICATION-MK.html} for more details.
      • -
      -
    • -
    • {@code ndk-gdb} now works properly when your application has private services - running in independent processes. It debugs the main application process, instead of the - first process listed by {@code ps}, which is usually a service process.
    • -
    • Fixed a rare bug where NDK r7 would fail to honor the {@code LOCAL_ARM_MODE} value - and always compile certain source files (but not all) to 32-bit instructions.
    • -
    • {@code stlport}: Refresh the sources to match the Android platform version. This - update fixes a few minor bugs: -
        -
      • Fixed instantiation of an incomplete type
      • -
      • Fixed minor "==" versus "=" typo
      • -
      • Used {@code memmove} instead of {@code memcpy} in {@code string::assign}
      • -
      • Added better handling of {@code IsNANorINF}, {@code IsINF}, {@code IsNegNAN}, - etc.
      • -
      -

      For complete details, see the commit log.

      -
    • -
    • {@code stlport}: Removed 5 unnecessary static initializers from the library.
    • -
    • The GNU libstdc++ libraries for armeabi-v7a were mistakenly compiled for - armeabi instead. This change had no impact on correctness, but using the right - ABI should provide slightly better performance.
    • -
    • The {@code cpu-features} helper library was updated to report three optional - x86 CPU features ({@code SSSE3}, {@code MOVBE} and {@code POPCNT}). See - {@code docs/CPU-FEATURES.html} for more details.
    • -
    • {@code docs/NDK-BUILD.html} was updated to mention {@code NDK_APPLICATION_MK} instead - of {@code NDK_APP_APPLICATION_MK} to select a custom {@code Application.mk} file.
    • -
    • Cygwin: {@code ndk-build} no longer creates an empty "NUL" file in the current - directory when invoked.
    • -
    • Cygwin: Added better automatic dependency detection. In the previous version, it - didn't work properly in the following cases: -
        -
      • When the Cygwin drive prefix was not {@code /cygdrive}.
      • -
      • When using drive-less mounts, for example, when Cygwin would translate - {@code /home} to {@code \\server\subdir} instead of {@code C:\Some\Dir}.
      • -
      -
    • -
    • Cygwin: {@code ndk-build} does not try to use the native Windows tools under - {@code $NDK/prebuilt/windows/bin} with certain versions of Cygwin and/or GNU Make.
    • -
    -
    -
    -
    -
    - - -
    - - Android NDK, Revision 7 (November 2011) - -
    -

    This release of the NDK includes new features to support the Android 4.0 platform as well - as many other additions and improvements:

    - -
    -
    New features
    - -
    -
      -
    • Added official NDK APIs for Android 4.0 (API level 14), which adds the following - native features to the platform: - -
        -
      • Added native multimedia API based on the Khronos Group OpenMAX AL™ 1.0.1 - standard. The new <OMXAL/OpenMAXAL.h> and - <OMXAL/OpenMAXAL_Android.h> headers allow applications targeting - API level 14 to perform multimedia output directly from native code by using a new - Android-specific buffer queue interface. For more details, see - docs/openmaxal/index.html and http://www.khronos.org/openmax/.
      • - -
      • Updated the native audio API based on the Khronos Group OpenSL ES 1.0.1™ - standard. With API Level 14, you can now decode compressed audio (e.g. MP3, AAC, - Vorbis) to PCM. For more details, see docs/opensles/index.html and - http://www.khronos.org/opensles/.
      • -
      -
    • - -
    • Added CCache support. To speed up large rebuilds, define the - NDK_CCACHE environment variable to ccache (or the path to - your ccache binary). When declared, the NDK build system automatically - uses CCache when compiling any source file. For example: -
      -export NDK_CCACHE=ccache
      -
      -

      Note: CCache is not included in the NDK release - so you must have it installed prior to using it. For more information about CCache, see - http://ccache.samba.org.

      -
    • - -
    • Added support for setting APP_ABI to all to indicate that - you want to build your NDK modules for all the ABIs supported by your given NDK - release. This means that either one of the following two lines in your - Application.mk are equivalent with this release: -
      -APP_ABI := all
      -APP_ABI := armeabi armeabi-v7a x86
      -
      - -

      This also works if you define APP_ABI when calling - ndk-build from the command-line, which is a quick way to check that your - project builds for all supported ABIs without changing the project's - Application.mk file. For example:

      -
      -ndk-build APP_ABI=all
      -
      -
    • - -
    • Added a LOCAL_CPP_FEATURES variable in Android.mk that - allows you to declare which C++ features (RTTI or Exceptions) your module uses. This - ensures that the final linking works correctly if you have prebuilt modules that depend - on these features. See docs/ANDROID-MK.html and - docs/CPLUSPLUS-SUPPORT.html for more details.
    • - -
    • Shortened paths to source and object files that are used in build commands. When - invoking $NDK/ndk-build from your project path, the paths to the source, - object, and binary files that are passed to the build commands are significantly - shorter now, because they are passed relative to the current directory. This is useful - when building projects with a lot of source files, to avoid limits on the maximum - command line length supported by your host operating system. The behavior is unchanged - if you invoke ndk-build from a sub-directory of your project tree, or if - you define NDK_PROJECT_PATH to point to a specific directory.
    • -
    -
    - -
    Experimental features
    - -
    - You can now build your NDK source files on Windows without Cygwin by calling the - ndk-build.cmd script from the command line from your project path. The - script takes exactly the same arguments as the original ndk-build script. - The Windows NDK package comes with its own prebuilt binaries for GNU Make, Awk and other - tools required by the build. You should not need to install anything else to get a - working build system. - -

    Important: ndk-gdb does not work on - Windows, so you still need Cygwin to debug.

    - -

    This feature is still experimental, so feel free to try it and report issues on the - public bug database or public forum. All samples and unit tests - shipped with the NDK succesfully compile with this feature.

    -
    - -
    Important bug fixes
    - -
    -
      -
    • Imported shared libraries are now installed by default to the target installation - location (libs/<abi>) if APP_MODULES is not defined in - your Application.mk. For example, if a top-level module foo - imports a module bar, then both libfoo.so and - libbar.so are copied to the install location. Previously, only - libfoo.so was copied, unless you listed bar in your - APP_MODULES too. If you define APP_MODULES explicitly, the - behavior is unchanged.
    • - -
    • ndk-gdb now works correctly for activities with multiple categories in - their MAIN intent filters.
    • - -
    • Static library imports are now properly transitive. For example, if a top-level - module foo imports static library bar that imports static - library zoo, the libfoo.so will now be linked against both - libbar.a and libzoo.a.
    • -
    -
    - -
    Other changes
    - -
    -
      -
    • docs/NATIVE-ACTIVITY.HTML: Fixed typo. The minimum API level should be - 9, not 8 for native activities.
    • - -
    • docs/STABLE-APIS.html: Added missing documentation listing EGL as a - supported stable API, starting from API level 9.
    • - -
    • download-toolchain-sources.sh: Updated to download the toolchain - sources from android.googlesource.com, - which is the new location for the AOSP servers.
    • - -
    • Added a new C++ support runtime named gabi++. More details about it - are available in the updated docs/CPLUSPLUS-SUPPORT.html.
    • - -
    • Added a new C++ support runtime named gnustl_shared that corresponds - to the shared library version of GNU libstdc++ v3 (GPLv3 license). See more info at - docs/CPLUSPLUS-SUPPORT.html
    • - -
    • Added support for RTTI in the STLport C++ runtimes (no support for - exceptions).
    • - -
    • Added support for multiple file extensions in LOCAL_CPP_EXTENSION. For - example, to compile both foo.cpp and bar.cxx as C++ sources, - declare the following: -
      -LOCAL_CPP_EXTENSION := .cpp .cxx
      -
      -
    • - -
    • Removed many unwanted exported symbols from the link-time shared system libraries - provided by the NDK. This ensures that code generated with the standalone toolchain - doesn't risk to accidentally depend on a non-stable ABI symbol (e.g. any libgcc.a - symbol that changes each time the toolchain used to build the platform is changed)
    • - -
    • Refreshed the EGL and OpenGLES Khronos headers to support more extensions. Note - that this does not change the NDK ABIs for the corresponding libraries, - because each extension must be probed at runtime by the client application. - -

      The extensions that are available depend on your actual device and GPU drivers, - not the platform version the device runs on. The header changes simply add new - constants and types to make it easier to use the extensions when they have been - probed with eglGetProcAddress() or glGetProcAddress(). The - following list describes the newly supported extensions:

      - -
      -
      GLES 1.x
      - -
      -
        -
      • GL_OES_vertex_array_object
      • - -
      • GL_OES_EGL_image_external
      • - -
      • GL_APPLE_texture_2D_limited_npot
      • - -
      • GL_EXT_blend_minmax
      • - -
      • GL_EXT_discard_framebuffer
      • - -
      • GL_EXT_multi_draw_arrays
      • - -
      • GL_EXT_read_format_bgra
      • - -
      • GL_EXT_texture_filter_anisotropic
      • - -
      • GL_EXT_texture_format_BGRA8888
      • - -
      • GL_EXT_texture_lod_bias
      • - -
      • GL_IMG_read_format
      • - -
      • GL_IMG_texture_compression_pvrtc
      • - -
      • GL_IMG_texture_env_enhanced_fixed_function
      • - -
      • GL_IMG_user_clip_plane
      • - -
      • GL_IMG_multisampled_render_to_texture
      • - -
      • GL_NV_fence
      • - -
      • GL_QCOM_driver_control
      • - -
      • GL_QCOM_extended_get
      • - -
      • GL_QCOM_extended_get2
      • - -
      • GL_QCOM_perfmon_global_mode
      • - -
      • GL_QCOM_writeonly_rendering
      • - -
      • GL_QCOM_tiled_rendering
      • -
      -
      - -
      GLES 2.0
      - -
      -
        -
      • GL_OES_element_index_uint
      • - -
      • GL_OES_get_program_binary
      • - -
      • GL_OES_mapbuffer
      • - -
      • GL_OES_packed_depth_stencil
      • - -
      • GL_OES_texture_3D
      • - -
      • GL_OES_texture_float
      • - -
      • GL_OES_texture_float_linear
      • - -
      • GL_OES_texture_half_float_linear
      • - -
      • GL_OES_texture_npot
      • - -
      • GL_OES_vertex_array_object
      • - -
      • GL_OES_EGL_image_external
      • - -
      • GL_AMD_program_binary_Z400
      • - -
      • GL_EXT_blend_minmax
      • - -
      • GL_EXT_discard_framebuffer
      • - -
      • GL_EXT_multi_draw_arrays
      • - -
      • GL_EXT_read_format_bgra
      • - -
      • GL_EXT_texture_format_BGRA8888
      • - -
      • GL_EXT_texture_compression_dxt1
      • - -
      • GL_IMG_program_binary
      • - -
      • GL_IMG_read_format
      • - -
      • GL_IMG_shader_binary
      • - -
      • GL_IMG_texture_compression_pvrtc
      • - -
      • GL_IMG_multisampled_render_to_texture
      • - -
      • GL_NV_coverage_sample
      • - -
      • GL_NV_depth_nonlinear
      • - -
      • GL_QCOM_extended_get
      • - -
      • GL_QCOM_extended_get2
      • - -
      • GL_QCOM_writeonly_rendering
      • - -
      • GL_QCOM_tiled_rendering
      • -
      -
      - -
      EGL
      - -
      -
        -
      • EGL_ANDROID_recordable
      • - -
      • EGL_NV_system_time
      • -
      -
      -
      -
    • -
    -
    -
    -
    -
    - - - -
    - - Android NDK, Revision 6b (August 2011) - -
    -

    This release of the NDK does not include any new features compared to r6. The r6b release - addresses the following issues in the r6 release:

    -
    -
    Important bug fixes
    -
    -
      -
    • Fixed the build when APP_ABI="armeabi x86" is used for - multi-architecture builds.
    • -
    • Fixed the location of prebuilt STLport binaries in the NDK release package. - A bug in the packaging script placed them in the wrong location.
    • -
    • Fixed atexit() usage in shared libraries with the x86standalone - toolchain.
    • -
    • Fixed make-standalone-toolchain.sh --arch=x86. It used to fail - to copy the proper GNU libstdc++ binaries to the right location.
    • -
    • Fixed the standalone toolchain linker warnings about missing the definition and - size for the __dso_handle symbol (ARM only).
    • -
    • Fixed the inclusion order of $(SYSROOT)/usr/include for x86 builds. - See the bug for - more information.
    • -
    • Fixed the definitions of ptrdiff_t and size_t in - x86-specific systems when they are used with the x86 standalone toolchain.
    • -
    -
    -
    -
    -
    - -
    - - Android NDK, Revision 6 (July 2011) - -
    -

    This release of the NDK includes support for the x86 ABI and other minor changes. - For detailed information describing the changes in this release, read the - CHANGES.HTML document included in the NDK package. -

    -
    -
    General notes:
    -
    -
      -
    • Adds support for the x86 ABI, which allows you to generate machine code - that runs on compatible x86-based Android devices. Major features for x86 - include x86-specific toolchains, system headers, libraries and - debugging support. For all of the details regarding x86 support, - see docs/CPU-X86.html in the NDK package. - -

      By default, code is generated for ARM-based devices, but you can add x86 to your - APP_ABI definition in your Application.mk file to build - for x86 platforms. For example, the following line instructs ndk-build - to build your code for three distinct ABIs:

      - -
      APP_ABI := armeabi armeabi-v7a x86
      - -

      Unless you rely on ARM-based assembly sources, you shouldn't need to touch - your Android.mk files to build x86 machine code.

      - -
    • - -
    • You can build a standalone x86 toolchain using the --toolchain=x86-4.4.3 - option when calling make-standalone-toolchain.sh. See - docs/STANDALONE-TOOLCHAIN.html for more details. -
    • -
    • The new ndk-stack tool lets you translate stack traces in - logcat that are generated by native code. The tool translates - instruction addresses into a readable format that contains things such - as the function, source file, and line number corresponding to each stack frame. - For more information and a usage example, see docs/NDK-STACK.html. -
    • -
    -
    -
    Other changes:
    -
    arm-eabi-4.4.0, which had been deprecated since NDK r5, has been - removed from the NDK distribution.
    - -
    -
    -
    - -
    - - Android NDK, Revision 5c (June 2011) - -
    -

    This release of the NDK does not include any new features compared to r5b. The r5c release - addresses the following problems in the r5b release:

    -
    -
    Important bug fixes:
    -
    -
      -
    • ndk-build: Fixed a rare bug that appeared when trying to perform parallel - builds of debuggable projects.
    • - -
    • Fixed a typo that prevented LOCAL_WHOLE_STATIC_LIBRARIES to work - correctly with the new toolchain and added documentation for this in - docs/ANDROID-MK.html.
    • - -
    • Fixed a bug where code linked against gnustl_static crashed when run on - platform releases older than API level 8 (Android 2.2).
    • - -
    • ndk-gdb: Fixed a bug that caused a segmentation fault when debugging Android 3.0 - or newer devices.
    • - -
    • <android/input.h>: Two functions that were introduced in API level - 9 (Android 2.3) were incorrect and are fixed. While this breaks the source API, the - binary interface to the system is unchanged. The incorrect functions were missing a - history_index parameter, and the correct definitions are shown below: -
      -float AMotionEvent_getHistoricalRawX(const AInputEvent* motion_event,
      -                                           size_t pointer_index,
      -                                           size_t history_index);
      -
      -float AMotionEvent_getHistoricalRawY(const AInputEvent* motion_event,
      -                                           size_t pointer_index,
      -                                           size_t history_index);
      -
      -
    • - -
    • Updated the C library ARM binary for API level 9 (Android 2.3) to correctly expose at - link time new functions that were added in that API level (for example, - pthread_rwlock_init).
    • - -
    -
    - -
    Minor improvements and fixes:
    -
    -
      -
    • Object files are now always linked in the order they appear in - LOCAL_SRC_FILES. This was not the case previously because the files were - grouped by source extensions instead.
    • - -
    • When import-module fails, it now prints the list of directories that - were searched. This is useful to check that the NDK_MODULE_PATH definition - used by the build system is correct.
    • - -
    • When import-module succeeds, it now prints the directory where the - module was found to the log (visible with NDK_LOG=1).
    • - -
    • Increased the build speed of debuggable applications when there is a very large number - of include directories in the project.
    • - -
    • ndk-gdb: Better detection of adb shell failures and improved - error messages.
    • - -
    • <pthread.h>: Fixed the definition of - PTHREAD_RWLOCK_INITIALIZER for API level 9 (Android 2.3) and higher.
    • - -
    • Fixed an issue where a module could import itself, resulting in an infinite loop in - GNU Make.
    • - -
    • Fixed a bug that caused the build to fail if LOCAL_ARM_NEON was set to - true (typo in build/core/build-binary.mk).
    • - -
    • Fixed a bug that prevented the compilation of .s assembly files - (.S files were okay).
    • -
    -
    -
    -
    - -
    - Android NDK, Revision 5b (January 2011) - -
    -

    This release of the NDK does not include any new features compared to r5. The r5b release addresses the - following problems in the r5 release: -

    -
      -
    • The r5 binaries required glibc 2.11, but the r5b binaries are generated with a special - toolchain that targets glibc 2.7 or higher instead. The Linux toolchain binaries now run on Ubuntu 8.04 or higher.
    • -
    • Fixes a compiler bug in the arm-linux-androideabi-4.4.3 toolchain. - The previous binary generated invalid thumb instruction sequences when - dealing with signed chars.
    • -
    • Adds missing documentation for the - "gnustl_static" value for APP_STL, that allows you to link against - a static library version of GNU libstdc++.
    • -
    • The following ndk-build issues are fixed: -
        -
      • A bug that created inconsistent dependency files when a - compilation error occured on Windows. This prevented a proper build after - the error was fixed in the source code.
      • -
      • A Cygwin-specific bug where using very short paths for - the Android NDK installation or the project path led to the - generation of invalid dependency files. This made incremental builds - impossible.
      • -
      • A typo that prevented the cpufeatures library from working correctly - with the new NDK toolchain.
      • -
      • Builds in Cygwin are faster by avoiding calls to cygpath -m - from GNU Make for every source or object file, which caused problems - with very large source trees. In case this doesn't work properly, define NDK_USE_CYGPATH=1 in your - environment to use cygpath -m again.
      • -
      • The Cygwin installation now notifies the user of invalid installation paths that contain spaces. Previously, an invalid path - would output an error that complained about an incorrect version of GNU Make, even if the right one was installed. -
      -
    • -
    • Fixed a typo that prevented the NDK_MODULE_PATH environment variable from working properly when - it contained multiple directories separated with a colon.
    • -
    • The prebuilt-common.sh script contains fixes to check the compiler for 64-bit - generated machine code, instead of relying on the host tag, which - allows the 32-bit toolchain to rebuild properly on Snow Leopard. The toolchain rebuild scripts now also support - using a 32-bit host toolchain.
    • -
    • A missing declaration for INET_ADDRSTRLEN was added to <netinet/in.h>.
    • -
    • Missing declarations for IN6_IS_ADDR_MC_NODELOCAL and IN6_IS_ADDR_MC_GLOBAL were added to <netinet/in6.h>.
    • -
    • 'asm' was replaced with '__asm__' in <asm/byteorder.h> to allow compilation with -std=c99.
    • -
    -
    -
    - -
    - Android NDK, Revision 5 (December 2010) - -
    -

    This release of the NDK includes many new APIs, most of which are introduced to - support the development of games and similar applications that make extensive use - of native code. Using the APIs, developers have direct native access to events, audio, - graphics and window management, assets, and storage. Developers can also implement the - Android application lifecycle in native code with help from the new - {@link android.app.NativeActivity} class. For detailed information describing the changes in this - release, read the CHANGES.HTML document included in the downloaded NDK package. -

    -
    -
    General notes:
    -
    -
      -
    • Adds support for native activities, which allows you to implement the - Android application lifecycle in native code.
    • - -
    • Adds native support for the following: - -
        - -
      • Input subsystem (such as the keyboard and touch screen)
      • - -
      • Access to sensor data (accelerometer, compass, gyroscope, etc).
      • - -
      • Event loop APIs to wait for things such as input and sensor events.
      • - -
      • Window and surface subsystem
      • - -
      • Audio APIs based on the OpenSL ES standard that support playback and recording - as well as control over platform audio effects
      • - -
      • Access to assets packaged in an .apk file.
      • - -
      -
    • - -
    • Includes a new toolchain (based on GCC 4.4.3), which generates better code, and can also now - be used as a standalone cross-compiler, for people who want to build their stuff with - ./configure && make. See - docs/STANDALONE-TOOLCHAIN.html for the details. The binaries for GCC 4.4.0 are still provided, - but the 4.2.1 binaries were removed.
    • - -
    • Adds support for prebuilt static and shared libraries (docs/PREBUILTS.html) and module - exports and imports to make sharing and reuse of third-party modules much easier - (docs/IMPORT-MODULE.html explains why).
    • - -
    • Provides a default C++ STL implementation (based on STLport) as a helper module. It can be used either - as a static or shared library (details and usage examples are in sources/android/stlport/README). Prebuilt - binaries for STLport (static or shared) and GNU libstdc++ (static only) are also provided if you choose to - compile against those libraries instead of the default C++ STL implementation. - C++ Exceptions and RTTI are not supported in the default STL implementation. For more information, see - docs/CPLUSPLUS-SUPPORT.HTML.
    • - -
    • Includes improvements to the cpufeatures helper library that improves reporting - of the CPU type (some devices previously reported ARMv7 CPU when the device really was an ARMv6). We - recommend developers that use this library to rebuild their applications then - upload to Google Play to benefit from the improvements.
    • - -
    • Adds an EGL library that lets you create and manage OpenGL ES textures and - services.
    • - -
    • Adds new sample applications, native-plasma and native-activity, - to demonstrate how to write a native activity.
    • - -
    • Includes many bugfixes and other small improvements; see docs/CHANGES.html for a more - detailed list of changes.
    • -
    -
    -
    -
    -
    - -
    - Android NDK, Revision 4b (June 2010) - -
    -
    -
    NDK r4b notes:
    - -
    -

    Includes fixes for several issues in the NDK build and debugging scripts — if - you are using NDK r4, we recommend downloading the NDK r4b build. For detailed - information describing the changes in this release, read the CHANGES.TXT document - included in the downloaded NDK package.

    -
    -
    - -
    -
    General notes:
    - -
    -
      -
    • Provides a simplified build system through the new ndk-build build - command.
    • - -
    • Adds support for easy native debugging of generated machine code on production - devices through the new ndk-gdb command.
    • - -
    • Adds a new Android-specific ABI for ARM-based CPU architectures, - armeabi-v7a. The new ABI extends the existing armeabi ABI to - include these CPU instruction set extensions: - -
        -
      • Thumb-2 instructions
      • - -
      • VFP hardware FPU instructions (VFPv3-D16)
      • - -
      • Optional support for ARM Advanced SIMD (NEON) GCC intrinsics and VFPv3-D32. - Supported by devices such as Verizon Droid by Motorola, Google Nexus One, and - others.
      • -
      -
    • - -
    • Adds a new cpufeatures static library (with sources) that lets your - app detect the host device's CPU features at runtime. Specifically, applications can - check for ARMv7-A support, as well as VFPv3-D32 and NEON support, then provide separate - code paths as needed.
    • - -
    • Adds a sample application, hello-neon, that illustrates how to use the - cpufeatures library to check CPU features and then provide an optimized - code path using NEON instrinsics, if supported by the CPU.
    • - -
    • Lets you generate machine code for either or both of the instruction sets supported - by the NDK. For example, you can build for both ARMv5 and ARMv7-A architectures at the - same time and have everything stored to your application's final - .apk.
    • - -
    • To ensure that your applications are available to users only if their devices are - capable of running them, Google Play now filters applications based on the - instruction set information included in your application — no action is needed on - your part to enable the filtering. Additionally, the Android system itself also checks - your application at install time and allows the installation to continue only if the - application provides a library that is compiled for the device's CPU architecture.
    • - -
    • Adds support for Android 2.2, including a new stable API for accessing the pixel - buffers of {@link android.graphics.Bitmap} objects from native code.
    • -
    -
    -
    -
    -
    - -
    - Android NDK, Revision 3 (March 2010) - -
    -
    -
    General notes:
    - -
    -
      -
    • Adds OpenGL ES 2.0 native library support.
    • - -
    • Adds a sample application,hello-gl2, that illustrates the use of - OpenGL ES 2.0 vertex and fragment shaders.
    • - -
    • The toolchain binaries have been refreshed for this release with GCC 4.4.0, which - should generate slightly more compact and efficient machine code than the previous one - (4.2.1). The NDK also still provides the 4.2.1 binaries, which you can optionally use - to build your machine code.
    • -
    -
    -
    -
    -
    - -
    - Android NDK, Revision 2 (September 2009) - -
    -

    Originally released as "Android 1.6 NDK, Release 1".

    - -
    -
    General notes:
    - -
    -
      -
    • Adds OpenGL ES 1.1 native library support.
    • - -
    • Adds a sample application, san-angeles, that renders 3D graphics - through the native OpenGL ES APIs, while managing activity lifecycle with a {@link - android.opengl.GLSurfaceView} object.
    • -
    -
    -
    -
    -
    - -
    - Android NDK, Revision 1 (June 2009) - -
    -

    Originally released as "Android 1.5 NDK, Release 1".

    - -
    -
    General notes:
    - -
    -
      -
    • Includes compiler support (GCC) for ARMv5TE instructions, including Thumb-1 - instructions.
    • - -
    • Includes system headers for stable native APIs, documentation, and sample - applications.
    • -
    -
    -
    -
    -
    - -

    Installing the NDK

    -

    Installing the NDK on your development computer is straightforward and involves extracting the - NDK from its download package.

    - -

    Before you get started make sure that you have downloaded the latest Android SDK and upgraded your applications and environment as - needed. The NDK is compatible with older platform versions but not older versions of the SDK tools. - Also, take a moment to review the System and -Software Requirements - for the NDK, if you haven't already.

    - -

    To install the NDK, follow these steps:

    - -
      -
    1. From the table at the top of this page, select the NDK package that is appropriate for your - development computer and download the package.
    2. - -
    3. Uncompress the NDK download package using tools available on your computer. When - uncompressed, the NDK files are contained in a directory called - android-ndk-<version>. You can rename the NDK directory if necessary and you - can move it to any location on your computer. This documentation refers to the NDK directory as - <ndk>.
    4. -
    - -

    You are now ready to start working with the NDK.

    - -

    Getting Started with the NDK

    - -

    Once you've installed the NDK successfully, take a few minutes to read the documentation - included in the NDK. You can find the documentation in the <ndk>/docs/ - directory. In particular, please read the OVERVIEW.HTML document completely, so that you - understand the intent of the NDK and how to use it.

    - -

    If you used a previous version of the NDK, take a moment to review the list of NDK changes in - the CHANGES.HTML document.

    - -

    Here's the general outline of how you work with the NDK tools:

    - -
      -
    1. Place your native sources under <project>/jni/...
    2. - -
    3. Create <project>/jni/Android.mk to describe your native sources to the - NDK build system
    4. - -
    5. Optional: Create <project>/jni/Application.mk.
    6. - -
    7. Build your native code by running the 'ndk-build' script from your project's directory. It - is located in the top-level NDK directory: -
      cd <project>
      -<ndk>/ndk-build
      -
      - -

      The build tools copy the stripped, shared libraries needed by your application to the - proper location in the application's project directory.

      -
    8. - -
    9. Finally, compile your application using the SDK tools in the usual way. The SDK build tools - will package the shared libraries in the application's deployable .apk file.
    10. -
    - -

    For complete information on all of the steps listed above, please see the documentation - included with the NDK package.

    - -

    Sample Applications

    - -

    The NDK includes sample Android applications that illustrate how to use native code in your - Android applications. For more information, see Sample Applications.

    - -

    Discussion Forum and Mailing List

    - -

    If you have questions about the NDK or would like to read or contribute to discussions about - it, please visit the android-ndk group - and mailing list.

    diff --git a/docs/html/sdk/ndk/overview.jd b/docs/html/sdk/ndk/overview.jd deleted file mode 100644 index d2a974621bef..000000000000 --- a/docs/html/sdk/ndk/overview.jd +++ /dev/null @@ -1,559 +0,0 @@ -page.title=What is the NDK? -@jd:body - - - -

    The Android NDK is a toolset that lets you embed components that make use of native code in - your Android applications.

    - -

    Android applications run in the Dalvik virtual machine. The NDK allows you to implement parts - of your applications using native-code languages such as C and C++. This can provide benefits to - certain classes of applications, in the form of reuse of existing code and in some cases - increased speed.

    - -

    The NDK provides:

    - -
      -
    • A set of tools and build files used to generate native code libraries from C and C++ - sources
    • - -
    • A way to embed the corresponding native libraries into an application package file - (.apk) that can be deployed on Android devices
    • - -
    • A set of native system headers and libraries that will be supported in all future versions - of the Android platform, starting from Android 1.5. Applications that use native activities - must be run on Android 2.3 or later.
    • - -
    • Documentation, samples, and tutorials
    • -
    - -

    The latest release of the NDK supports the following instruction sets:

    - -
      -
    • ARMv5TE (including Thumb-1 instructions)
    • - -
    • ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for - NEON/VFPv3-D32 instructions)
    • - -
    • x86 instructions (see CPU-ARCH-ABIS.HTML for more information)
    • -
    - -

    ARMv5TE machine code will run on all ARM-based Android devices. ARMv7-A will run only on - devices such as the Verizon Droid or Google Nexus One that have a compatible CPU. The main - difference between the two instruction sets is that ARMv7-A supports hardware FPU, Thumb-2, and - NEON instructions. You can target either or both of the instruction sets — ARMv5TE is the - default, but switching to ARMv7-A is as easy as adding a single line to the application's - Application.mk file, without needing to change anything else in the file. You can also build for - both architectures at the same time and have everything stored in the final .apk. - Complete information is provided in the CPU-ARCH-ABIS.HTML in the NDK package.

    - -

    The NDK provides stable headers for libc (the C library), libm (the Math library), OpenGL ES - (3D graphics library), the JNI interface, and other libraries, as listed in the Development Tools section.

    - -

    When to Develop in Native Code

    - -

    The NDK will not benefit most applications. As a developer, you need to balance its benefits - against its drawbacks; notably, using native code does not result in an automatic performance - increase, but always increases application complexity. In general, you should only use native - code if it is essential to your application, not just because you prefer to program in C/C++.

    - -

    Typical good candidates for the NDK are self-contained, CPU-intensive operations that don't - allocate much memory, such as signal processing, physics simulation, and so on. Simply re-coding - a method to run in C usually does not result in a large performance increase. When examining - whether or not you should develop in native code, think about your requirements and see if the - Android framework APIs provide the functionality that you need. The NDK can, however, can be an - effective way to reuse a large corpus of existing C/C++ code.

    - -

    The Android framework provides two ways to use native code:

    - -
      -
    • Write your application using the Android framework and use JNI to access the APIs provided - by the Android NDK. This technique allows you to take advantage of the convenience of the - Android framework, but still allows you to write native code when necessary. You can install - applications that use native code through the JNI on devices that run Android 1.5 or - later.
    • - -
    • -

      Write a native activity, which allows you to implement the lifecycle callbacks in native - code. The Android SDK provides the {@link android.app.NativeActivity} class, which is a convenience class that notifies your - native code of any activity lifecycle callbacks (onCreate(), onPause(), - onResume(), etc). You can implement the callbacks in your native code to handle - these events when they occur. Applications that use native activities must be run on Android - 2.3 (API Level 9) or later.

      - -

      You cannot access features such as Services and Content Providers natively, so if you want - to use them or any other framework API, you can still write JNI code to do so.

      -
    • -
    - -

    Contents of the NDK

    The NDK contains the APIs, documentation, and sample - applications that help you write your native code. - -

    Development tools

    - -

    The NDK includes a set of cross-toolchains (compilers, linkers, etc..) that can generate - native ARM binaries on Linux, OS X, and Windows (with Cygwin) platforms.

    - -

    It provides a set of system headers for stable native APIs that are guaranteed to be supported - in all later releases of the platform:

    - -
      -
    • libc (C library) headers
    • - -
    • libm (math library) headers
    • - -
    • JNI interface headers
    • - -
    • libz (Zlib compression) headers
    • - -
    • liblog (Android logging) header
    • - -
    • OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headers
    • - -
    • libjnigraphics (Pixel buffer access) header (for Android 2.2 and above).
    • - -
    • A Minimal set of headers for C++ support
    • - -
    • OpenSL ES native audio libraries
    • - -
    • Android native application APIS
    • -
    - -

    The NDK also provides a build system that lets you work efficiently with your sources, without - having to handle the toolchain/platform/CPU/ABI details. You create very short build files to - describe which sources to compile and which Android application will use them — the build - system compiles the sources and places the shared libraries directly in your application - project.

    - -

    Important: With the exception of the libraries listed above, - native system libraries in the Android platform are not stable and may change in future - platform versions. Your applications should only make use of the stable native system - libraries provided in this NDK.

    - -

    Documentation

    - -

    The NDK package includes a set of documentation that describes the capabilities of the NDK and - how to use it to create shared libraries for your Android applications. In this release, the - documentation is provided only in the downloadable NDK package. You can find the documentation in - the <ndk>/docs/ directory. Included are these files:

    - -
      -
    • - INSTALL.HTML — describes how to install the NDK and configure it for your host - system
    • - -
    • OVERVIEW.HTML — provides an overview of the NDK capabilities and usage
    • - -
    • ANDROID-MK.HTML — describes the use of the Android.mk file, which defines the native - sources you want to compile
    • - -
    • APPLICATION-MK.HTML — describes the use of the Application.mk file, which describes - the native sources required by your Android application
    • -
    • CPLUSPLUS-SUPPORT.HTML — describes the C++ support provided in the Android NDK
    • -
    • CPU-ARCH-ABIS.HTML — a description of supported CPU architectures and how to target - them.
    • - -
    • CPU-FEATURES.HTML — a description of the cpufeatures static library that - lets your application code detect the target device's CPU family and the optional features at - runtime.
    • - -
    • CPU-ARM-NEON.HTML — a description of how to build with optional ARM NEON / VFPv3-D32 - instructions.
    • - -
    • CHANGES.HTML — a complete list of changes to the NDK across all releases.
    • - -
    • DEVELOPMENT.HTML — describes how to modify the NDK and generate release packages for it
    • - -
    • HOWTO.HTML — information about common tasks associated with NDK development
    • - -
    • IMPORT-MODULE.HTML — describes how to share and reuse modules
    • - -
    • LICENSES.HTML — information about the various open source licenses that govern the Android NDK
    • - -
    • NATIVE-ACTIVITY.HTML — describes how to implement native activities
    • - -
    • NDK-BUILD.HTML — describes the usage of the ndk-build script
    • - -
    • NDK-GDB.HTML — describes how to use the native code debugger
    • - -
    • PREBUILTS.HTML — information about how shared and static prebuilt libraries work
    • - -
    • STANDALONE-TOOLCHAIN.HTML — describes how to use Android NDK toolchain as a standalone - compiler (still in beta).
    • - -
    • SYSTEM-ISSUES.HTML — known issues in the Android system images that you should be - aware of, if you are developing using the NDK.
    • - -
    • STABLE-APIS.HTML — a complete list of the stable APIs exposed by headers in the - NDK.
    • - -
    - -

    Additionally, the package includes detailed information about the "bionic" C library provided - with the Android platform that you should be aware of, if you are developing using the NDK. You - can find the documentation in the <ndk>/docs/system/libc/ directory:

    - -
      -
    • OVERVIEW.HTML — provides an overview of the "bionic" C library and the features it - offers.
    • -
    - -

    Sample applications

    - -

    The NDK includes sample applications that illustrate how to use native code in your Android - applications:

    - -
      -
    • hello-jni — a simple application that loads a string from a native - method implemented in a shared library and then displays it in the application UI.
    • - -
    • two-libs — a simple application that loads a shared library dynamically - and calls a native method provided by the library. In this case, the method is implemented in a - static library imported by the shared library.
    • - -
    • san-angeles — a simple application that renders 3D graphics through the - native OpenGL ES APIs, while managing activity lifecycle with a {@link - android.opengl.GLSurfaceView} object.
    • - -
    • hello-gl2 — a simple application that renders a triangle using OpenGL ES - 2.0 vertex and fragment shaders.
    • - -
    • hello-neon — a simple application that shows how to use the - cpufeatures library to check CPU capabilities at runtime, then use NEON intrinsics - if supported by the CPU. Specifically, the application implements two versions of a tiny - benchmark for a FIR filter loop, a C version and a NEON-optimized version for devices that - support it.
    • - -
    • bitmap-plasma — a simple application that demonstrates how to access the - pixel buffers of Android {@link android.graphics.Bitmap} objects from native code, and uses - this to generate an old-school "plasma" effect.
    • - -
    • native-activity — a simple application that demonstrates how to use the - native-app-glue static library to create a native activity
    • - -
    • native-plasma — a version of bitmap-plasma implemented with a native - activity.
    • -
    - -

    For each sample, the NDK includes the corresponding C source code and the necessary Android.mk - and Application.mk files. There are located under <ndk>/samples/<name>/ - and their source code can be found under <ndk>/samples/<name>/jni/.

    - -

    You can build the shared libraries for the sample apps by going into - <ndk>/samples/<name>/ then calling the ndk-build command. - The generated shared libraries will be located under - <ndk>/samples/<name>/libs/armeabi/ for (ARMv5TE machine code) and/or - <ndk>/samples/<name>/libs/armeabi-v7a/ for (ARMv7 machine code).

    - -

    Next, build the sample Android applications that use the shared libraries:

    - -
      -
    • If you are developing in Eclipse with ADT, use the New Project Wizard to create a new - Android project for each sample, using the "Import from Existing Source" option and importing - the source from <ndk>/samples/<name>/. Then, set up an AVD, - if necessary, and build/run the application in the emulator.
    • - -
    • If you are developing with Ant, use the android tool to create the build file - for each of the sample projects at <ndk>/samples/<name>/. - Then set up an AVD, if necessary, build your project in the usual way, and run it in the - emulator.
    • - -
    - -

    For more information about developing with the Android SDK tools and what - you need to do to create, build, and run your applications, see - the Overview - section for developing on Android.

    - -

    Exploring the hello-jni Sample

    - -

    The hello-jni sample is a simple demonstration on how to use JNI from an Android application. - The HelloJni activity receives a string from a simple C function and displays it in a - TextView.

    - -

    The main components of the sample include:

    - -
      -
    • The familiar basic structure of an Android application (an AndroidManifest.xml - file, a src/ and res directories, and a main activity)
    • - -
    • A jni/ directory that includes the implemented source file for the native code - as well as the Android.mk file
    • - -
    • A tests/ directory that contains unit test code.
    • -
    - -
      -
    1. Create a new project in Eclipse from the existing sample source or use the - android tool to update the project so it generates a build.xml file that you can - use to build the sample. - -
        -
      • In Eclipse: - -
          -
        1. Click File > New Android Project...
        2. - -
        3. Select the Create project from existing source radio button.
        4. - -
        5. Select any API level above Android 1.5.
        6. - -
        7. In the Location field, click Browse... and select - the <ndk-root>/samples/hello-jni directory.
        8. - -
        9. Click Finish.
        10. -
        -
      • - -
      • On the command line: - -
          -
        1. Change to the <ndk-root>/samples/hello-jni directory.
        2. - -
        3. Run the following command to generate a build.xml file: -
          android update project -p . -s
          -
        4. -
        -
      • -
      -
    2. - -
    3. Compile the native code using the ndk-build command. -
      -cd <ndk-root>/samples/hello-jni
      -<ndk_root>/ndk-build
      -
      -
    4. - -
    5. Build and install the application as you would a normal Android application. If you are - using Eclipse, run the application to build and install it on a device. If you are using Ant, - run the following commands from the project directory: -
      -ant debug
      -adb install bin/HelloJni-debug.apk
      -
      -
    6. -
    - -

    When you run the application on the device, the string Hello JNI should appear on - your device. You can explore the rest of the samples that are located in the - <ndk-root>/samples directory for more examples on how to use the JNI.

    - -

    Exploring the native-activity Sample Application

    - -

    The native-activity sample provided with the Android NDK demonstrates how to use the - android_native_app_glue static library. This static library makes creating a native activity - easier by providing you with an implementation that handles your callbacks in another thread, so - you do not have to worry about them blocking your main UI thread. The main parts of the sample - are described below:

    - -
      -
    • The familiar basic structure of an Android application (an AndroidManifest.xml - file, a src/ and res directories). The AndroidManifest.xml declares - that the application is native and specifies the .so file of the native activity. See {@link - android.app.NativeActivity} for the source or see the - <ndk_root>/platforms/samples/native-activity/AndroidManifest.xml file.
    • - -
    • A jni/ directory contains the native activity, main.c, which uses the - android_native_app_glue.h interface to implement the activity. The Android.mk that - describes the native module to the build system also exists here.
    • -
    - -

    To build this sample application:

    - -
      -
    1. Create a new project in Eclipse from the existing sample source or use the - android tool to update the project so it generates a build.xml file that you can - use to build the sample. - -
        -
      • In Eclipse: - -
          -
        1. Click File > New Android Project...
        2. - -
        3. Select the Create project from existing source radio button.
        4. - -
        5. Select any API level above Android 2.3.
        6. - -
        7. In the Location field, click Browse... and select - the <ndk-root>/samples/native-activity directory.
        8. - -
        9. Click Finish.
        10. -
        -
      • - -
      • On the command line: - -
          -
        1. Change to the <ndk-root>/samples/native-activity directory.
        2. - -
        3. Run the following command to generate a build.xml file: -
          -android update project -p . -s
          -
          -
        4. -
        -
      • -
      -
    2. - -
    3. Compile the native code using the ndk-build command. -
      -cd <ndk-root>/platforms/samples/android-9/samples/native-activity
      -<ndk_root>/ndk-build
      -
      -
    4. - -
    5. Build and install the application as you would a normal Android application. If you are - using Eclipse, run the application to build and install it on a device. If you are using Ant, - run the following commands in the project directory, then run the application on the device: -
      -ant debug
      -adb install bin/NativeActivity-debug.apk
      -
      -
    6. -
    - - -

    System and Software Requirements

    - -

    The sections below describe the system and software requirements for using the Android NDK, as - well as platform compatibility considerations that affect appplications using libraries produced - with the NDK.

    - -

    The Android SDK

    - -
      -
    • A complete Android SDK installation (including all dependencies) is required.
    • - -
    • Android 1.5 SDK or later version is required.
    • -
    - -

    Supported operating systems

    - -
      -
    • Windows XP (32-bit) or Vista (32- or 64-bit)
    • - -
    • Mac OS X 10.4.8 or later (x86 only)
    • - -
    • Linux (32 or 64-bit; Ubuntu 8.04, or other Linux distributions using GLibc 2.7 or -later)
    • -
    - -

    Required development tools

    - -
      -
    • For all development platforms, GNU Make 3.81 or later is required. Earlier versions of GNU - Make might work but have not been tested.
    • - -
    • A recent version of awk (either GNU Awk or Nawk) is also required.
    • - -
    • For Windows, Cygwin 1.7 or higher is required. The NDK - will not work with Cygwin 1.5 installations.
    • -
    - -

    Android platform compatibility

    - -
      -
    • The native libraries created by the Android NDK can only be used on devices running the - Android 1.5 platform version or later. This is due to toolchain and ABI related changes that - make the native libraries incompatible with 1.0 and 1.1 system images.
    • - -
    • For this reason, you should use native libraries produced with the NDK in applications that - are deployable to devices running the Android 1.5 platform version or later.
    • - -
    • To ensure compatibility, an application using a native library produced with the NDK - must declare a - <uses-sdk> element in its manifest file, with an - android:minSdkVersion attribute value of "3" or higher. For example: -
      -<manifest>
      -  <uses-sdk android:minSdkVersion="3" />
      -  ...
      -</manifest>
      -
      -
    • - -
    • If you use this NDK to create a native library that uses the OpenGL ES APIs, the - application containing the library can be deployed only to devices running the minimum platform - versions described in the table below. To ensure compatibility, make sure that your application - declares the proper android:minSdkVersion attribute value, as given in the - table.
    • - -
    • - - - - - - - - - - - - - - - - - - - - - - - - -
      OpenGL ES Version UsedCompatible Android Platform(s)Required uses-sdk Attribute
      OpenGL ES 1.1Android 1.6 and higherandroid:minSdkVersion="4"
      OpenGL ES 2.0Android 2.0 and higherandroid:minSdkVersion="5"
      - -

      For more information about API Level and its relationship to Android platform versions, - see Android API Levels.

      -
    • - -
    • Additionally, an application using the OpenGL ES APIs should declare a - <uses-feature> element in its manifest, with an - android:glEsVersion attribute that specifies the minimum OpenGl ES version - required by the application. This ensures that Google Play will show your application only - to users whose devices are capable of supporting your application. For example: -
      -<manifest>
      -
      -  <uses-feature android:glEsVersion="0x00020000" />
      -  ...
      -</manifest>
      -
      - -

      For more information, see the <uses-feature> - documentation.

      -
    • - -
    • If you use this NDK to create a native library that uses the API to access Android {@link - android.graphics.Bitmap} pixel buffers or utilizes native activities, the application - containing the library can be deployed only to devices running Android 2.2 (API level 8) or - higher. To ensure compatibility, make sure that your application declares <uses-sdk - android:minSdkVersion="8" /> attribute value in its manifest.
    • -
    diff --git a/docs/html/sdk/oem-usb.jd b/docs/html/sdk/oem-usb.jd deleted file mode 100644 index 88d66dd3a4f8..000000000000 --- a/docs/html/sdk/oem-usb.jd +++ /dev/null @@ -1,324 +0,0 @@ -page.title=OEM USB Drivers -@jd:body - -
    - -
    - -

    If you are developing on Windows and would like to connect an Android-powered device -to test your applications, then you need to install the appropriate USB driver. This document -provides links to the web sites for several original equipment manufacturers (OEMs), -where you can download the appropriate USB driver for your device. However, this list is -not exhaustive for all available Android-powered devices.

    - -

    If you're developing on Mac OS X or Linux, then you probably don't need to install a USB driver. -To start developing with your device, read Using Hardware Devices.

    - -

    Note: If your device is one of the Android Developer Phones -(ADP), a Nexus One, or a Nexus S, then you need -the Google USB Driver, instead of an OEM driver. The Galaxy -Nexus driver, however, is distributed by Samsung -(listed as model SCH-I515).

    - - -

    Installing a USB Driver

    - -

    First, find the appropriate driver for your device from the OEM drivers -table below.

    - -

    Once you've downloaded your USB driver, follow the instructions below to install or upgrade the -driver, based on your version of Windows and whether you're installing for the first time -or upgrading an existing driver.

    - -

    Tip: When you finish the USB driver installation, -see Using Hardware Devices for -other important information about using an Android-powered device for -development.

    - -
      -
    1. Windows 7
    2. -
    3. Windows XP
    4. -
    5. Windows Vista
    6. -
    - - -

    Caution: -You may make changes to android_winusb.inf file found inside -usb_driver\ (for example, to add support for other devices), -however, this will lead to security warnings when you install or upgrade the -driver. Making any other changes to the driver files may break the installation -process.

    - - -

    Windows 7

    - - -

    To install the Android USB driver on Windows 7 for the first time:

    -
      -
    1. Connect your Android-powered device to your computer's USB port.
    2. -
    3. Right-click on Computer from your desktop or Windows Explorer, - and select Manage.
    4. -
    5. Select Devices in the left pane.
    6. -
    7. Locate and expand Other device in the right pane.
    8. -
    9. Right-click the device name (such as Nexus S) and select Update - Driver Software. - This will launch the Hardware Update Wizard.
    10. -
    11. Select Browse my computer for driver software and click - Next.
    12. -
    13. Click Browse and locate the USB driver folder. (The Google USB -Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    14. -
    15. Click Next to install the driver.
    16. -
    - -

    Or, to upgrade an existing Android USB driver on Windows 7 with the new -driver:

    - -
      -
    1. Connect your Android-powered device to your computer's USB port.
    2. -
    3. Right-click on Computer from your desktop or Windows Explorer, - and select Manage.
    4. -
    5. Select Device Manager in the left pane of the Computer Management - window.
    6. -
    7. Locate and expand Android Phone in the right pane.
    8. -
    9. Right-click Android Composite ADB Interface and select Update - Driver. - This will launch the Hardware Update Wizard.
    10. -
    11. Select Install from a list or specific location and click - Next.
    12. -
    13. Select Search for the best driver in these locations; un-check -Search removable media; and check Include this location in the -search.
    14. -
    15. Click Browse and locate the USB driver folder. (The Google USB -Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    16. -
    17. Click Next to upgrade the driver.
    18. -
    - - - - - -

    Windows XP

    - -

    To install the Android USB driver on Windows XP for the first time:

    - -
      -
    1. Connect your Android-powered device to your computer's USB port. Windows - will detect the device and launch the Hardware Update Wizard.
    2. -
    3. Select Install from a list or specific location and click - Next.
    4. -
    5. Select Search for the best driver in these locations; un-check -Search - removable media; and check Include -this location in the search.
    6. -
    7. Click Browse and locate the USB driver folder. (The Google USB -Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    8. -
    9. Click Next to install the driver.
    10. -
    - -

    Or, to upgrade an existing Android USB driver on Windows XP with the new -driver:

    - -
      -
    1. Connect your Android-powered device to your computer's USB port.
    2. -
    3. Right-click on My Computer from your desktop or Windows Explorer, - and select Manage.
    4. -
    5. Select Device Manager in the left pane.
    6. -
    7. Locate and expand Android Phone in the right pane.
    8. -
    9. Right-click Android Composite ADB Interface and select Update - Driver. - This will launch the Hardware Update Wizard.
    10. -
    11. Select Install from a list or specific location and click - Next.
    12. -
    13. Select Search for the best driver in these locations; un-check Search - removable media; and check Include -this location in the search.
    14. -
    15. Click Browse and locate the USB driver folder. (The Google USB -Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    16. -
    17. Click Next to upgrade the driver.
    18. -
    - - - -

    Windows Vista

    - -

    To install the Android USB driver on Windows Vista for the first time:

    - -
      -
    1. Connect your Android-powered device to your computer's USB port. Windows - will detect the device and launch the Found New Hardware wizard.
    2. -
    3. Select Locate and install driver software.
    4. -
    5. Select Don't search online.
    6. -
    7. Select I don't have the disk. Show me other options.
    8. -
    9. Select Browse my computer for driver software.
    10. -
    11. Click Browse and locate the USB driver folder. (The Google USB -Driver is located in {@code <sdk>\extras\google\usb_driver\}.) As long as you specified the -exact location of the - installation package, you may leave Include subfolders checked or - unchecked—it doesn't matter.
    12. -
    13. Click Next. Vista may prompt you to confirm the privilege elevation - required for driver installation. Confirm it.
    14. -
    15. When Vista asks if you'd like to install the Google ADB Interface device, - click Install to install the driver.
    16. -
    - -

    Or, to upgrade an existing Android USB driver on Windows Vista with the new -driver:

    - -
      -
    1. Connect your Android-powered device to your computer's USB port.
    2. -
    3. Right-click on Computer from your desktop or Windows Explorer, - and select Manage.
    4. -
    5. Select Device Manager in the left pane.
    6. -
    7. Locate and expand ADB Interface in the right pane.
    8. -
    9. Right-click on HTC Dream Composite ADB Interface, and select Update - Driver Software.
    10. -
    11. When Vista starts updating the driver, a prompt will ask how you want to - search for the driver - software. Select Browse my computer for driver software.
    12. -
    13. Click Browse and locate the USB driver folder. (The Google USB -Driver is located in {@code <sdk>\extras\google\usb_driver\}.) As long as you specified the -exact location of the - installation package, you may leave Include subfolders checked or - unchecked—it doesn't matter.
    14. -
    15. Click Next. Vista might prompt you to confirm the privilege elevation - required for driver installation. Confirm it.
    16. -
    17. When Vista asks if you'd like to install the Google ADB Interface device, - click Install to upgrade the driver.
    18. -
    - - -

    OEM Drivers

    - -

    Note: If your device is one of the Android Developer Phones -(purchased from the Google Play publisher site), a Nexus One, or a Nexus S, then you need -the Google USB Driver, instead of an OEM driver. The Galaxy -Nexus driver, however, is distributed by Samsung -(listed as model SCH-I515).

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    OEMDriver URL
    Acer http://www.acer.com/worldwide/support/mobile.html -
    alcatel one touchhttp://www.alcatel-mobilephones.com/global/Android-Downloads
    Asushttp://support.asus.com/download/
    - Dell - - http://support.dell.com/support/downloads/index.aspx?c=us&cs=19&l=en&s=dhs&~ck=anavml
    Foxconn http://drivers.cmcs.com.tw/
    - Fujitsu - http://www.fmworld.net/product/phone/sp/android/develop/ -
    - Fujitsu Toshiba - http://www.fmworld.net/product/phone/sp/android/develop/ -
    - Garmin-Asus - https://www.garminasus.com/en_US/support/pcsync/
    Hisensehttp://app.hismarttv.com/dss/resourcecontent.do?method=viewResourceDetail&resourceId=16&type=5
    HTC http://www.htc.com
    Click on the -support tab to select your products/device. Different regions will have different links.
    Huawei http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index
    KT Tech http://www.kttech.co.kr/cscenter/download05.asp for EV-S100 (Take)
    - Kyocera - http://www.kyocera-wireless.com/support/phone_drivers.htm -
    Lenevohttp://developer.lenovomm.com/developer/download.jsp -
    LGE http://www.lg.com/us/mobile-phones/mobile-support/mobile-lg-mobile-phone-support.jsp
    Motorola http://developer.motorola.com/docstools/USB_Drivers/
    Pantech http://www.isky.co.kr/cs/software/software.sky?fromUrl=index
    Pegatron http://www.pegatroncorp.com/download/New_Duke_PC_Driver_0705.zip (ZIP download)
    Samsung http://www.samsung.com/us/support/downloads
    Sharp http://k-tai.sharp.co.jp/support/
    SK Telesys http://www.sk-w.com/service/wDownload/wDownload.jsp
    Sony Ericsson http://developer.sonyericsson.com/wportal/devworld/search-downloads/driver?cc=gb&lc=en
    Teleepoch http://www.teleepoch.com/android.html
    Yulong Coolpad http://www.yulong.com/product/product/product/downloadList.html#downListUL
    ZTE http://support.zte.com.cn/support/news/NewsDetail.aspx?newsId=1000442
    diff --git a/docs/html/sdk/older_releases.jd b/docs/html/sdk/older_releases.jd index 870ff04df37d..bb274b67aa7a 100644 --- a/docs/html/sdk/older_releases.jd +++ b/docs/html/sdk/older_releases.jd @@ -15,7 +15,7 @@ development and testing.

    If you already have an Android SDK for platform version 1.6 or newer, then you do not need to install a new SDK—especially not one from this page. You should install older platforms as components of your existing SDK. -See Adding SDK Components.

    +See Exploring the SDK.

    diff --git a/docs/html/sdk/preview/features.jd b/docs/html/sdk/preview/features.jd deleted file mode 100644 index d7ecc47ce8f4..000000000000 --- a/docs/html/sdk/preview/features.jd +++ /dev/null @@ -1,8 +0,0 @@ -@jd:body - - - -

    You should have already been redirected by your browser. Please go to the -Android 3.0 Platform.

    \ No newline at end of file diff --git a/docs/html/sdk/preview/index.jd b/docs/html/sdk/preview/index.jd deleted file mode 100644 index ed8f7e0d5522..000000000000 --- a/docs/html/sdk/preview/index.jd +++ /dev/null @@ -1,2 +0,0 @@ -sdk.redirect=true -@jd:body diff --git a/docs/html/sdk/preview/installing.jd b/docs/html/sdk/preview/installing.jd deleted file mode 100644 index 94c6f2f9ab95..000000000000 --- a/docs/html/sdk/preview/installing.jd +++ /dev/null @@ -1,8 +0,0 @@ -@jd:body - - - -

    You should have already been redirected by your browser. Please go to -Installing the SDK.

    \ No newline at end of file diff --git a/docs/html/sdk/preview/requirements.jd b/docs/html/sdk/preview/requirements.jd deleted file mode 100644 index b5aed80ef644..000000000000 --- a/docs/html/sdk/preview/requirements.jd +++ /dev/null @@ -1,8 +0,0 @@ -@jd:body - - - -

    You should have already been redirected by your browser. Please go to the -SDK System Requirements.

    \ No newline at end of file diff --git a/docs/html/sdk/preview/upgrading.jd b/docs/html/sdk/preview/upgrading.jd deleted file mode 100644 index 1c53bdbfe07f..000000000000 --- a/docs/html/sdk/preview/upgrading.jd +++ /dev/null @@ -1,8 +0,0 @@ -@jd:body - - - -

    You should have already been redirected by your browser. Please go to -the Android SDK.

    \ No newline at end of file diff --git a/docs/html/sdk/requirements.jd b/docs/html/sdk/requirements.jd deleted file mode 100644 index c76e8c8b82a3..000000000000 --- a/docs/html/sdk/requirements.jd +++ /dev/null @@ -1,114 +0,0 @@ -page.title=System Requirements -@jd:body - -

    The sections below describe the system and software requirements for developing -Android applications using the Android SDK.

    - -

    Supported Operating Systems

    -
      -
    • Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
    • -
    • Mac OS X 10.5.8 or later (x86 only)
    • -
    • Linux (tested on Ubuntu Linux, Lucid Lynx) -
        -
      • GNU C Library (glibc) 2.7 or later is required.
      • -
      • On Ubuntu Linux, version 8.04 or later is required.
      • -
      • 64-bit distributions must be capable of running 32-bit applications. - For information about how to add support for 32-bit applications, see - the Ubuntu Linux - installation notes.
      • -
      -
    • -
    - -

    Supported Development Environments

    - -

    Eclipse IDE

    -
      -
    • Eclipse 3.6.2 (Helios) or greater -

      Note: Eclipse 3.5 (Galileo) is no longer -supported with the latest version of ADT.

    • -
    • Eclipse JDT plugin (included -in most Eclipse IDE packages)
    • -
    • If you need to install or update Eclipse, you can download it from http://www.eclipse.org/downloads/. - -

      Several types of Eclipse packages are available for each platform. For -developing Android applications, we recommend that you install one of these -packages:

      -
        -
      • Eclipse IDE for Java Developers
      • -
      • Eclipse Classic
      • -
      • Eclipse IDE for Java EE Developers
      • -
      -
    • -
    • JDK 6 - (JRE alone is not sufficient)
    • -
    • Android Development Tools plugin -(recommended)
    • -
    • Not compatible with Gnu Compiler for Java (gcj)
    • -
    - - -

    Other development environments or IDEs

    -
      -
    • JDK 6 - (JRE alone is not sufficient)
    • -
    • Apache Ant 1.8 or later
    • -
    • Not compatible with Gnu Compiler for Java (gcj)
    • -
    - - - -

    Note: If JDK is already installed on your development computer, please take a moment to make sure that it meets the version requirements listed above. In -particular, note that some Linux distributions may include JDK 1.4 or Gnu Compiler for Java, both of which are not supported for Android development.

    - -

    Hardware requirements

    - -

    The Android SDK requires disk storage for all of the components that you choose to install. The table below provides a rough idea of the disk-space requirements to expect, based on the components that you plan to use.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Component typeApproximate sizeComments
    SDK Tools35 MBRequired.
    SDK Platform-tools6 MBRequired.
    Android platform (each)150 MBAt least one platform is required.
    SDK Add-on (each)100 MBOptional.
    USB Driver for Windows10 MBOptional. For Windows only.
    Samples (per platform)10MOptional.
    Offline documentation250 MBOptional.
    - -

    Note that the disk-space requirements above are in addition to those of the Eclipse IDE, JDK, or other prerequisite tools that you may need to install on your development computer.

    - - diff --git a/docs/html/sdk/sdk_toc.cs b/docs/html/sdk/sdk_toc.cs deleted file mode 100644 index e994d9516448..000000000000 --- a/docs/html/sdk/sdk_toc.cs +++ /dev/null @@ -1,228 +0,0 @@ - - - - - diff --git a/docs/html/sdk/terms.jd b/docs/html/sdk/terms.jd deleted file mode 100644 index 614a438ef17c..000000000000 --- a/docs/html/sdk/terms.jd +++ /dev/null @@ -1,207 +0,0 @@ -page.title=Terms and Conditions -hide_license_footer=true -@jd:body - -

    This is the Android Software Development Kit License Agreement.

    - -

    - 1. Introduction -

    -

    - 1.1 The Android Software Development Kit (referred to in this License Agreement as the "SDK" and specifically including the Android system files, packaged APIs, and Google APIs add-ons) is licensed to you subject to the terms of this License Agreement. This License Agreement forms a legally binding contract between you and Google in relation to your use of the SDK. - -

    -

    - 1.2 "Google" means Google Inc., a Delaware corporation with principal place of business at 1600 Amphitheatre Parkway, Mountain View, CA 94043, United States. -

    -

    - 2. Accepting this License Agreement -

    -

    - 2.1 In order to use the SDK, you must first agree to this License Agreement. You may not use the SDK if you do not accept this License Agreement. -

    -

    - 2.2 You can accept this License Agreement by: -

    -

    - (A) clicking to accept or agree to this License Agreement, where this option is made available to you; or -

    -

    - (B) by actually using the SDK. In this case, you agree that use of the SDK constitutes acceptance of the Licensing Agreement from that point onwards. -

    -

    - 2.3 You may not use the SDK and may not accept the Licensing Agreement if you are a person barred from receiving the SDK under the laws of the United States or other countries including the country in which you are resident or from which you use the SDK. -

    -

    - 2.4 If you are agreeing to be bound by this License Agreement on behalf of your employer or other entity, you represent and warrant that you have full legal authority to bind your employer or such entity to this License Agreement. If you do not have the requisite authority, you may not accept the Licensing Agreement or use the SDK on behalf of your employer or other entity. -

    -

    - 3. SDK License from Google -

    -

    - 3.1 Subject to the terms of this License Agreement, Google grants you a limited, worldwide, royalty-free, non- assignable and non-exclusive license to use the SDK solely to develop applications to run on the Android platform. -

    -

    - 3.2 You agree that Google or third parties own all legal right, title and interest in and to the SDK, including any Intellectual Property Rights that subsist in the SDK. "Intellectual Property Rights" means any and all rights under patent law, copyright law, trade secret law, trademark law, and any and all other proprietary rights. Google reserves all rights not expressly granted to you. - -

    -

    - 3.3 Except to the extent required by applicable third party licenses, you may not copy (except for backup purposes), modify, adapt, redistribute, decompile, reverse engineer, disassemble, or create derivative works of the SDK or any part of the SDK. Except to the extent required by applicable third party licenses, you may not load any part of the SDK onto a mobile handset or any other hardware device except a personal computer, combine any part of the SDK with other software, or distribute any software or device incorporating a part of the SDK. -

    -

    - 3.4 Use, reproduction and distribution of components of the SDK licensed under an open source software license are governed solely by the terms of that open source software license and not this License Agreement. -

    -

    - 3.5 You agree that the form and nature of the SDK that Google provides may change without prior notice to you and that future versions of the SDK may be incompatible with applications developed on previous versions of the SDK. You agree that Google may stop (permanently or temporarily) providing the SDK (or any features within the SDK) to you or to users generally at Google's sole discretion, without prior notice to you. -

    -

    - 3.6 Nothing in this License Agreement gives you a right to use any of Google's trade names, trademarks, service marks, logos, domain names, or other distinctive brand features. -

    -

    - 3.7 You agree that you will not remove, obscure, or alter any proprietary rights notices (including copyright and trademark notices) that may be affixed to or contained within the SDK. -

    -

    - 4. Use of the SDK by You -

    -

    - 4.1 Google agrees that it obtains no right, title or interest from you (or your licensors) under this License Agreement in or to any software applications that you develop using the SDK, including any intellectual property rights that subsist in those applications. -

    -

    - 4.2 You agree to use the SDK and write applications only for purposes that are permitted by (a) this License Agreement and (b) any applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the export of data or software to and from the United States or other relevant countries). -

    -

    - 4.3 You agree that if you use the SDK to develop applications for general public users, you will protect the privacy and legal rights of those users. If the users provide you with user names, passwords, or other login information or personal information, your must make the users aware that the information will be available to your application, and you must provide legally adequate privacy notice and protection for those users. If your application stores personal or sensitive information provided by users, it must do so securely. If the user provides your application with Google Account information, your application may only use that information to access the user's Google Account when, and for the limited purposes for which, the user has given you permission to do so. -

    -

    - 4.4 You agree that you will not engage in any activity with the SDK, including the development or distribution of an application, that interferes with, disrupts, damages, or accesses in an unauthorized manner the servers, networks, or other properties or services of any third party including, but not limited to, Google or any mobile communications carrier. -

    -

    - 4.5 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any data, content, or resources that you create, transmit or display through the Android platform and/or applications for the Android platform, and for the consequences of your actions (including any loss or damage which Google may suffer) by doing so. -

    -

    - 4.6 You agree that you are solely responsible for (and that Google has no responsibility to you or to any third party for) any breach of your obligations under this License Agreement, any applicable third party contract or Terms of Service, or any applicable law or regulation, and for the consequences (including any loss or damage which Google or any third party may suffer) of any such breach. -

    -

    - 5. Your Developer Credentials -

    -

    - 5.1 You agree that you are responsible for maintaining the confidentiality of any developer credentials that may be issued to you by Google or which you may choose yourself and that you will be solely responsible for all applications that are developed under your developer credentials. -

    -

    - 6. Privacy and Information -

    -

    - 6.1 In order to continually innovate and improve the SDK, Google may collect certain usage statistics from the software including but not limited to a unique identifier, associated IP address, version number of the software, and information on which tools and/or services in the SDK are being used and how they are being used. Before any of this information is collected, the SDK will notify you and seek your consent. If you withhold consent, the information will not be collected. -

    -

    - 6.2 The data collected is examined in the aggregate to improve the SDK and is maintained in accordance with Google's Privacy Policy. -

    -

    - 7. Third Party Applications for the Android Platform -

    -

    - 7.1 If you use the SDK to run applications developed by a third party or that access data, content or resources provided by a third party, you agree that Google is not responsible for those applications, data, content, or resources. You understand that all data, content or resources which you may access through such third party applications are the sole responsibility of the person from which they originated and that Google is not liable for any loss or damage that you may experience as a result of the use or access of any of those third party applications, data, content, or resources. -

    -

    - 7.2 You should be aware the data, content, and resources presented to you through such a third party application may be protected by intellectual property rights which are owned by the providers (or by other persons or companies on their behalf). You may not modify, rent, lease, loan, sell, distribute or create derivative works based on these data, content, or resources (either in whole or in part) unless you have been specifically given permission to do so by the relevant owners. -

    -

    - 7.3 You acknowledge that your use of such third party applications, data, content, or resources may be subject to separate terms between you and the relevant third party. In that case, this License Agreement does not affect your legal relationship with these third parties. -

    -

    - 8. Using Android APIs -

    -

    - 8.1 Google Data APIs -

    -

    - 8.1.1 If you use any API to retrieve data from Google, you acknowledge that the data may be protected by intellectual property rights which are owned by Google or those parties that provide the data (or by other persons or companies on their behalf). Your use of any such API may be subject to additional Terms of Service. You may not modify, rent, lease, loan, sell, distribute or create derivative works based on this data (either in whole or in part) unless allowed by the relevant Terms of Service. -

    -

    - 8.1.2 If you use any API to retrieve a user's data from Google, you acknowledge and agree that you shall retrieve data only with the user's explicit consent and only when, and for the limited purposes for which, the user has given you permission to do so. - -

    -

    - 9. Terminating this License Agreement -

    -

    - 9.1 This License Agreement will continue to apply until terminated by either you or Google as set out below. -

    -

    - 9.2 If you want to terminate this License Agreement, you may do so by ceasing your use of the SDK and any relevant developer credentials. -

    -

    - 9.3 Google may at any time, terminate this License Agreement with you if: -

    -

    - (A) you have breached any provision of this License Agreement; or -

    -

    - (B) Google is required to do so by law; or -

    -

    - (C) the partner with whom Google offered certain parts of SDK (such as APIs) to you has terminated its relationship with Google or ceased to offer certain parts of the SDK to you; or -

    -

    - (D) Google decides to no longer providing the SDK or certain parts of the SDK to users in the country in which you are resident or from which you use the service, or the provision of the SDK or certain SDK services to you by Google is, in Google's sole discretion, no longer commercially viable. -

    -

    - 9.4 When this License Agreement comes to an end, all of the legal rights, obligations and liabilities that you and Google have benefited from, been subject to (or which have accrued over time whilst this License Agreement has been in force) or which are expressed to continue indefinitely, shall be unaffected by this cessation, and the provisions of paragraph 14.7 shall continue to apply to such rights, obligations and liabilities indefinitely. -

    -

    - 10. DISCLAIMER OF WARRANTIES -

    -

    - 10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE SDK IS AT YOUR SOLE RISK AND THAT THE SDK IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND FROM GOOGLE. -

    -

    - 10.2 YOUR USE OF THE SDK AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE SDK IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. -

    -

    - 10.3 GOOGLE FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. -

    -

    - 11. LIMITATION OF LIABILITY -

    -

    - 11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT GOOGLE, ITS SUBSIDIARIES AND AFFILIATES, AND ITS LICENSORS SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANY LOSS OF DATA, WHETHER OR NOT GOOGLE OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEEN AWARE OF THE POSSIBILITY OF ANY SUCH LOSSES ARISING. -

    -

    - 12. Indemnification -

    -

    - 12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold harmless Google, its affiliates and their respective directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or accruing from (a) your use of the SDK, (b) any application you develop on the SDK that infringes any copyright, trademark, trade secret, trade dress, patent or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy, and (c) any non-compliance by you with this License Agreement. -

    -

    - 13. Changes to the License Agreement -

    -

    - 13.1 Google may make changes to the License Agreement as it distributes new versions of the SDK. When these changes are made, Google will make a new version of the License Agreement available on the website where the SDK is made available. -

    -

    - 14. General Legal Terms -

    -

    - 14.1 This License Agreement constitute the whole legal agreement between you and Google and govern your use of the SDK (excluding any services which Google may provide to you under a separate written agreement), and completely replace any prior agreements between you and Google in relation to the SDK. -

    -

    - 14.2 You agree that if Google does not exercise or enforce any legal right or remedy which is contained in this License Agreement (or which Google has the benefit of under any applicable law), this will not be taken to be a formal waiver of Google's rights and that those rights or remedies will still be available to Google. -

    -

    - 14.3 If any court of law, having the jurisdiction to decide on this matter, rules that any provision of this License Agreement is invalid, then that provision will be removed from this License Agreement without affecting the rest of this License Agreement. The remaining provisions of this License Agreement will continue to be valid and enforceable. -

    -

    - 14.4 You acknowledge and agree that each member of the group of companies of which Google is the parent shall be third party beneficiaries to this License Agreement and that such other companies shall be entitled to directly enforce, and rely upon, any provision of this License Agreement that confers a benefit on (or rights in favor of) them. Other than this, no other person or company shall be third party beneficiaries to this License Agreement. -

    -

    - 14.5 EXPORT RESTRICTIONS. THE SDK IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE SDK. THESE LAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END USE. -

    -

    - 14.6 The rights granted in this License Agreement may not be assigned or transferred by either you or Google without the prior written approval of the other party. Neither you nor Google shall be permitted to delegate their responsibilities or obligations under this License Agreement without the prior written approval of the other party. -

    -

    - 14.7 This License Agreement, and your relationship with Google under this License Agreement, shall be governed by the laws of the State of California without regard to its conflict of laws provisions. You and Google agree to submit to the exclusive jurisdiction of the courts located within the county of Santa Clara, California to resolve any legal matter arising from this License Agreement. Notwithstanding this, you agree that Google shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction. -

    -

    - April 10, 2009 -

    diff --git a/docs/html/sdk/terms_body.html b/docs/html/sdk/terms_body.html deleted file mode 100644 index 8c55b37bc61d..000000000000 --- a/docs/html/sdk/terms_body.html +++ /dev/null @@ -1,336 +0,0 @@ - - -

    This is the Android Software Development Kit License Agreement.

    - -

    - 1. Introduction -

    -

    - 1.1 The Android Software Development Kit (referred to in this License Agreement as the "SDK" -and specifically including the Android system files, packaged APIs, and Google APIs add-ons) is -licensed to you subject to the terms of this License Agreement. This License Agreement forms a -legally binding contract between you and Google in relation to your use of the SDK. - -

    -

    - 1.2 "Google" means Google Inc., a Delaware corporation with principal place of business at -1600 Amphitheatre Parkway, Mountain View, CA 94043, United States. -

    -

    - 2. Accepting this License Agreement -

    -

    - 2.1 In order to use the SDK, you must first agree to this License Agreement. You may not use -the SDK if you do not accept this License Agreement. -

    -

    - 2.2 You can accept this License Agreement by: -

    -

    - (A) clicking to accept or agree to this License Agreement, where this option is made -available to you; or -

    -

    - (B) by actually using the SDK. In this case, you agree that use of the SDK constitutes -acceptance of the Licensing Agreement from that point onwards. -

    -

    - 2.3 You may not use the SDK and may not accept the Licensing Agreement if you are a person -barred from receiving the SDK under the laws of the United States or other countries including the -country in which you are resident or from which you use the SDK. -

    -

    - 2.4 If you are agreeing to be bound by this License Agreement on behalf of your employer or -other entity, you represent and warrant that you have full legal authority to bind your employer or -such entity to this License Agreement. If you do not have the requisite authority, you may not -accept the Licensing Agreement or use the SDK on behalf of your employer or other entity. -

    -

    - 3. SDK License from Google -

    -

    - 3.1 Subject to the terms of this License Agreement, Google grants you a limited, worldwide, -royalty-free, non- assignable and non-exclusive license to use the SDK solely to develop -applications to run on the Android platform. -

    -

    - 3.2 You agree that Google or third parties own all legal right, title and interest in and to -the SDK, including any Intellectual Property Rights that subsist in the SDK. "Intellectual Property -Rights" means any and all rights under patent law, copyright law, trade secret law, trademark law, -and any and all other proprietary rights. Google reserves all rights not expressly granted to you. - -

    -

    - 3.3 Except to the extent required by applicable third party licenses, you may not copy -(except for backup purposes), modify, adapt, redistribute, decompile, reverse engineer, disassemble, -or create derivative works of the SDK or any part of the SDK. Except to the extent required by -applicable third party licenses, you may not load any part of the SDK onto a mobile handset or any -other hardware device except a personal computer, combine any part of the SDK with other software, -or distribute any software or device incorporating a part of the SDK. -

    -

    - 3.4 Use, reproduction and distribution of components of the SDK licensed under an open -source software license are governed solely by the terms of that open source software license and -not this License Agreement. -

    -

    - 3.5 You agree that the form and nature of the SDK that Google provides may change without -prior notice to you and that future versions of the SDK may be incompatible with applications -developed on previous versions of the SDK. You agree that Google may stop (permanently or -temporarily) providing the SDK (or any features within the SDK) to you or to users generally at -Google's sole discretion, without prior notice to you. -

    -

    - 3.6 Nothing in this License Agreement gives you a right to use any of Google's trade names, -trademarks, service marks, logos, domain names, or other distinctive brand features. -

    -

    - 3.7 You agree that you will not remove, obscure, or alter any proprietary rights notices -(including copyright and trademark notices) that may be affixed to or contained within the SDK. -

    -

    - 4. Use of the SDK by You -

    -

    - 4.1 Google agrees that it obtains no right, title or interest from you (or your licensors) -under this License Agreement in or to any software applications that you develop using the SDK, -including any intellectual property rights that subsist in those applications. -

    -

    - 4.2 You agree to use the SDK and write applications only for purposes that are permitted by -(a) this License Agreement and (b) any applicable law, regulation or generally accepted practices or -guidelines in the relevant jurisdictions (including any laws regarding the export of data or -software to and from the United States or other relevant countries). -

    -

    - 4.3 You agree that if you use the SDK to develop applications for general public users, you -will protect the privacy and legal rights of those users. If the users provide you with user names, -passwords, or other login information or personal information, your must make the users aware that -the information will be available to your application, and you must provide legally adequate privacy -notice and protection for those users. If your application stores personal or sensitive information -provided by users, it must do so securely. If the user provides your application with Google Account -information, your application may only use that information to access the user's Google Account -when, and for the limited purposes for which, the user has given you permission to do so. -

    -

    - 4.4 You agree that you will not engage in any activity with the SDK, including the -development or distribution of an application, that interferes with, disrupts, damages, or accesses -in an unauthorized manner the servers, networks, or other properties or services of any third party -including, but not limited to, Google or any mobile communications carrier. -

    -

    - 4.5 You agree that you are solely responsible for (and that Google has no responsibility to -you or to any third party for) any data, content, or resources that you create, transmit or display -through the Android platform and/or applications for the Android platform, and for the consequences -of your actions (including any loss or damage which Google may suffer) by doing so. -

    -

    - 4.6 You agree that you are solely responsible for (and that Google has no responsibility to -you or to any third party for) any breach of your obligations under this License Agreement, any -applicable third party contract or Terms of Service, or any applicable law or regulation, and for -the consequences (including any loss or damage which Google or any third party may suffer) of any -such breach. -

    -

    - 5. Your Developer Credentials -

    -

    - 5.1 You agree that you are responsible for maintaining the confidentiality of any developer -credentials that may be issued to you by Google or which you may choose yourself and that you will -be solely responsible for all applications that are developed under your developer credentials. -

    -

    - 6. Privacy and Information -

    -

    - 6.1 In order to continually innovate and improve the SDK, Google may collect certain usage -statistics from the software including but not limited to a unique identifier, associated IP -address, version number of the software, and information on which tools and/or services in the SDK -are being used and how they are being used. Before any of this information is collected, the SDK -will notify you and seek your consent. If you withhold consent, the information will not be -collected. -

    -

    - 6.2 The data collected is examined in the aggregate to improve the SDK and is maintained in -accordance with Google's Privacy Policy. -

    -

    - 7. Third Party Applications for the Android Platform -

    -

    - 7.1 If you use the SDK to run applications developed by a third party or that access data, -content or resources provided by a third party, you agree that Google is not responsible for those -applications, data, content, or resources. You understand that all data, content or resources which -you may access through such third party applications are the sole responsibility of the person from -which they originated and that Google is not liable for any loss or damage that you may experience -as a result of the use or access of any of those third party applications, data, content, or -resources. -

    -

    - 7.2 You should be aware the data, content, and resources presented to you through such a -third party application may be protected by intellectual property rights which are owned by the -providers (or by other persons or companies on their behalf). You may not modify, rent, lease, loan, -sell, distribute or create derivative works based on these data, content, or resources (either in -whole or in part) unless you have been specifically given permission to do so by the relevant -owners. -

    -

    - 7.3 You acknowledge that your use of such third party applications, data, content, or -resources may be subject to separate terms between you and the relevant third party. In that case, -this License Agreement does not affect your legal relationship with these third parties. -

    -

    - 8. Using Android APIs -

    -

    - 8.1 Google Data APIs -

    -

    - 8.1.1 If you use any API to retrieve data from Google, you acknowledge that the data may be -protected by intellectual property rights which are owned by Google or those parties that provide -the data (or by other persons or companies on their behalf). Your use of any such API may be subject -to additional Terms of Service. You may not modify, rent, lease, loan, sell, distribute or create -derivative works based on this data (either in whole or in part) unless allowed by the relevant -Terms of Service. -

    -

    - 8.1.2 If you use any API to retrieve a user's data from Google, you acknowledge and agree -that you shall retrieve data only with the user's explicit consent and only when, and for the -limited purposes for which, the user has given you permission to do so. - -

    -

    - 9. Terminating this License Agreement -

    -

    - 9.1 This License Agreement will continue to apply until terminated by either you or Google -as set out below. -

    -

    - 9.2 If you want to terminate this License Agreement, you may do so by ceasing your use of -the SDK and any relevant developer credentials. -

    -

    - 9.3 Google may at any time, terminate this License Agreement with you if: -

    -

    - (A) you have breached any provision of this License Agreement; or -

    -

    - (B) Google is required to do so by law; or -

    -

    - (C) the partner with whom Google offered certain parts of SDK (such as APIs) to you has -terminated its relationship with Google or ceased to offer certain parts of the SDK to you; or -

    -

    - (D) Google decides to no longer providing the SDK or certain parts of the SDK to users in -the country in which you are resident or from which you use the service, or the provision of the SDK -or certain SDK services to you by Google is, in Google's sole discretion, no longer commercially -viable. -

    -

    - 9.4 When this License Agreement comes to an end, all of the legal rights, obligations and -liabilities that you and Google have benefited from, been subject to (or which have accrued over -time whilst this License Agreement has been in force) or which are expressed to continue -indefinitely, shall be unaffected by this cessation, and the provisions of paragraph 14.7 shall -continue to apply to such rights, obligations and liabilities indefinitely. -

    -

    - 10. DISCLAIMER OF WARRANTIES -

    -

    - 10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE SDK IS AT YOUR SOLE RISK AND -THAT THE SDK IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND FROM GOOGLE. -

    -

    - 10.2 YOUR USE OF THE SDK AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE -OF THE SDK IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR -COMPUTER SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. -

    -

    - 10.3 GOOGLE FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER -EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. -

    -

    - 11. LIMITATION OF LIABILITY -

    -

    - 11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT GOOGLE, ITS SUBSIDIARIES AND AFFILIATES, AND -ITS LICENSORS SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANY -LOSS OF DATA, WHETHER OR NOT GOOGLE OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEEN -AWARE OF THE POSSIBILITY OF ANY SUCH LOSSES ARISING. -

    -

    - 12. Indemnification -

    -

    - 12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold -harmless Google, its affiliates and their respective directors, officers, employees and agents from -and against any and all claims, actions, suits or proceedings, as well as any and all losses, -liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or -accruing from (a) your use of the SDK, (b) any application you develop on the SDK that infringes any -copyright, trademark, trade secret, trade dress, patent or other intellectual property right of any -person or defames any person or violates their rights of publicity or privacy, and (c) any -non-compliance by you with this License Agreement. -

    -

    - 13. Changes to the License Agreement -

    -

    - 13.1 Google may make changes to the License Agreement as it distributes new versions of the -SDK. When these changes are made, Google will make a new version of the License Agreement available -on the website where the SDK is made available. -

    -

    - 14. General Legal Terms -

    -

    - 14.1 This License Agreement constitute the whole legal agreement between you and Google and -govern your use of the SDK (excluding any services which Google may provide to you under a separate -written agreement), and completely replace any prior agreements between you and Google in relation -to the SDK. -

    -

    - 14.2 You agree that if Google does not exercise or enforce any legal right or remedy which -is contained in this License Agreement (or which Google has the benefit of under any applicable -law), this will not be taken to be a formal waiver of Google's rights and that those rights or -remedies will still be available to Google. -

    -

    - 14.3 If any court of law, having the jurisdiction to decide on this matter, rules that any -provision of this License Agreement is invalid, then that provision will be removed from this -License Agreement without affecting the rest of this License Agreement. The remaining provisions of -this License Agreement will continue to be valid and enforceable. -

    -

    - 14.4 You acknowledge and agree that each member of the group of companies of which Google is -the parent shall be third party beneficiaries to this License Agreement and that such other -companies shall be entitled to directly enforce, and rely upon, any provision of this License -Agreement that confers a benefit on (or rights in favor of) them. Other than this, no other person -or company shall be third party beneficiaries to this License Agreement. -

    -

    - 14.5 EXPORT RESTRICTIONS. THE SDK IS SUBJECT TO UNITED STATES EXPORT LAWS AND REGULATIONS. -YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND REGULATIONS THAT APPLY TO THE -SDK. THESE LAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END USE. -

    -

    - 14.6 The rights granted in this License Agreement may not be assigned or transferred by -either you or Google without the prior written approval of the other party. Neither you nor Google -shall be permitted to delegate their responsibilities or obligations under this License Agreement -without the prior written approval of the other party. -

    -

    - 14.7 This License Agreement, and your relationship with Google under this License Agreement, -shall be governed by the laws of the State of California without regard to its conflict of laws -provisions. You and Google agree to submit to the exclusive jurisdiction of the courts located -within the county of Santa Clara, California to resolve any legal matter arising from this License -Agreement. Notwithstanding this, you agree that Google shall still be allowed to apply for -injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction. -

    -

    - April 10, 2009 -

    \ No newline at end of file diff --git a/docs/html/sdk/tools-notes.jd b/docs/html/sdk/tools-notes.jd deleted file mode 100644 index 062f8f1b75c7..000000000000 --- a/docs/html/sdk/tools-notes.jd +++ /dev/null @@ -1,857 +0,0 @@ -page.title=SDK Tools -@jd:body - -

    SDK Tools is a downloadable component for the Android SDK. It includes the -complete set of development and debugging tools for the Android SDK.

    - -

    If you are new to the Android SDK, the SDK starter package installs the -latest revision of the SDK Tools in the <sdk>/tools directory.

    - -

    If you are already using the SDK and you want to update to the latest version -of the SDK Tools, use the Android SDK Manager to get the -update, rather than downloading a new SDK starter package. For more information -about how to update, see Updating SDK -Components.

    - - -

    Revisions

    - -

    The sections below provide notes about successive releases of -the SDK Tools, as denoted by revision number. To determine what revision of the SDK -Tools you are using, refer to the "Installed Packages" listing in the Android SDK Manager.

    - -

    For a summary of all known issues in SDK Tools, see http://tools.android.com/knownissues.

    - - - - -
    - - - SDK Tools, Revision 19 (April 2012) - -
    -

    Note: This update of SDK Tools is only available through -the Android SDK Manager. Use this tool to -download and install this update.

    - -
    -
    Dependencies:
    -
    -
      -
    • Android SDK Platform-tools revision 9 or later.
    • -
    • If you are developing in Eclipse with ADT, note that the SDK Tools r19 is designed for - use with ADT 18.0.0 and later. If you haven't already, we highly recommend updating your - ADT Plugin to 18.0.0.
    • -
    • If you are developing outside Eclipse, you must have - Apache Ant 1.8 or later.
    • -
    -
    -
    Bug fixes:
    -
    -
      -
    • Fixed an issue that prevented some developers from running the emulator with GPU -acceleration.
    • -
    -
    -
    -
    -
    - -
    - - - SDK Tools, Revision 18 (April 2012) - -
    -

    Important: To download the new Android - 4.0 system components from the Android SDK Manager, you must first update the - SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, - the Android 4.0 system components will not be available for download.

    - -
    -
    Dependencies:
    -
    -
      -
    • Android SDK Platform-tools revision 9 or later.
    • -
    • If you are developing in Eclipse with ADT, note that the SDK Tools r18 is designed for - use with ADT 18.0.0 and later. If you haven't already, we highly recommend updating your - ADT Plugin to 18.0.0.
    • -
    • If you are developing outside Eclipse, you must have - Apache Ant 1.8 or later.
    • -
    -
    -
    General notes:
    -
    -
      -
    • Updated the SdkController app to encapsulate both sensor and multitouch emulation - functionality.
    • -
    -
    -
    Bug fixes:
    -
    -
      -
    • Fixed Ant issues where some jar libraries in the {@code libs/} folder are not picked up -in some cases.
    • -
    -
    -
    -
    -
    - -
    - - - SDK Tools, Revision 17 (March 2012) - -
    -

    Important: To download the new Android - 4.0 system components from the Android SDK Manager, you must first update the - SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, - the Android 4.0 system components will not be available for download.

    - -
    -
    Dependencies:
    -
    -
      -
    • Android SDK Platform-tools revision 9 or later.
    • -
    • If you are developing in Eclipse with ADT, note that the SDK Tools r17 is designed for - use with ADT 17.0.0 and later. If you haven't already, we highly recommend updating your - ADT Plugin to 17.0.0.
    • -
    • If you are developing outside Eclipse, you must have - Apache Ant 1.8 or later.
    • -
    -
    -
    General notes:
    -
    -
      -
    • Emulator -
        -
      • Added support for hardware accelerated graphics rendering. This feature requires an -API Level 15, Revision 3 or later system image. -(more info) -
      • -
      • Added support for running Android x86 system images in virtualization mode on -Windows and Mac OS X. -(more info) -

        Note: Use the Android SDK Manager to download and -install x86 system images. Android x86 system images are not available for all API levels.

        -
      • -
      • Added experimental support for multi-touch input by enabing the emulator to receive - touch input from a USB-tethered physical Android device. - (more info)
      • -
      -
    • -
    • Added viewing of live detailed network usage of an app in DDMS. (more info)
    • -
    • ProGuard -
        -
      • Updated the bundled ProGuard tool to version 4.7. In addition to many new features, -this update fixes the {@code Conversion to Dalvik format failed with error 1} error some users have -experienced.
      • -
      • Updated the default {@code proguard.cfg} file with better default flags for - Android.
      • -
      • Split the ProGuard configuration file has been in half, with project specific flags -kept in project and the generic Android flags distributed (and updated) with the tools -themselves.
      • -
      -
    • -
    • Build -
        -
      • Added a feature that allows you to run some code only in debug mode. Builds now -generate a class called {@code BuildConfig} containing a {@code DEBUG} constant that is -automatically set according to your build type. You can check the ({@code BuildConfig.DEBUG}) -constant in your code to run debug-only functions.
      • -
      • Fixed issue when a project and its libraries include the same jar file in their libs - folder. (more - info)
      • -
      • Added support for custom views with custom attributes in libraries. Layouts using -custom attributes must use the namespace URI {@code http://schemas.android.com/apk/res-auto} instead -of the URI that includes the app package name. This URI is replaced with the app specific one at -build time.
      • -
      -
    • -
    • Lint -
        -
      • Updated Lint to check Android application code. Lint rules which previously -performed pattern based searches in the application code (such as the unused resource check) have -been rewritten to use the more accurate Java-style parse trees.
      • -
      • Added support for checking library projects. This change means that rules such as -the unused resource check properly handle resources declared in a library project and referenced in -a downstream project.
      • -
      • Added ability to suppress Lint warnings in Java code with the new -{@code @SuppressLint} annotation, and in XML files with the new tools: namespace and -ignore attribute. (more info)
      • -
      • New Lint checks: -
          -
        • Added check for Android API calls that require a version of Android higher than - the minimum supported version. You can use the new {@code @TargetApi} annotation - to suppress warnings when the code is wrapped in a system version condition. - (more info)
        • -
        • Added over 20 new Lint rules, including checks for - performance, - XML layouts, manifest and file handling.
        • -
        -
      • -
      -
    • -
    -
    -
    -
    -
    - -
    - - - SDK Tools, Revision 16 (December 2011) - -
    -

    Important: To download the new Android - 4.0 system components from the Android SDK Manager, you must first update the - SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, - the Android 4.0 system components will not be available for download.

    - -
    -
    Dependencies:
    -
    -
      -
    • Android SDK Platform-tools revision 9 or later.
    • -
    • If you are developing in Eclipse with ADT, note that the SDK Tools r16 is designed for use - with ADT 16.0.0 and later. If you haven't already, we highly recommend updating your - ADT Plugin to 16.0.0.
    • -
    • If you are developing outside Eclipse, you must have Apache - Ant 1.8 or later.
    • -
    -
    -
    General notes:
    -
    -
      -
    • Added Lint tools to detect common errors in Android projects. - (more info)
    • -
    • Added sensor emulation support, which allows the emulator to read sensor data from a - physical Android device. - (more info)
    • -
    • Added support for using a webcam to emulate a camera on Mac OS X.
    • -
    -
    -
    Bug fixes:
    -
    - -
    -
    -
    -
    - -
    - - - SDK Tools, Revision 15 (October 2011) - -
    -

    Important: To download the new Android - 4.0 system components from the Android SDK Manager, you must first update the - SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, - the Android 4.0 system components will not be available for download.

    -
    -
    Dependencies:
    -
    -
    • Android SDK Platform-tools revision 9 or later.
    • -
    • If you are developing in Eclipse with ADT, note that the SDK Tools r15 is designed for use - with ADT 15.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 15.0.0.
    • -
    • If you are developing outside Eclipse, you must have Apache - Ant 1.8 or later.
    • -
    - -
    Bug fixes:
    -
    -
      -
    • Fixed emulator crash on Linux due to improper webcam detection - (Issue 20952).
    • -
    • Fixed emulator issue when using the -wipe-data argument.
    • -
    • Fixed build issue when using Renderscript in projects that target API levels 11-13 - (Issue 21006).
    • -
    • Fixed issue when creating an AVD using the GoogleTV addon - (Issue 20963).
    • -
    • Fixed ant test - (Issue 20979).
    • -
    • Fixed android update project - (Issue 20535).
    • -
    • Fixed scrolling issue in the new Logcat panel of DDMS.
    • -
    • Fixed issue with MonkeyRunner - (Issue 20964).
    • -
    • Fixed issues in the SDK Manager - (Issue 20939, - Issue 20607).
    • -
    -
    -
    -
    -
    - -
    - - - SDK Tools, Revision 14 (October 2011) - -
    -

    Important: To download the new Android - 4.0 system components from the Android SDK Manager, you must first update the - SDK tools to revision 14 and restart the Android SDK Manager. If you do not, - the Android 4.0 system components will not be available for download.

    -
    -
    Dependencies:
    -
    -
    • Android SDK Platform-tools revision 8 or later.
    • -
    • If you are developing in Eclipse with ADT, note that the SDK Tools r14 is designed for use - with ADT 14.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 14.0.0.
    • -
    • If you are developing outside Eclipse, you must have Apache - Ant 1.8 or later.
    • -
    - -
    General notes:
    -
    -
      -
    • Added webcam support to Android 4.0 or later platforms to emulate rear-facing cameras when - one webcam is present, and to emulate both rear-facing and front-facing cameras when two - webcams are present. Webcam support is for Windows and Linux only. - Mac support will come in a later release.
    • -
    • Changed default.properties to project.properties and - build.properties to ant.properties. Any existing - projects that you build with Ant must be updated with the android update project - command.
    • -
    • Changed Ant build.xml file to support improvements to the - build system and added and modified Ant commands to support these changes. For a list of Ant -commands, see the -Ant Command -Reference.
    • -
    • Changed how library projects are built.
    • -
    • Improved incremental builds, so that resource compilation runs less frequently. Builds no - longer run when you edit strings or layouts (unless you add a new id) and no longer - run once for each library project.
    • -
    • Introduced a "PNG crunch cache" that only runs on modified PNG files, instead of - crunching all existing PNG files, all the time.
    • -
    • Revamped the SDK Manager UI (more -info).
    • -
    -

    For a complete overview of the build system changes and what you need to do to support them, -see the Android Tools Project -site.

    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 13 (September 2011) -
    -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that the SDK Tools r13 is designed for use with -ADT 12.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 12.0.0.

    - -

    If you are developing outside Eclipse, you must have Apache -Ant 1.8 or later.

    - -
    General notes:
    -
    -
      -
    • Fix compilation issue in Ant (dex step) when paths have spaces.
    • -
    • Fix issue in emulator installation when paths have spaces.
    • -
    • Fix issue when AVD paths have spaces.
    • -
    • Fix rendering issue when using emulator scaling (see more).
    • -
    -
    -
    -
    -
    - - -
    - - -SDK Tools, Revision 12 (July 2011) -
    -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that the SDK Tools r12 is designed for use with -ADT 12.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 12.0.0.

    - -

    If you are developing outside Eclipse, you must have Apache -Ant 1.8 or later.

    - -
    General notes:
    -
    -
      -
    • The AVD manager and emulator can now use system images - compiled for ARM v7 and x86 CPUs.
    • -
    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 11 (May 2011) -
    -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that the SDK Tools r11 is designed for use with -ADT 10.0.1 and later. If you haven't already, we highly recommend updating your ADT Plugin to 10.0.1.

    - -

    If you are developing outside Eclipse, you must have Apache -Ant 1.8 or later.

    - -
    General notes:
    -
    -
      -
    • Miscellaneous emulator changes to support Android 3.1.
    • -
    -
    -
    -
    -
    - - -
    - - -SDK Tools, Revision 10 (February 2011) -
    -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that the SDK Tools r10 is -designed for use with ADT 10.0.0 and later. After installing SDK Tools r10, we -highly recommend updating your ADT Plugin to 10.0.0.

    - -

    If you are developing outside Eclipse, you must have Apache -Ant 1.8 or later.

    - -
    General notes:
    -
    -
      -
    • The tools now automatically generate Java Programming Language source files (in the -gen directory) and - bytecode (in the res/raw directory) from your native .rs files
    • -
    -
    -
    -
    -
    - - - -
    - - -SDK Tools, Revision 9 (January 2011) -
    -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that the SDK Tools r9 is -designed for use with ADT 9.0.0 and later. After installing SDK Tools r9, we -highly recommend updating your ADT Plugin to 9.0.0.

    - -

    If you are developing outside Eclipse, you must have Apache -Ant 1.8 or later.

    - -
    Upgrading to SDK Tools r9:
    -
    -

    If you are upgrading to SDK Tools r9 from SDK Tools r7 or earlier, the default installed location -for the adb tool has changed from <SDK>/tools/adb to -<SDK>/platform-tools/adb. This means that you should -add the new location to your PATH and modify any custom build scripts to -reference the new location. Copying the adb executable from the new -location to the old is not recommended, since subsequent updates to the SDK -Tools will delete the file.

    -
    - -
    General notes:
    -
    -
      -
    • The default ProGuard configuration, proguard.cfg, now ignores the following classes: -
        -
      • classes that extend {@link android.preference.Preference}
      • -
      • classes that extend {@link android.app.backup.BackupAgentHelper}
      • -
      -
    • -
    • Ant lib rules now allow you to override java.encoding, java.source, - and java.target properties.
    • -
    • The default encoding for the javac Ant task is now UTF-8.
    • -
    • The LogCat view in DDMS now properly displays UTF-8 characters.
    • -
    • The SDK Manager is more reliable on Windows. For details on the improvements, see the - Android Tools Project Site.
    • -
    • Early look at the new snapshot feature: To improve startup time for the emulator, you can -enable snapshots for the system state. The emulator will then restore to the state when it last -closed almost instantly. Note: The snapshot feature is still under active -development and might not always perform as expected.
    • -
    • Fixed the missing JAR file error that prevented draw9patch from running.
    • -
    • Fixed the Windows launch scripts hierarchyviewer and ddms to support - the new location of adb.
    • -
    • Known issues with emulator performance: Because the Android emulator must simulate the ARM -instruction set architecture on your computer, emulator performance is slow. We're working hard to -resolve the performance issues and it will improve in future releases.
    • -
    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 8 (December 2010) -
    - -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that SDK Tools r8 is -designed for use with ADT 8.0.0 and later. After installing SDK Tools r8, we -highly recommend updating your ADT Plugin to 8.0.0.

    - -

    If you are developing outside Eclipse, you must have Apache -Ant 1.8 or later.

    - -

    Also note that SDK Tools r8 requires a new SDK component called -Platform-tools. The new Platform-tools component lets all SDK platforms -(Android 2.1, Android 2.2, and so on) use the same (latest) version of build -tools such as adb, aapt, aidl, and -dx. To download the Platform-tools component, use the Android SDK -Manager, as described in Adding SDK -Components

    - -
    Upgrading from SDK Tools r7:
    -
    -

    If you are upgrading to SDK Tools r8 from an earlier version, note that the -the default installed location for the adb tool has changed from -<SDK>/tools/adb to -<SDK>/platform-tools/adb. This means that you should -add the new location to your PATH and modify any custom build scripts to -reference the new location. Copying the adb executable from the new -location to the old is not recommended, since subsequent updates to the SDK -Tools will delete the file.

    -
    - -
    General notes:
    -
    -
      -
    • All SDK platforms now support Library Projects.
    • -
    • Support for a true debug build. Developers no longer need to add the -android:debuggable attribute to the -<application> tag in the manifest — the build tools add -the attribute automatically. In Eclipse/ADT, all incremental builds are assumed -to be debug builds, so the tools insert android:debuggable="true". -When exporting a signed release build, the tools do not add the attribute. In -Ant, a ant debug command automatically inserts the -android:debuggable="true" attribute, while ant release -does not. If android:debuggable="true" is manually set, then -ant release will actually do a debug build, rather than a release -build.
    • -
    • Automatic ProGuard support in release builds. Developers generate a ProGuard -configuration file using the android tool — the build tools -then automatically run ProGuard against the project sources during the build. -For more information, see the ProGuard -documentation.
    • -
    • New overridable Ant javac properties: java.encoding, -java.source, and java.target (default values are -"ascii", "1.5", and "1.5", respectively).
    • -
    • New UI for the HierarchyViewer tool.
    • -
    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 7 (September 2010) -
    - -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that SDK Tools r7 is -designed for use with ADT 0.9.8 and later. After installing SDK Tools r7, we -highly recommend updating your ADT Plugin to 0.9.8.

    -
    - -
    General notes:
    -
    -
      -
    • Added support for library projects that depend on other library projects.
    • -
    • Adds support for aidl files in library projects.
    • -
    • Adds support for extension targets in Ant build to perform tasks between the -normal tasks: -pre-build, -pre-compile, and --post-compile.
    • -
    • Adds support for "headless" SDK update. See android -h update sdk -for more information.
    • -
    • Fixes location control in DDMS to work in any locale not using '.' as a -decimal point.
    • -
    - -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 6 (May 2010) -
    - -
    -
    Dependencies:
    -
    -

    If you are developing in Eclipse with ADT, note that SDK Tools r6 is -designed for use with ADT 0.9.7 and later. After installing SDK Tools r6, we -highly recommend updating your ADT Plugin to 0.9.7.

    -
    - -
    Library projects:
    -
    -

    The SDK Tools now support the use of library projects during -development, a capability that lets you store shared Android application -code and resources in a separate development project. You can then reference the -library project from other Android projects and, at build time, the tools -compile the shared code and resources as part of the dependent applications. -More information about this feature is available in the Creating and Managing Projects document.

    -

    If you are developing in Eclipse, ADT -provides the equivalent library project support.

    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 5 (March 2010) -
    - -
    -
    Dependencies:
    -
      -
    • If you are developing in Eclipse with ADT, note that SDK Tools r5 is -designed for use with ADT 0.9.6 and later. After installing SDK Tools r5, we -highly recommend updating your ADT Plugin to 0.9.6.
    • -
    • For Mac OS platforms, OS X 10.4.x (Tiger) is no longer -officially supported.
    • -
    -
    - -
    SDK and AVD Manager:
    -
    -
      -
    • Fixes SSL download for the standalone version of the SDK Updater.
    • -
    • Fixes issue with 64-bit JVM on Windows.
    • -
    • Adds support for platform samples components.
    • -
    • Improves support for dependency between components.
    • -
    • AVDs now sorted by API level.
    • -
    • The AVD creation dialog now enforces a minimum SD card size of 9MB.
    • -
    • Prevents deletion of running AVDs.
    • -
    • Settings are now automatically saved, no need to click "Apply".
    • -
    -
    - -
    Emulator:
    -
    -
      -
    • Emulator now requires SD card to be 9MB or more.
    • -
    -
    - -
    Layoutopt:
    -
    -
      -
    • Fixes layoutopt.bat to execute correctly on Windows.
    • -
    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 4 (December 2009) -
    - -
    -
    Dependencies:
    -

    SDK Tools r4 is compatible with ADT 0.9.5 and later, but not -compatible with earlier versions. If you are developing in Eclipse with ADT, you -must update your ADT plugin to version 0.9.5 or higher if you -install SDK Tools r4 in your SDK.

    - -
    General notes:
    -
    -
      -
    • Launcher script now forces GDK_NATIVE_WINDOW=true (linux only), to fix a -compatibility issue between GTK and SWT.
    • -
    -
    - -
    Android SDK and AVD Manager:
    -
    -
      -
    • AVD Launch dialog now shows scale value.
    • -
    • Fixes potential NPE in SDK Manager on AVD launch, for older AVD with no -skin name specified.
    • -
    • Fixes XML validation issue in on older Java versions.
    • -
    • No longer forces the use of Java 1.5 on Mac OS X.
    • -
    -
    - -
    Emulator:
    -
    -
      -
    • No longer limits the size of the system partition.
    • -
    -
    - -
    Ant build tools:
    -
    -
      -
    • .apk packaging now properly ignores vi swap files as well as hidden files.
    • -
    -
    -
    -
    -
    - -
    - - -SDK Tools, Revision 3 (October 2009) -
    - -
    -
    Dependencies:
    -

    SDK Tools r3 is compatible with ADT 0.9.4 and later, but not -compatible with earlier versions. If you are developing in Eclipse with ADT, you -must update your ADT plugin to version 0.9.4 or higher if you -install SDK Tools r3 in your SDK.

    -
    - -
    Android tool:
    -
    -
      -
    • Adds new android create test-project and android update -test-project commands to allow for greater flexibility in the location of the -main and test projects.
    • -
    -
    - -
    DDMS:
    -
    -
      -
    • Adds a button to dump HPROF file for running applications (app must be able -to write to the sdcard).
    • -
    • Button to start/stop profiling of a running application (app must be able to -write to the sdcard). Upon stop, Traceview will automatically be launched to -display the trace.
    • -
    • Fixed DDMS, Traceview, and the AVD Mananger/SDK Updater to run on Mac OS X -10.6.
    • -
    • Fixed screenshot support for devices running 32-bit framebuffer.
    • -
    -
    - -
    Android SDK and AVD Manager:
    -
    -
      -
    • Provides a new UI that lets you set options for controlling -the emulator skin, screen size/density, and scale factor used when launching -an AVD.
    • -
    • Provides improved AVD creation UI, which lets you customize the hardware -properties of your AVDs.
    • -
    • Now enforces dependencies between platforms and tools components, and -between SDK add-ons and platforms.
    • -
    -
    - -
    Layoutopt, a new tool for optimizing layouts:
    - -

    The SDK Tools r3 package includes layoutopt, a new command-line -tool that helps you optimize your layout hierarchies. When run against your -layout files, the tool analyzes their hierarchies and notifies you of -inefficiencies and other potential issues. The tool also provides simple -solutions for the issues it finds. For usage, see layoutopt.

    -
    -
    -
    -
    diff --git a/docs/html/sdk/win-usb.jd b/docs/html/sdk/win-usb.jd index 3be0faf99bfc..802615e3849d 100644 --- a/docs/html/sdk/win-usb.jd +++ b/docs/html/sdk/win-usb.jd @@ -10,7 +10,7 @@ page.title=Google USB Driver

    See also

      -
    1. Installing a USB Driver
    2. +
    3. Installing a USB Driver
    4. Using Hardware Devices
    5. Adding SDK Packages
    @@ -30,7 +30,7 @@ following devices:

    * Or similar hardware on other carriers

    All other devices require Windows drivers provided by the hardware manufacturer, as listed in -the OEM USB Drivers document. The Galaxy Nexus +the OEM USB Drivers document. The Galaxy Nexus driver is also distributed by Samsung (listed as model SCH-I515).

    @@ -169,4 +169,4 @@ included with the Android SDK:

    downloaded into the <sdk>\extras\google\usb_driver\ directory. -

    For installation information, read Installing a USB Driver.

    +

    For installation information, read Installing a USB Driver.

    diff --git a/docs/html/search.jd b/docs/html/search.jd deleted file mode 100644 index 407bc86b570b..000000000000 --- a/docs/html/search.jd +++ /dev/null @@ -1,148 +0,0 @@ -page.title=Search Results -@jd:body - - - - - -
    -

    search results

    - -

    -
    Loading...
    -
    diff --git a/docs/html/shareables/training/CustomView.zip b/docs/html/shareables/training/CustomView.zip new file mode 100644 index 000000000000..f8c1c7aa7c1c Binary files /dev/null and b/docs/html/shareables/training/CustomView.zip differ diff --git a/docs/html/shareables/training/FragmentBasics.zip b/docs/html/shareables/training/FragmentBasics.zip index ff5b7f120ca1..b5b19d03ba5a 100644 Binary files a/docs/html/shareables/training/FragmentBasics.zip and b/docs/html/shareables/training/FragmentBasics.zip differ diff --git a/docs/html/shareables/training/NetworkUsage.zip b/docs/html/shareables/training/NetworkUsage.zip new file mode 100644 index 000000000000..8c7fbef9fb49 Binary files /dev/null and b/docs/html/shareables/training/NetworkUsage.zip differ diff --git a/docs/html/shareables/training/OpenGLES.zip b/docs/html/shareables/training/OpenGLES.zip new file mode 100644 index 000000000000..862ae1f87984 Binary files /dev/null and b/docs/html/shareables/training/OpenGLES.zip differ diff --git a/docs/html/sitemap-intl.txt b/docs/html/sitemap-intl.txt index ded0554b3c41..9041581db6e8 100644 --- a/docs/html/sitemap-intl.txt +++ b/docs/html/sitemap-intl.txt @@ -1,11 +1,11 @@ http://developer.android.com/ja/sdk/1.5_r3/installing.html http://developer.android.com/ja/community/index.html http://developer.android.com/ja/index.html -http://developer.android.com/ja/guide/publishing/versioning.html -http://developer.android.com/ja/guide/publishing/app-signing.html -http://developer.android.com/ja/guide/publishing/preparing.html +http://developer.android.com/ja/tools/publishing/versioning.html +http://developer.android.com/ja/tools/publishing/app-signing.html +http://developer.android.com/ja/tools/publishing/preparing.html http://developer.android.com/ja/guide/tutorials/hello-world.html -http://developer.android.com/ja/guide/topics/fundamentals.html +http://developer.android.com/ja/guide/components/fundamentals.html http://developer.android.com/ja/guide/index.html http://developer.android.com/ja/guide/basics/what-is-android.html http://developer.android.com/ja/guide/developing/other-ide.html diff --git a/docs/html/sitemap.txt b/docs/html/sitemap.txt index 3f26dd063625..ee85bd436fa6 100644 --- a/docs/html/sitemap.txt +++ b/docs/html/sitemap.txt @@ -5,32 +5,32 @@ http://developer.android.com/guide/index.html http://developer.android.com/reference/packages.html http://developer.android.com/resources/index.html http://developer.android.com/videos/index.html -http://developer.android.com/resources/dashboard/platform-versions.html +http://developer.android.com/about/dashboards/index.html http://developer.android.com/license.html -http://developer.android.com/sdk/installing.html -http://developer.android.com/sdk/android-3.0-highlights.html +http://developer.android.com/sdk/installing/index.html +http://developer.android.com/about/versions/android-3.0-highlights.html http://developer.android.com/sdk/preview/index.html -http://developer.android.com/sdk/adding-components.html -http://developer.android.com/sdk/android-2.3.html -http://developer.android.com/sdk/android-2.3-highlights.html +http://developer.android.com/sdk/exploring.html +http://developer.android.com/about/versions/android-2.3.html +http://developer.android.com/about/versions/android-2.3-highlights.html http://developer.android.com/sdk/api_diff/9/changes.html -http://developer.android.com/sdk/android-2.2.html -http://developer.android.com/sdk/android-2.1.html -http://developer.android.com/sdk/android-1.6.html -http://developer.android.com/sdk/android-1.5.html -http://developer.android.com/sdk/android-2.0.1.html -http://developer.android.com/sdk/android-2.0.html -http://developer.android.com/sdk/android-1.1.html -http://developer.android.com/sdk/tools-notes.html +http://developer.android.com/about/versions/android-2.2.html +http://developer.android.com/about/versions/android-2.1.html +http://developer.android.com/about/versions/android-1.6.html +http://developer.android.com/about/versions/android-1.5.html +http://developer.android.com/about/versions/android-2.0.1.html +http://developer.android.com/about/versions/android-2.0.html +http://developer.android.com/about/versions/android-1.1.html +http://developer.android.com/tools/sdk/tools-notes.html http://developer.android.com/sdk/win-usb.html http://developer.android.com/sdk/eclipse-adt.html http://developer.android.com/sdk/ndk/index.html http://developer.android.com/sdk/ndk/overview.html -http://developer.android.com/sdk/oem-usb.html +http://developer.android.com/tools/extras/oem-usb.html http://developer.android.com/sdk/requirements.html http://developer.android.com/sdk/older_releases.html http://developer.android.com/guide/basics/what-is-android.html -http://developer.android.com/guide/topics/fundamentals.html +http://developer.android.com/guide/components/fundamentals.html http://developer.android.com/guide/topics/ui/index.html http://developer.android.com/guide/topics/ui/declaring-layout.html http://developer.android.com/guide/topics/ui/menus.html @@ -58,7 +58,7 @@ http://developer.android.com/guide/topics/resources/menu-resource.html http://developer.android.com/guide/topics/resources/string-resource.html http://developer.android.com/guide/topics/resources/style-resource.html http://developer.android.com/guide/topics/resources/more-resources.html -http://developer.android.com/guide/topics/intents/intents-filters.html +http://developer.android.com/guide/components/intents-filters.html http://developer.android.com/guide/topics/data/data-storage.html http://developer.android.com/guide/topics/data/backup.html http://developer.android.com/guide/topics/providers/content-providers.html @@ -93,62 +93,62 @@ http://developer.android.com/guide/topics/graphics/2d-graphics.html http://developer.android.com/guide/topics/graphics/opengl.html http://developer.android.com/guide/topics/media/index.html http://developer.android.com/guide/topics/location/index.html -http://developer.android.com/guide/topics/location/obtaining-user-location.html +http://developer.android.com/guide/topics/location/strategies.html http://developer.android.com/guide/topics/appwidgets/index.html -http://developer.android.com/guide/topics/wireless/bluetooth.html +http://developer.android.com/guide/topics/connectivity/bluetooth.html http://developer.android.com/guide/topics/search/index.html http://developer.android.com/guide/topics/search/search-dialog.html http://developer.android.com/guide/topics/search/adding-recent-query-suggestions.html http://developer.android.com/guide/topics/search/adding-custom-suggestions.html http://developer.android.com/guide/topics/search/searchable-config.html http://developer.android.com/guide/topics/admin/device-admin.html -http://developer.android.com/guide/topics/testing/index.html -http://developer.android.com/guide/topics/testing/testing_android.html -http://developer.android.com/guide/topics/testing/activity_testing.html -http://developer.android.com/guide/topics/testing/contentprovider_testing.html -http://developer.android.com/guide/topics/testing/service_testing.html -http://developer.android.com/guide/topics/testing/what_to_test.html -http://developer.android.com/guide/market/licensing/index.html -http://developer.android.com/guide/market/billing/index.html -http://developer.android.com/guide/market/billing/billing_about.html -http://developer.android.com/guide/market/billing/billing_overview.html -http://developer.android.com/guide/market/billing/billing_integrate.html -http://developer.android.com/guide/market/billing/billing_best_practices.html -http://developer.android.com/guide/market/billing/billing_testing.html -http://developer.android.com/guide/market/billing/billing_admin.html -http://developer.android.com/guide/market/billing/billing_reference.html -http://developer.android.com/guide/appendix/market-filters.html +http://developer.android.com/tools/testing/index.html +http://developer.android.com/tools/testing/testing_android.html +http://developer.android.com/tools/testing/activity_testing.html +http://developer.android.com/tools/testing/contentprovider_testing.html +http://developer.android.com/tools/testing/service_testing.html +http://developer.android.com/tools/testing/what_to_test.html +http://developer.android.com/guide/google/play/licensing/index.html +http://developer.android.com/guide/google/play/billing/index.html +http://developer.android.com/guide/google/play/billing/billing_about.html +http://developer.android.com/guide/google/play/billing/billing_overview.html +http://developer.android.com/guide/google/play/billing/billing_integrate.html +http://developer.android.com/guide/google/play/billing/billing_best_practices.html +http://developer.android.com/guide/google/play/billing/billing_testing.html +http://developer.android.com/guide/google/play/billing/billing_admin.html +http://developer.android.com/guide/google/play/billing/billing_reference.html +http://developer.android.com/guide/google/play/filters.html http://developer.android.com/guide/developing/eclipse-adt.html http://developer.android.com/guide/developing/other-ide.html -http://developer.android.com/guide/developing/device.html +http://developer.android.com/tools/device.html http://developer.android.com/guide/developing/debug-tasks.html -http://developer.android.com/guide/developing/testing/index.html -http://developer.android.com/guide/developing/testing/testing_eclipse.html -http://developer.android.com/guide/developing/testing/testing_otheride.html -http://developer.android.com/guide/developing/tools/index.html -http://developer.android.com/guide/developing/tools/aapt.html -http://developer.android.com/guide/developing/tools/adb.html -http://developer.android.com/guide/developing/tools/othertools.html -http://developer.android.com/guide/developing/tools/aidl.html -http://developer.android.com/guide/developing/tools/avd.html -http://developer.android.com/guide/developing/tools/bmgr.html -http://developer.android.com/guide/developing/tools/ddms.html -http://developer.android.com/guide/developing/tools/draw9patch.html -http://developer.android.com/guide/developing/tools/emulator.html -http://developer.android.com/guide/developing/tools/hierarchy-viewer.html -http://developer.android.com/guide/developing/tools/layoutopt.html -http://developer.android.com/guide/developing/tools/monkey.html -http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html -http://developer.android.com/guide/developing/tools/MonkeyDevice.html -http://developer.android.com/guide/developing/tools/MonkeyImage.html -http://developer.android.com/guide/developing/tools/MonkeyRunner.html -http://developer.android.com/guide/developing/tools/proguard.html -http://developer.android.com/guide/developing/tools/traceview.html -http://developer.android.com/guide/developing/tools/zipalign.html -http://developer.android.com/guide/publishing/app-signing.html -http://developer.android.com/guide/publishing/versioning.html -http://developer.android.com/guide/publishing/preparing.html -http://developer.android.com/guide/publishing/publishing.html +http://developer.android.com/tools/testing/index.html +http://developer.android.com/tools/testing/testing_eclipse.html +http://developer.android.com/tools/testing/testing_otheride.html +http://developer.android.com/tools/index.html +http://developer.android.com/tools/aapt.html +http://developer.android.com/tools/help/adb.html +http://developer.android.com/tools/othertools.html +http://developer.android.com/tools/aidl.html +http://developer.android.com/tools/avd.html +http://developer.android.com/tools/bmgr.html +http://developer.android.com/tools/ddms.html +http://developer.android.com/tools/draw9patch.html +http://developer.android.com/tools/help/emulator.html +http://developer.android.com/tools/hierarchy-viewer.html +http://developer.android.com/tools/help/layoutopt.html +http://developer.android.com/tools/monkey.html +http://developer.android.com/tools/monkeyrunner_concepts.html +http://developer.android.com/tools/MonkeyDevice.html +http://developer.android.com/tools/MonkeyImage.html +http://developer.android.com/tools/MonkeyRunner.html +http://developer.android.com/tools/proguard.html +http://developer.android.com/tools/traceview.html +http://developer.android.com/tools/zipalign.html +http://developer.android.com/tools/publishing/app-signing.html +http://developer.android.com/tools/publishing/versioning.html +http://developer.android.com/tools/publishing/preparing.html +http://developer.android.com/tools/publishing/publishing.html http://developer.android.com/guide/practices/compatibility.html http://developer.android.com/guide/practices/screens_support.html http://developer.android.com/guide/practices/ui_guidelines/index.html @@ -160,15 +160,15 @@ http://developer.android.com/guide/practices/ui_guidelines/icon_design_tab.html http://developer.android.com/guide/practices/ui_guidelines/icon_design_dialog.html http://developer.android.com/guide/practices/ui_guidelines/icon_design_list.html http://developer.android.com/guide/practices/ui_guidelines/widget_design.html -http://developer.android.com/guide/practices/design/performance.html -http://developer.android.com/guide/practices/design/responsiveness.html -http://developer.android.com/guide/practices/design/seamlessness.html +http://developer.android.com/guide/practices/performance.html +http://developer.android.com/guide/practices/responsiveness.html +http://developer.android.com/guide/practices/seamlessness.html http://developer.android.com/guide/webapps/index.html http://developer.android.com/guide/webapps/targeting.html http://developer.android.com/guide/webapps/webview.html http://developer.android.com/guide/webapps/debugging.html http://developer.android.com/guide/webapps/best-practices.html -http://developer.android.com/guide/appendix/api-levels.html +http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels http://developer.android.com/guide/appendix/install-location.html http://developer.android.com/guide/appendix/media-formats.html http://developer.android.com/guide/appendix/g-app-intents.html @@ -209,12 +209,12 @@ http://developer.android.com/resources/articles/wikinotes-linkify.html http://developer.android.com/resources/articles/wikinotes-intents.html http://developer.android.com/resources/articles/window-bg-speed.html http://developer.android.com/resources/articles/zipalign.html -http://developer.android.com/resources/tutorials/hello-world.html +http://developer.android.com/training/basics/firstapp/index.html http://developer.android.com/resources/tutorials/views/index.html http://developer.android.com/resources/tutorials/localization/index.html http://developer.android.com/resources/tutorials/testing/helloandroid_test.html http://developer.android.com/resources/tutorials/notepad/index.html -http://developer.android.com/resources/tutorials/testing/activity_test.html +http://developer.android.com/tools/testing/activity_test.html http://developer.android.com/resources/samples/get.html http://developer.android.com/resources/samples/index.html http://developer.android.com/resources/samples/AccelerometerPlay/index.html @@ -404,7 +404,7 @@ http://developer.android.com/reference/android/app/NativeActivity.html http://developer.android.com/reference/android/opengl/GLSurfaceView.html http://developer.android.com/reference/android/graphics/Bitmap.html http://developer.android.com/sdk/api_diff/3/changes.html -http://developer.android.com/sdk/android-1.5-highlights.html +http://developer.android.com/about/versions/android-1.5-highlights.html http://developer.android.com/reference/android/widget/SlidingDrawer.html http://developer.android.com/reference/android/widget/HorizontalScrollView.html http://developer.android.com/reference/android/provider/LiveFolders.html @@ -412,7 +412,7 @@ http://developer.android.com/reference/android/inputmethodservice/InputMethodSer http://developer.android.com/reference/android/speech/RecognizerIntent.html http://developer.android.com/reference/android/hardware/SensorManager.html http://developer.android.com/sdk/api_diff/6/changes.html -http://developer.android.com/sdk/android-2.0-highlights.html +http://developer.android.com/about/versions/android-2.0-highlights.html http://developer.android.com/reference/android/widget/QuickContactBadge.html http://developer.android.com/reference/android/content/Intent.html http://developer.android.com/reference/android/content/Context.html @@ -503,7 +503,7 @@ http://developer.android.com/reference/java/lang/String.html http://developer.android.com/reference/java/text/Normalizer.html http://developer.android.com/reference/java/text/Normalizer.Form.html http://developer.android.com/sdk/api_diff/8/changes.html -http://developer.android.com/sdk/android-2.2-highlights.html +http://developer.android.com/about/versions/android-2.2-highlights.html http://developer.android.com/reference/android/opengl/ETC1.html http://developer.android.com/reference/android/opengl/ETC1Util.html http://developer.android.com/reference/android/opengl/ETC1Util.ETC1Texture.html @@ -540,7 +540,7 @@ http://developer.android.com/reference/android/os/Process.html http://developer.android.com/reference/android/widget/TextView.html http://developer.android.com/reference/android/Manifest.permission.html http://developer.android.com/sdk/api_diff/4/changes.html -http://developer.android.com/sdk/android-1.6-highlights.html +http://developer.android.com/about/versions/android-1.6-highlights.html http://developer.android.com/reference/android/view/View.OnClickListener.html http://developer.android.com/reference/android/app/SearchManager.html http://developer.android.com/reference/android/telephony/SmsManager.html @@ -942,7 +942,7 @@ http://developer.android.com/reference/android/net/http/SslError.html http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html http://developer.android.com/reference/org/apache/http/HttpRequestInterceptor.html http://developer.android.com/reference/android/content/pm/PackageItemInfo.html -http://developer.android.com/guide/developing/tools/adt.html +http://developer.android.com/tools/adt.html http://developer.android.com/reference/android/graphics/NinePatch.html http://developer.android.com/reference/android/preference/Preference.OnPreferenceChangeListener.html http://developer.android.com/reference/android/preference/Preference.OnPreferenceClickListener.html @@ -5020,7 +5020,7 @@ http://developer.android.com/sdk/api_diff/4/changes/fields_index_changes.html http://developer.android.com/resources/samples/MultiResolution/res/drawable-ldpi-v6/ic_launcher.html http://developer.android.com/reference/android/app/package-descr.html http://developer.android.com/resources/samples/TicTacToeLib/res/layout/lib_game.html -http://developer.android.com/guide/market/billing/billing-intents +http://developer.android.com/guide/google/play/billing/billing-intents http://developer.android.com/resources/samples/TicTacToeLib/res/values/strings.html http://developer.android.com/resources/samples/ApiDemos/res/values-normal-notlong/strings.html http://developer.android.com/resources/samples/TicTacToeMain/src/com/example/android/index.html diff --git a/docs/html/support.jd b/docs/html/support.jd new file mode 100644 index 000000000000..89acd5db45c0 --- /dev/null +++ b/docs/html/support.jd @@ -0,0 +1,74 @@ +page.title=Developer Support +fullpage=1 +@jd:body + +
    + +

    Developer Support Resources

    + +
    + +
    +

    Code-Level Support

    + +
    Community and Office Hours
    +

    + +android-developers support forum
    +android-ndk support forum
    +android-security-discuss support forum
    + + #android, #android-dev (IRC via irc.freenode.net)
    + +Android Developers Office Hours (Wednesdays 2 PM PST (UTC-7))
    +

    + + +
    Send Feedback
    +

    + Report documentation bug
    + Report device bug
    + Report platform bug
    + +

    + + + + +
    \ No newline at end of file diff --git a/docs/html/tools/aidl.jd b/docs/html/tools/aidl.jd new file mode 100644 index 000000000000..805b7ec216d2 --- /dev/null +++ b/docs/html/tools/aidl.jd @@ -0,0 +1,465 @@ +page.title=Android Interface Definition Language (AIDL) +@jd:body + + + + + +

    AIDL (Android Interface Definition Language) is similar to other IDLs you might have +worked with. It allows you to define the programming interface that both +the client and service agree upon in order to communicate with each other using +interprocess communication (IPC). On Android, one process cannot normally access the +memory of another process. So to talk, they need to decompose their objects into primitives that the +operating system can understand, and marshall the objects across that boundary for you. The code to +do that marshalling is tedious to write, so Android handles it for you with AIDL.

    + +

    Note: Using AIDL is necessary only if you allow clients from +different applications to access your service for IPC and want to handle multithreading in your +service. If you do not need to perform concurrent IPC across +different applications, you should create your interface by implementing a +Binder or, if you want to perform IPC, but do not need to handle multithreading, +implement your interface using a Messenger. +Regardless, be sure that you understand Bound Services before +implementing an AIDL.

    + +

    Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are +direct function calls. You should not make assumptions about the thread in which the call +occurs. What happens is different depending on whether the call is from a thread in the +local process or a remote process. Specifically:

    + +
      +
    • Calls made from the local process are executed in the same thread that is making the call. If +this is your main UI thread, that thread continues to execute in the AIDL interface. If it is +another thread, that is the one that executes your code in the service. Thus, if only local +threads are accessing the service, you can completely control which threads are executing in it (but +if that is the case, then you shouldn't be using AIDL at all, but should instead create the +interface by implementing a +Binder).
    • + +
    • Calls from a remote process are dispatched from a thread pool the platform maintains inside of +your own process. You must be prepared for incoming calls from unknown threads, with multiple calls +happening at the same time. In other words, an implementation of an AIDL interface must be +completely thread-safe.
    • + +
    • The {@code oneway} keyword modifies the behavior of remote calls. When used, a remote call does +not block; it simply sends the transaction data and immediately returns. +The implementation of the interface eventually receives this as a regular call from the {@link +android.os.Binder} thread pool as a normal remote call. If {@code oneway} is used with a local call, +there is no impact and the call is still synchronous.
    • +
    + + +

    Defining an AIDL Interface

    + +

    You must define your AIDL interface in an {@code .aidl} file using the Java +programming language syntax, then save it in the source code (in the {@code src/} directory) of both +the application hosting the service and any other application that binds to the service.

    + +

    When you build each application that contains the {@code .aidl} file, the Android SDK tools +generate an {@link android.os.IBinder} interface based on the {@code .aidl} file and save it in +the project's {@code gen/} directory. The service must implement the {@link android.os.IBinder} +interface as appropriate. The client applications can then bind to the service and call methods from +the {@link android.os.IBinder} to perform IPC.

    + +

    To create a bounded service using AIDL, follow these steps:

    +
      +
    1. Create the .aidl file +

      This file defines the programming interface with method signatures.

      +
    2. +
    3. Implement the interface +

      The Android SDK tools generate an interface in the Java programming language, based on your +{@code .aidl} file. This interface has an inner abstract class named {@code Stub} that extends +{@link android.os.Binder} and implements methods from your AIDL interface. You must extend the +{@code Stub} class and implement the methods.

      +
    4. +
    5. Expose the interface to clients +

      Implement a {@link android.app.Service Service} and override {@link +android.app.Service#onBind onBind()} to return your implementation of the {@code Stub} +class.

      +
    6. +
    + +

    Caution: Any changes that you make to your AIDL interface after +your first release must remain backward compatible in order to avoid breaking other applications +that use your service. That is, because your {@code .aidl} file must be copied to other applications +in order for them to access your service's interface, you must maintain support for the original +interface.

    + + +

    1. Create the .aidl file

    + +

    AIDL uses a simple syntax that lets you declare an interface with one or more methods that can +take parameters and return values. The parameters and return values can be of any type, even other +AIDL-generated interfaces.

    + +

    You must construct the {@code .aidl} file using the Java programming language. Each {@code .aidl} +file must define a single interface and requires only the interface declaration and method +signatures.

    + +

    By default, AIDL supports the following data types:

    + +
      +
    • All primitive types in the Java programming language (such as {@code int}, {@code long}, +{@code char}, {@code boolean}, and so on)
    • +
    • {@link java.lang.String}
    • +
    • {@link java.lang.CharSequence}
    • +
    • {@link java.util.List} +

      All elements in the {@link java.util.List} must be one of the supported data types in this +list or one of the other AIDL-generated interfaces or parcelables you've declared. A {@link +java.util.List} may optionally be used as a "generic" class (for example, +List<String>). +The actual concrete class that the other side receives is always an {@link +java.util.ArrayList}, although the method is generated to use the {@link +java.util.List} interface.

      +
    • +
    • {@link java.util.Map} +

      All elements in the {@link java.util.Map} must be one of the supported data types in this +list or one of the other AIDL-generated interfaces or parcelables you've declared. Generic maps, +(such as those of the form +{@code Map<String,Integer>} are not supported. The actual concrete class that the other side +receives is always a {@link java.util.HashMap}, although the method is generated to +use the {@link java.util.Map} interface.

      +
    • +
    + +

    You must include an {@code import} statement for each additional type not listed above, even if +they are defined in the same package as your interface.

    + +

    When defining your service interface, be aware that:

    +
      +
    • Methods can take zero or more parameters, and return a value or void.
    • +
    • All non-primitive parameters require a directional tag indicating which way the data goes. +Either in, out, or inout (see the example below). +

      Primitives are in by default, and cannot be otherwise.

      +

      Caution: You should limit the direction to what is truly +needed, because marshalling parameters is expensive.

    • +
    • All code comments included in the {@code .aidl} file are included in the generated {@link +android.os.IBinder} interface (except for comments before the import and package +statements).
    • +
    • Only methods are supported; you cannot expose static fields in AIDL.
    • +
    + +

    Here is an example {@code .aidl} file:

    + +
    +// IRemoteService.aidl
    +package com.example.android;
    +
    +// Declare any non-default types here with import statements
    +
    +/** Example service interface */
    +interface IRemoteService {
    +    /** Request the process ID of this service, to do evil things with it. */
    +    int getPid();
    +
    +    /** Demonstrates some basic types that you can use as parameters
    +     * and return values in AIDL.
    +     */
    +    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
    +            double aDouble, String aString);
    +}
    +
    + +

    Simply save your {@code .aidl} file in your project's {@code src/} directory and when you +build your application, the SDK tools generate the {@link android.os.IBinder} interface file in your +project's {@code gen/} directory. The generated file name matches the {@code .aidl} file name, but +with a {@code .java} extension (for example, {@code IRemoteService.aidl} results in {@code +IRemoteService.java}).

    + +

    If you use Eclipse, the incremental build generates the binder class almost immediately. If you +do not use Eclipse, then the Ant tool generates the binder class next time you build your +application—you should build your project with ant debug (or ant +release) as soon as you're finished writing the {@code .aidl} file, so that your code can +link against the generated class.

    + + +

    2. Implement the interface

    + +

    When you build your application, the Android SDK tools generate a {@code .java} interface file +named after your {@code .aidl} file. The generated interface includes a subclass named {@code Stub} +that is an abstract implementation of its parent interface (for example, {@code +YourInterface.Stub}) and declares all the methods from the {@code .aidl} file.

    + +

    Note: {@code Stub} also +defines a few helper methods, most notably {@code asInterface()}, which takes an {@link +android.os.IBinder} (usually the one passed to a client's {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method) and +returns an instance of the stub interface. See the section Calling an IPC +Method for more details on how to make this cast.

    + +

    To implement the interface generated from the {@code .aidl}, extend the generated {@link +android.os.Binder} interface (for example, {@code YourInterface.Stub}) and implement the methods +inherited from the {@code .aidl} file.

    + +

    Here is an example implementation of an interface called {@code IRemoteService} (defined by the +{@code IRemoteService.aidl} example, above) using an anonymous instance:

    + +
    +private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    +    public int getPid(){
    +        return Process.myPid();
    +    }
    +    public void basicTypes(int anInt, long aLong, boolean aBoolean,
    +        float aFloat, double aDouble, String aString) {
    +        // Does nothing
    +    }
    +};
    +
    + +

    Now the {@code mBinder} is an instance of the {@code Stub} class (a {@link android.os.Binder}), +which defines the RPC interface for the service. In the next step, this instance is exposed to +clients so they can interact with the service.

    + +

    There are a few rules you should be aware of when implementing your AIDL interface:

    +
      +
    • Incoming calls are not guaranteed to be executed on the main thread, so you need to think +about multithreading from the start and properly build your service to be thread-safe.
    • +
    • By default, RPC calls are synchronous. If you know that the service takes more than a few +milliseconds to complete a request, you should not call it from the activity's main thread, because +it might hang the application (Android might display an "Application is Not Responding" +dialog)—you should usually call them from a separate thread in the client.
    • +
    • No exceptions that you throw are sent back to the caller.
    • +
    + + +

    3. Expose the interface to clients

    + +

    Once you've implemented the interface for your service, you need to expose it to +clients so they can bind to it. To expose the interface +for your service, extend {@link android.app.Service Service} and implement {@link +android.app.Service#onBind onBind()} to return an instance of your class that implements +the generated {@code Stub} (as discussed in the previous section). Here's an example +service that exposes the {@code IRemoteService} example interface to clients.

    + +
    +public class RemoteService extends Service {
    +    @Override
    +    public void onCreate() {
    +        super.onCreate();
    +    }
    +
    +    @Override
    +    public IBinder onBind(Intent intent) {
    +        // Return the interface
    +        return mBinder;
    +    }
    +
    +    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    +        public int getPid(){
    +            return Process.myPid();
    +        }
    +        public void basicTypes(int anInt, long aLong, boolean aBoolean,
    +            float aFloat, double aDouble, String aString) {
    +            // Does nothing
    +        }
    +    };
    +}
    +
    + +

    Now, when a client (such as an activity) calls {@link android.content.Context#bindService +bindService()} to connect to this service, the client's {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback receives the +{@code mBinder} instance returned by the service's {@link android.app.Service#onBind onBind()} +method.

    + +

    The client must also have access to the interface class, so if the client and service are in +separate applications, then the client's application must have a copy of the {@code .aidl} file +in its {@code src/} directory (which generates the {@code android.os.Binder} +interface—providing the client access to the AIDL methods).

    + +

    When the client receives the {@link android.os.IBinder} in the {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback, it must call +YourServiceInterface.Stub.asInterface(service) to cast the returned +parameter to YourServiceInterface type. For example:

    + +
    +IRemoteService mIRemoteService;
    +private ServiceConnection mConnection = new ServiceConnection() {
    +    // Called when the connection with the service is established
    +    public void onServiceConnected(ComponentName className, IBinder service) {
    +        // Following the example above for an AIDL interface,
    +        // this gets an instance of the IRemoteInterface, which we can use to call on the service
    +        mIRemoteService = IRemoteService.Stub.asInterface(service);
    +    }
    +
    +    // Called when the connection with the service disconnects unexpectedly
    +    public void onServiceDisconnected(ComponentName className) {
    +        Log.e(TAG, "Service has unexpectedly disconnected");
    +        mIRemoteService = null;
    +    }
    +};
    +
    + +

    For more sample code, see the {@code +RemoteService.java} class in ApiDemos.

    + + + + + + + + +

    Passing Objects over IPC

    + +

    If you have a class that you would like to send from one process to another through +an IPC interface, you can do that. However, you must ensure that the code for your class is +available to the other side of the IPC channel and your class must support the {@link +android.os.Parcelable} interface. Supporting the {@link android.os.Parcelable} interface is +important because it allows the Android system to decompose objects into primitives that can be +marshalled across processes.

    + +

    To create a class that supports the {@link android.os.Parcelable} protocol, you must do the +following: +

      +
    1. Make your class implement the {@link android.os.Parcelable} interface.
    2. +
    3. Implement {@link android.os.Parcelable#writeToParcel writeToParcel}, which takes the +current state of the object and writes it to a {@link android.os.Parcel}.
    4. +
    5. Add a static field called CREATOR to your class which is an object implementing +the {@link android.os.Parcelable.Creator Parcelable.Creator} interface.
    6. +
    7. Finally, create an {@code .aidl} file that declares your parcelable class (as shown for the +{@code Rect.aidl} file, below). +

      If you are using a custom build process, do not add the {@code .aidl} file to your +build. Similar to a header file in the C language, this {@code .aidl} file isn't compiled.

    8. +
    + +

    AIDL uses these methods and fields in the code it generates to marshall and unmarshall +your objects.

    + +

    For example, here is a {@code Rect.aidl} file to create a {@code Rect} class that's +parcelable:

    + +
    +package android.graphics;
    +
    +// Declare Rect so AIDL can find it and knows that it implements
    +// the parcelable protocol.
    +parcelable Rect;
    +
    + +

    And here is an example of how the {@link android.graphics.Rect} class implements the +{@link android.os.Parcelable} protocol.

    + +
    +import android.os.Parcel;
    +import android.os.Parcelable;
    +
    +public final class Rect implements Parcelable {
    +    public int left;
    +    public int top;
    +    public int right;
    +    public int bottom;
    +
    +    public static final Parcelable.Creator<Rect> CREATOR = new
    +Parcelable.Creator<Rect>() {
    +        public Rect createFromParcel(Parcel in) {
    +            return new Rect(in);
    +        }
    +
    +        public Rect[] newArray(int size) {
    +            return new Rect[size];
    +        }
    +    };
    +
    +    public Rect() {
    +    }
    +
    +    private Rect(Parcel in) {
    +        readFromParcel(in);
    +    }
    +
    +    public void writeToParcel(Parcel out) {
    +        out.writeInt(left);
    +        out.writeInt(top);
    +        out.writeInt(right);
    +        out.writeInt(bottom);
    +    }
    +
    +    public void readFromParcel(Parcel in) {
    +        left = in.readInt();
    +        top = in.readInt();
    +        right = in.readInt();
    +        bottom = in.readInt();
    +    }
    +}
    +
    + +

    The marshalling in the {@code Rect} class is pretty simple. Take a look at the other +methods on {@link android.os.Parcel} to see the other kinds of values you can write +to a Parcel.

    + +

    Warning: Don't forget the security implications of receiving +data from other processes. In this case, the {@code Rect} reads four numbers from the {@link +android.os.Parcel}, but it is up to you to ensure that these are within the acceptable range of +values for whatever the caller is trying to do. See Security and Permissions for more +information about how to keep your application secure from malware.

    + + + +

    Calling an IPC Method

    + +

    Here are the steps a calling class must take to call a remote interface defined with AIDL:

    +
      +
    1. Include the {@code .aidl} file in the project {@code src/} directory.
    2. +
    3. Declare an instance of the {@link android.os.IBinder} interface (generated based on the +AIDL).
    4. +
    5. Implement {@link android.content.ServiceConnection ServiceConnection}.
    6. +
    7. Call {@link +android.content.Context#bindService(android.content.Intent,android.content.ServiceConnection,int) + Context.bindService()}, passing in your {@link +android.content.ServiceConnection} implementation.
    8. +
    9. In your implementation of {@link +android.content.ServiceConnection#onServiceConnected onServiceConnected()}, +you will receive an {@link android.os.IBinder} instance (called service). Call +YourInterfaceName.Stub.asInterface((IBinder)service) to + cast the returned parameter to YourInterface type.
    10. +
    11. Call the methods that you defined on your interface. You should always trap + {@link android.os.DeadObjectException} exceptions, which are thrown when + the connection has broken; this will be the only exception thrown by remote + methods.
    12. +
    13. To disconnect, call {@link +android.content.Context#unbindService(android.content.ServiceConnection) + Context.unbindService()} with the instance of your interface.
    14. +
    +

    A few comments on calling an IPC service:

    +
      +
    • Objects are reference counted across processes.
    • +
    • You can send anonymous objects + as method arguments.
    • +
    + +

    For more information about binding to a service, read the Bound Services +document.

    + +

    Here is some sample code demonstrating calling an AIDL-created service, taken + from the Remote Service sample in the ApiDemos project.

    +

    {@sample development/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.java + calling_a_service}

    diff --git a/docs/html/tools/avd.html b/docs/html/tools/avd.html new file mode 100644 index 000000000000..1d314a10c714 --- /dev/null +++ b/docs/html/tools/avd.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/tools/building/building-cmdline.jd b/docs/html/tools/building/building-cmdline.jd new file mode 100644 index 000000000000..6154d96e6353 --- /dev/null +++ b/docs/html/tools/building/building-cmdline.jd @@ -0,0 +1,371 @@ +page.title=Building and Running from the Command Line +parent.title=Building and Running +parent.link=index.html +@jd:body + + + +

    There are two ways to build your application using the Ant build script: one for + testing/debugging your application — debug mode — and one for building your + final package for release — release mode. Regardless of which way you build your application, + it must be signed before it can install on an emulator or device—with a debug key when building + in debug mode and with your own private key when building in release mode.

    + +

    Whether you're building in debug mode or release mode, you need to use the Ant tool to compile + and build your project. This will create the .apk file that you can install on an emulator or device. + When you build in debug mode, the .apk file is automatically signed by the SDK tools with + a debug key, so it's instantly ready for installation onto an emulator or attached + development device. You cannot distribute an application that is signed with a debug key. + When you build in release mode, the .apk file is unsigned, so you + must manually sign it with your own private key, using Keytool and Jarsigner.

    + +

    It's important that you read and understand Signing Your Applications, particularly once + you're ready to release your application and share it with end-users. That document describes the + procedure for generating a private key and then using it to sign your .apk file. If you're just + getting started, however, you can quickly run your applications on an emulator or your own + development device by building in debug mode.

    + +

    If you don't have Ant, you can obtain it from the Apache Ant + home page. Install it and make sure it is in your executable PATH. Before calling Ant, you + need to declare the JAVA_HOME environment variable to specify the path to where the JDK is + installed.

    + +

    Note: When installing JDK on Windows, the default is to install + in the "Program Files" directory. This location will cause ant to fail, because of + the space. To fix the problem, you can specify the JAVA_HOME variable like this: +

    set JAVA_HOME=c:\Progra~1\Java\<jdkdir>
    + +

    The easiest solution, however, is to install JDK in a non-space directory, for example:

    + +
    c:\java\jdk1.6.0_02
    + +

    Building in Debug Mode

    + +

    For immediate application testing and debugging, you can build your application in debug mode + and immediately install it on an emulator. In debug mode, the build tools automatically sign your + application with a debug key and optimize the package with {@code zipalign}.

    + +

    To build in debug mode:

    + +
      +
    1. Open a command-line and navigate to the root of your project directory.
    2. +
    3. Use Ant to compile your project in debug mode: +
      +ant debug
      +
      + +

      This creates your debug .apk file inside the project bin/ directory, named + <your_project_name>-debug.apk. The file is already signed with + the debug key and has been aligned with + zipalign. +

      +
    4. +
    + +

    Each time you change a source file or resource, you must run Ant again in order to package up + the latest version of the application.

    + +

    To install and run your application on an emulator, see the following section about Running on the Emulator.

    + +

    Building in Release Mode

    + +

    When you're ready to release and distribute your application to end-users, you must build your + application in release mode. Once you have built in release mode, it's a good idea to perform + additional testing and debugging with the final .apk.

    + +

    Before you start building your application in release mode, be aware that you must sign the + resulting application package with your private key, and should then align it using the {@code + zipalign} tool. There are two approaches to building in release mode: build an unsigned package + in release mode and then manually sign and align the package, or allow the build script to sign + and align the package for you.

    + +

    Build unsigned

    + +

    If you build your application unsigned, then you will need to manually sign and align + the package.

    + +

    To build an unsigned .apk in release mode:

    + +
      +
    1. Open a command-line and navigate to the root of your project directory.
    2. + +
    3. Use Ant to compile your project in release mode: +
      +ant release
      +
      +
    4. +
    + +

    This creates your Android application .apk file inside the project bin/ + directory, named <your_project_name>-unsigned.apk.

    + +

    Note: The .apk file is unsigned at this point and can't + be installed until signed with your private key.

    + +

    Once you have created the unsigned .apk, your next step is to sign the .apk with your private + key and then align it with {@code zipalign}. To complete this procedure, read Signing Your Applications.

    + +

    When your .apk has been signed and aligned, it's ready to be distributed to end-users. + You should test the final build on different devices or AVDs to ensure that it + runs properly on different platforms.

    + +

    Build signed and aligned

    + +

    If you would like, you can configure the Android build script to automatically sign and align + your application package. To do so, you must provide the path to your keystore and the name of + your key alias in your project's {@code ant.properties} file. With this information provided, + the build script will prompt you for your keystore and alias password when you build in release + mode and produce your final application package, which will be ready for distribution.

    + +

    Caution: Due to the way Ant handles input, the password that + you enter during the build process will be visible. If you are concerned about + your keystore and alias password being visible on screen, then you may prefer to perform the + application signing manually, via Jarsigner (or a similar tool). To instead perform the signing + procedure manually, build unsigned and then continue with + Signing Your Applications.

    + +

    To specify your keystore and alias, open the project {@code ant.properties} file (found in + the root of the project directory) and add entries for {@code key.store} and {@code key.alias}. + For example:

    +
    +key.store=path/to/my.keystore
    +key.alias=mykeystore
    +
    + +

    Save your changes. Now you can build a signed .apk in release mode:

    + +
      +
    1. Open a command-line and navigate to the root of your project directory.
    2. + +
    3. Use Ant to compile your project in release mode: +
      +ant release
      +
      +
    4. + +
    5. When prompted, enter you keystore and alias passwords. + +

      Caution: As described above, your password will be + visible on the screen.

      +
    6. +
    + +

    This creates your Android application .apk file inside the project bin/ + directory, named <your_project_name>-release.apk. This .apk file has + been signed with the private key specified in {@code ant.properties} and aligned with {@code + zipalign}. It's ready for installation and distribution.

    + +

    Once built and signed in release mode

    + +

    Once you have signed your application with a private key, you can install and run it on an + emulator or device. You can + also try installing it onto a device from a web server. Simply upload the signed .apk to a web + site, then load the .apk URL in your Android web browser to download the application and begin + installation. (On your device, be sure you have enabled + Settings > Applications > Unknown sources.)

    + +

    Running on the Emulator

    + +

    Before you can run your application on the Android Emulator, you must create an AVD.

    + +

    To run your application:

    + +
      +
    1. + Open the AVD Manager and launch a virtual device + +

      From your SDK's platform-tools/ directory, execute the {@code android} tool +with the avd options:

      +
      +android avd
      +
      + +

      In the Virtual Devices view, select an AVD and click Start.

      +
    2. + +
    3. + Install your application + +

      From your SDK's tools/ directory, install the {@code .apk} on the + emulator:

      +
      +adb install <path_to_your_bin>.apk
      +
      + +

      Your .apk file (signed with either a release or debug key) is in your project {@code bin/} + directory after you build your application.

      + +

      If there is more than one emulator running, you must specify the emulator upon which to + install the application, by its serial number, with the -s option. For + example:

      +
      +adb -s emulator-5554 install path/to/your/app.apk
      +
      + +

      To see a list of available device serial numbers, execute {@code adb devices}.

      +
    4. +
    + +

    If you don't see your application on the emulator, try closing the emulator and launching the + virtual device again from the AVD Manager. Sometimes when you install an application for the + first time, it won't show up in the application launcher or be accessible by other applications. + This is because the package manager usually examines manifests completely only on emulator + startup.

    + +

    Be certain to create multiple AVDs upon which to test your application. You should have one + AVD for each platform and screen type with which your application is compatible. For instance, if + your application compiles against the Android 1.5 (API Level 3) platform, you should create an + AVD for each platform equal to and greater than 1.5 and an AVD for each screen type you support, then test your + application on each one.

    + +

    Tip: If you have only one emulator running, you can + build your application and install it on the emulator in one simple step. Navigate to the root of + your project directory and use Ant to compile the project with install mode: ant + install. This will build your application, sign it with the debug key, and install it on + the currently running emulator.

    + +

    Running on a Device

    + +

    Before you can run your application on a device, you must perform some basic setup for your + device:

    + +
      +
    • Enable USB Debugging on your device. You can find the setting on most Android devices by + going to Settings > Applications > Development > USB debugging.
    • + +
    • Ensure that your development computer can detect your device when connected via USB
    • +
    + +

    Read Setting up a Device for + Development for more information.

    + +

    Once your device is set up and connected via USB, navigate to your SDK's platform-tools/ + directory and install the .apk on the device:

    +
    +adb -d install path/to/your/app.apk
    +
    + +

    The {@code -d} flag specifies that you want to use the attached device (in case you also have + an emulator running).

    + +

    For more information on the tools used above, please see the following documents:

    + + + +

    Application Signing

    + +

    As you begin developing Android applications, understand that all Android applications must be + digitally signed before the system will install them on an emulator or device. There are two ways + to do this: with a debug key (for immediate testing on an emulator or development + device) or with a private key (for application distribution).

    + +

    The Android build tools help you get started by automatically signing your .apk files with a + debug key at build time. This means that you can compile your application and install it on the + emulator without having to generate your own private key. However, please note that if you intend + to publish your application, you must sign the application with your own private + key, rather than the debug key generated by the SDK tools.

    + +

    The ADT plugin helps you get started quickly by signing your .apk files with a debug key, + prior to installing them on an emulator or development device. This means that you can quickly + run your application from Eclipse without having to generate your own private key. No specific + action on your part is needed, provided ADT has access to Keytool. However, please note that if + you intend to publish your application, you must sign the application with your + own private key, rather than the debug key generated by the SDK tools.

    + +

    Please read Signing Your + Applications, which provides a thorough guide to application signing on Android and what it + means to you as an Android application developer. The document also includes a guide to exporting + and signing your application with the ADT's Export Wizard.

    + +

    Ant Command Reference

    +
    ant clean
    +
    Cleans the project. If you include the all target before clean +(ant all clean), other projects are also cleaned. For instance if you clean a +test project, the tested project is also cleaned.
    + +
    ant debug
    +
    Builds a debug package. Works on application, library, and test projects and compiles + dependencies as needed.
    + +
    ant emma debug
    +
    Builds a test project while building the tested project with instrumentation turned on. + This is used to run tests with code coverage enabled.
    + +
    ant release
    +
    Builds a release package.
    + +
    ant instrument +
    +
    Builds an instrumented debug package. This is generally called automatically when building a + test project with code coverage enabled (with the emma + target)
    + +
    ant <build_target> install
    +
    Builds and installs a package. Using install by itself fails.
    + +
    ant installd
    +
    Installs an already compiled debug package. This fails if the .apk is not + already built.
    + +
    ant installr
    +
    Installs an already compiled release package. This fails if the .apk is not + already built.
    + +
    ant installt
    +
    Installs an already compiled test package. Also installs the .apk of the + tested application. This fails if the .apk is not already built.
    + +
    ant installi
    +
    Installs an already compiled instrumented package. This is generally not used manually as + it's called when installing a test package. This fails if the .apk is not already + built.
    + +
    ant test
    +
    Runs the tests (for test projects). The tested and test .apk files must be + previously installed.
    + +
    ant debug installt test
    +
    Builds a test project and the tested project, installs both .apk files, and + runs the tests.
    + +
    ant emma debug install test
    +
    Builds a test project and the tested project, installs both .apk files, and + runs the tests with code coverage enabled.
    + diff --git a/docs/html/tools/building/building-eclipse.jd b/docs/html/tools/building/building-eclipse.jd new file mode 100644 index 000000000000..c73fe974410d --- /dev/null +++ b/docs/html/tools/building/building-eclipse.jd @@ -0,0 +1,165 @@ +page.title=Building and Running from Eclipse with ADT +parent.title=Building and Running +parent.link=index.html +@jd:body + + + +

    Eclipse and ADT provide an environment where most of the details of the build process are + hidden from you. By default, the build process constantly runs in the background as you make + changes to your project.

    + +

    When Eclipse automatically builds your application, it enables debugging and signs the + .apk with a debug key, by default. When you run the application, + Eclipse invokes ADB and installs your application to a device or emulator, so you do not have to + manually perform these tasks. Since most of the build process is taken care of by Eclipse, the + following topics show you how to run an application, which will automatically build your + application as well.

    + +

    To distribute your application, however, you must build your application in release mode and sign the + .apk file with your own private key.

    + +

    This document shows you how to run your application on an emulator or a real device + from Eclipse—all of which is done using the debug version of your application. + For more information about how to sign your application with a private key for release, see Signing Your Applications

    + +

    Running on the emulator

    + +

    Before you can run your application on the Android Emulator, you must create an AVD.

    + +

    To run (or debug) your application, select Run > Run (or + Run > Debug) from the Eclipse menu bar. The ADT plugin will + automatically create a default run configuration for the project. Eclipse will then perform the + following:

    + +
      +
    1. Compile the project (if there have been changes since the last build).
    2. + +
    3. Create a default run configuration (if one does not already exist for the project).
    4. + +
    5. Install and start the application on an emulator (or device), based on the Deployment + Target defined by the run configuration. + +

      By default, Android run configurations use an "automatic target" mode for selecting a + device target. For information on how automatic target mode selects a deployment target, see + Automatic and manual target modes below.

      +
    6. +
    + +

    If you run the application with the Debug option, the application will start in the "Waiting For Debugger" mode. Once the debugger + is attached, Eclipse opens the Debug perspective and starts the application's main activity. Otherwise, if you run the + application with the normal Run option, Eclipse installs the application on the device and launches the main activity.

    + +

    To set or change the run configuration used for your project, use the run configuration + manager. See the section below about Creating a Run Configuration for more information.

    + +

    Be certain to create multiple AVDs upon which to test your application. You should have one + AVD for each platform and screen type with which your application is compatible. For instance, if + your application compiles against the Android 1.5 (API Level 3) platform, you should create an + AVD for each platform equal to and greater than 1.5 and an AVD for each screen type you support, then test your + application on each one.

    + +

    Running on a device

    + +

    Before you can run your application on a device, you must perform some basic setup for your + device:

    + +
      +
    • Ensure that your application is debuggable by setting the + android:debuggable attribute of the <application> + element to true. As of ADT 8.0, this is done by default when you build in debug mode.
    • + +
    • Enable USB Debugging on your device. You can find the setting on most Android devices by + going to Settings > Applications > Development > USB debugging.
    • + +
    • Ensure that your development computer can detect your device when connected via USB
    • +
    + +

    Read Using Hardware Devices + for more information.

    + +

    Once set up and your device is connected via USB, install your application on the device by + selecting Run > Run (or Run > + Debug) from the Eclipse menu bar.

    + +

    Creating a Run Configuration

    + +

    The run configuration specifies the project to run, the Activity to start, the emulator or + connected device to use, and so on. When you first run a project as an Android + Application, ADT will automatically create a run configuration. The default run + configuration will launch the default project Activity and use automatic target mode for device + selection (with no preferred AVD). If the default settings don't suit your project, you can + customize the run configuration or even create a new one.

    + +

    To create or modify a run configuration, refer to the Eclipse documentation on how to create Run configurations. + The following steps highlight the important things you need to do for an Android project:

    + +
      +
    1. Open the run configuration manager from the Run Menu.
    2. + +
    3. Expand the Android Application item and create a new configuration or open + an existing one. +
    4. + +
    5. With the Run Configuration selected, adjust your desired run configuration settings: +
        +
      • In the Android tab, specify the Project and Activity to launch. +
      • +
      • In the Target tab, consider whether you'd like to use Manual or Automatic mode when + selecting an AVD to run your application. See the following section on Automatic and manual target modes).

        + +

        You can specify any emulator options to the Additional Emulator Command Line Options + field. For example, you could add -scale 96dpi to scale the AVD's screen to an + accurate size, based on the dpi of your computer monitor. For a full list of emulator + options, see the Android + Emulator document.

        +
      • +
      +
    6. +
    + +

    Automatic and manual target modes

    + +

    By default, a run configuration uses the automatic target mode in order to + select an AVD. In this mode, ADT will select an AVD for the application in the following + manner:

    + +
      +
    1. If there's a device or emulator already running and its AVD configuration meets the + requirements of the application's build target, the application is installed and run upon + it.
    2. + +
    3. If there's more than one device or emulator running, each of which meets the requirements + of the build target, a "device chooser" is shown to let you select which device to use.
    4. + +
    5. If there are no devices or emulators running that meet the requirements of the build + target, ADT looks at the available AVDs. If there is an AVD that matches the build target of the project, + ADT chooses that AVD. If the AVD versions are newer than the build target of the project, ADT chooses + the oldest possible version of an AVD that meets the project's build target requirement.
    6. + +
    7. If there are no suitable AVDs, the application is not installed a console error warning tells + you that there is no existing AVD that meets the build target requirements.
    8. +
    + +

    However, if a "preferred AVD" is selected in the run configuration, then the application will + always be deployed to that AVD. If it's not already running, then a new emulator will be + launched.

    + +

    If your run configuration uses manual mode, then the "device chooser" is + presented every time that your application is run, so that you can select which AVD to use.

    \ No newline at end of file diff --git a/docs/html/tools/building/index.jd b/docs/html/tools/building/index.jd new file mode 100644 index 000000000000..c64942ff7d25 --- /dev/null +++ b/docs/html/tools/building/index.jd @@ -0,0 +1,81 @@ +page.title=Building and Running +@jd:body + +
    +
    +

    In this document

    +
      +
    1. A Detailed Look at the Build Process
    2. +
    +
    +
    + +

    During the build process, your Android projects are compiled and packaged into an .apk file, + the container for your application binary. It contains all of the information necessary to run + your application on a device or emulator, such as compiled .dex files (.class files + converted to Dalvik byte code), a binary version of the AndroidManifest.xml file, compiled + resources (resources.arsc) and uncompiled resource files for your application.

    + +

    If you are developing in Eclipse, the ADT plugin incrementally builds your project as you + make changes to the source code. Eclipse outputs an .apk file automatically to the bin folder of + the project, so you do not have to do anything extra to generate the .apk.

    + +

    If you are developing in a non-Eclipse environment, you can build your project with the + generated build.xml Ant file that is in the project directory. The Ant file calls targets that + automatically call the build tools for you.

    + +

    To run an application on an emulator or device, the application must be signed using debug or + release mode. You typically want to sign your application in debug mode when you develop and test + your application, because the build tools use a debug key with a known password so you do not have + to enter it every time you build. When you are ready to release the application to Google + Play, you must sign the application in release mode, using your own private key.

    + +

    Fortunately, Eclipse or your Ant build script signs the application for you in debug mode + when you build your application. You can also easily setup Eclipse or your Ant build to sign your + application in release mode as well. For more information on signing applications, see Signing Your Applications.

    + +

    The following diagram depicts the components involved in building and running an application:

    + + + +

    A Detailed Look at the Build Process

    + +

    The build process involves many tools and processes that generate intermediate files on the + way to producing an .apk. If you are developing in Eclipse, the complete build process is + automatically done periodically as you develop and save your code changes. If you are using other + IDEs, this build process is done every time you run the generated Ant build script for your + project. It is useful, however, to understand what is happening under the hood since much of the + tools and processes are masked from you. The following diagram depicts the different tools and + processes that are involved in a build:

    + + + +

    The general process for a typical build is outlined below:

    + +
      + +
    • The Android Asset Packaging Tool (aapt) takes your application resource files, such as the + AndroidManifest.xml file and the XML files for your Activities, and compiles them. An R.java is + also produced so you can reference your resources from your Java code.
    • + +
    • The aidl tool converts any .aidl interfaces that you have into Java interfaces.
    • + +
    • All of your Java code, including the R.java and .aidl files, are compiled by the Java + compiler and .class files are output.
    • + +
    • The dex tool converts the .class files to Dalvik byte code. Any 3rd party libraries and + .class files that you have included in your project are also converted into .dex files so that + they can be packaged into the final .apk file.
    • + +
    • All non-compiled resources (such as images), compiled resources, and the .dex files are + sent to the apkbuilder tool to be packaged into an .apk file.
    • + +
    • Once the .apk is built, it must be signed with either a debug or release key before it can + be installed to a device.
    • + +
    • Finally, if the application is being signed in release mode, you must align the .apk with + the zipalign tool. Aligning the final .apk decreases memory usage when the application is + running on a device.
    • +
    + diff --git a/docs/html/tools/debug-tasks.html b/docs/html/tools/debug-tasks.html new file mode 100644 index 000000000000..2a5bc511242e --- /dev/null +++ b/docs/html/tools/debug-tasks.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/tools/debugging/ddms.jd b/docs/html/tools/debugging/ddms.jd new file mode 100644 index 000000000000..3d6324b7a7e9 --- /dev/null +++ b/docs/html/tools/debugging/ddms.jd @@ -0,0 +1,357 @@ +page.title=Using DDMS +parent.title=Debugging +parent.link=index.html +@jd:body + + + +

    Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which + provides port-forwarding services, screen capture on the device, thread and heap information on + the device, logcat, process, and radio state information, incoming call and SMS spoofing, + location data spoofing, and more. This page provides a modest discussion of DDMS features; it is + not an exhaustive exploration of all the features and capabilities.

    + +

    Running DDMS

    +

    DDMS is integrated into Eclipse and is also shipped in the tools/ directory of the + SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, + DDMS defaults to the emulator.

    + +
      +
    • From Eclipse: Click Window > Open Perspective > Other... > DDMS.
    • +
    • From the command line: Type ddms (or ./ddms on Mac/Linux) from the tools/ + directory.
    • +
    + + +

    How DDMS Interacts with a Debugger

    + +

    On Android, every application runs in its own process, each of which runs in its own virtual machine + (VM). Each VM exposes a unique port that a debugger can attach to.

    + +

    When DDMS starts, it connects to adb. + When a device is connected, a VM monitoring service is created between + adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM + is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a connection to the + VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a + custom wire protocol.

    + +

    DDMS assigns a debugging port to each VM on the device. Typically, + DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger + connects to one of these ports, all traffic is forwarded to the debugger from the associated + VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached + debuggers.

    + +

    By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by default). + The base port is a port forwarder, which can accept VM traffic from any debugging port and forward + it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug + all the VMs on a device. The traffic that is forwarded is determined by the currently selected process + in the DDMS Devices view.

    + +

    The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS from + the command line, the screen is slightly different, but much of the functionality is identical. + Notice that the highlighted process, com.android.email, that is running in the emulator + has the debugging port 8700 assigned to it as well as 8606. This signifies that DDMS is currently + forwarding port 8606 to the static debugging port of 8700.

    + + +

    Figure 1. + Screenshot of DDMS

    + +

    If you are not using Eclipse and ADT, read Configuring + your IDE to attach to the debugging port, for more information on attaching your + debugger.

    + +

    Tip: You can set a number of DDMS preferences in + File > Preferences. Preferences are saved to + $HOME/.android/ddms.cfg.

    + +

    Known debugging issues with Dalvik
    + Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, + when single-stepping out of synchronized code, the "current line" cursor may jump to the last + line in the method for one step.

    + +

    Using DDMS

    + The following sections describe how to use DDMS and the various tabs and panes that are part of the + DDMS GUI. The Eclipse version and the command line version have minor UI differences, but the + same functionality. For information on running DDMS, see the previous section in this document, + Running DDMS. + + +

    Viewing heap usage for a process

    + +

    DDMS allows you to view how much heap memory a process is using. This information is useful in + tracking heap usage at a certain point of time during the execution of your application.

    +

    To view heap usage for a process:

    +
      +
    1. In the Devices tab, select the process that you want to see the heap information for.
    2. + +
    3. Click the Update Heap button to enable heap information for the + process.
    4. + +
    5. In the Heap tab, click Cause GC to invoke garbage collection, which + enables the collection of heap data. When the operation completes, you will see a group of + object types and the memory that has been allocated for each type. You can click Cause + GC again to refresh the data.
    6. + +
    7. Click on an object type in the list to see a bar graph that shows the number of objects + allocated for a particular memory size in bytes.
    8. +
    + +

    Tracking memory allocation of objects

    + +

    DDMS provides a feature to track objects that are being allocated to memory and to see which + classes and threads are allocating the objects. This allows you to track, in real time, where + objects are being allocated when you perform certain actions in your application. This + information is valuable for assessing memory usage that can affect application performance. +

    + +

    To track memory allocation of objects:

    +
      +
    1. In the Devices tab, select the process that you want to enable allocation tracking + for.
    2. + +
    3. In the Allocation Tracker tab, click the Start Tracking button to begin + allocation tracking. At this point, anything you do in your application will be tracked.
    4. + +
    5. Click Get Allocations to see a list of objects that have been allocated + since you clicked on the Start Tracking button. You can click on Get + Allocations again to append to the list new objects that that have been + allocated.
    6. + +
    7. To stop tracking or to clear the data and start over, click the Stop Tracking + button.
    8. + +
    9. Click on a specific row in the list to see more detailed information such as the method and + line number of the code that allocated the object.
    10. +
    + +

    Working with an emulator or device's file system

    + +

    DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the + device. This feature is useful in examining files that are created by your application or if you + want to transfer files to and from the device.

    + +

    To work with an emulator or device's file system:

    +
      +
    1. In the Devices tab, select the emulator that you want to view the file system for.
    2. + +
    3. To copy a file from the device, locate the file in the File Explorer and click the + Pull file button.
    4. + +
    5. To copy a file to the device, click the Push file button on the File + Explorer tab.
    6. +
    + + + +

    Examining thread information

    + +

    The Threads tab in DDMS shows you the currently running threads for a selected process.

    + +
      +
    1. In the Devices tab, select the process that you want to examine the threads for.
    2. + +
    3. Click the Update Threads button.
    4. + +
    5. In the Threads tab, you can view the thread information for the selected process.
    6. +
    + +

    Starting method profiling

    + +

    Method profiling is a means to track certain metrics about a method, such as number of calls, + execution time, and time spent executing the method. If you want more granular control over + where profiling data is collected, use the {@link android.os.Debug#startMethodTracing()} and + {@link android.os.Debug#stopMethodTracing()} methods. For more information about generating trace logs, see + Profiling and Debugging UIs.

    + +

    Before you start method profiling in DDMS, be aware of the following restrictions:

    +
      +
    • Android 1.5 devices are not supported.
    • +
    • Android 2.1 and earlier devices must + have an SD card present and your application must have permission to write to the SD card. +
    • Android 2.2 and later devices do not need an SD card. The trace log files are + streamed directly to your development machine.
    • +
    + +

    To start method profiling:

    +
      +
    1. On the Devices tab, select the process that you want to enable method profiling for.
    2. + +
    3. Click the Start Method Profiling button.
    4. + +
    5. Interact with your application to start the methods that you want to profile.
    6. + +
    7. Click the Stop Method Profiling button. DDMS stops profiling your + application and opens Traceview + with the method profiling information that was collected + between the time you clicked on Start Method Profiling and Stop Method + Profiling.
    8. +
    + +

    Using the Network Traffic tool

    + +

    In Android 4.0, the DDMS (Dalvik Debug Monitor Server) includes a Detailed +Network Usage tab that makes it possible to track when your application is +making network requests. Using this tool, you can monitor how and when your app +transfers data and optimize the underlying code appropriately. You can also +distinguish between different traffic types by applying a “tag” to network +sockets before use.

    + +

    These tags are shown in a stack area chart in DDMS, as shown in figure 2:

    + + +

    Figure 2. Network Usage tab.

    + +

    By monitoring the frequency of your data transfers, and the amount of data +transferred during each connection, you can identify areas of your application +that can be made more battery-efficient. Generally, you should look for +short spikes that can be delayed, or that should cause a later transfer to be +pre-empted.

    + +

    To better identify the cause of transfer spikes, the +{@link android.net.TrafficStats} API allows you +to tag the data transfers occurring within a thread using {@link +android.net.TrafficStats#setThreadStatsTag setThreadStatsTag()}, followed +by manually tagging (and untagging) individual sockets using {@link +android.net.TrafficStats#tagSocket tagSocket()} and {@link +android.net.TrafficStats#untagSocket untagSocket()}. For example:

    + +
    TrafficStats.setThreadStatsTag(0xF00D);
    +TrafficStats.tagSocket(outputSocket);
    +// Transfer data using socket
    +TrafficStats.untagSocket(outputSocket);
    + +

    Alternatively, the Apache {@link org.apache.http.client.HttpClient} and +{@link java.net.URLConnection} APIs included in the platform +automatically tag sockets internally based on the active tag (as +identified by +{@link android.net.TrafficStats#getThreadStatsTag getThreadStatsTag()}). +These APIs correctly tag/untag sockets when recycled through +keep-alive pools. In the following example, +{@link android.net.TrafficStats#setThreadStatsTag setThreadStatsTag()} +sets the active tag to be {@code 0xF00D}. +There can only be one active tag per thread. +That is the value that will +be returned by {@link android.net.TrafficStats#getThreadStatsTag getThreadStatsTag()} +and thus used by {@link org.apache.http.client.HttpClient} + to tag sockets. The {@code finally} statement +invokes +{@link android.net.TrafficStats#clearThreadStatsTag clearThreadStatsTag()} +to clear the tag.

    + +
    TrafficStats.setThreadStatsTag(0xF00D);
    +    try {
    +        // Make network request using HttpClient.execute()
    +    } finally {
    +        TrafficStats.clearThreadStatsTag();
    +}
    + +

    Socket tagging is supported in Android 4.0, but real-time stats will only be +displayed on devices running Android 4.0.3 or higher.

    + +

    Using LogCat

    + +

    LogCat is integrated into DDMS, and outputs the messages that you print out using the {@link android.util.Log} + class along with other system messages such as stack traces when exceptions are thrown. View the + Reading and + Writing Log Messages. topic for more information on how to log messages to the LogCat.

    + +

    When you have set up your logging, you can use the LogCat feature of DDMS to filter certain + messages with the following buttons:

    + +
      +
    • Verbose
    • + +
    • Debug
    • + +
    • Info
    • + +
    • Warn
    • + +
    • Error
    • +
    + +

    You can also setup your own custom filter to specify more details such as filtering messages + with the log tags or with the process id that generated the log message. The add filter, + edit filter, and delete filter buttons let you manage your custom filters.

    + +

    Emulating phone operations and location

    +

    The Emulator control tab lets you simulate a + phone's voice and data network status. This is useful when you want to test your application's + robustness in differing network environments.

    + +

    Changing network state, speed, and latency

    +

    The Telephony Status section of the Emulator + controls tab lets you change different aspects of the phone's networks status, speed and latency. + The following options are available to you and are effective immediately after you set them:

    + +
      +
    • Voice - unregistered, home, roaming, searching, denied
    • + +
    • Data - unregistered, home, roaming, searching, denied
    • + +
    • Speed - Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPA
    • + +
    • Latency - GPRS, EDGE, UMTS
    • +
    + +

    Spoofing calls or SMS text messages

    +

    The Telephony Actions section of the Emulator + controls tab lets you spoof calls and messages. This is useful when you want to to test your + application's robustness in responding to incoming calls and messages that are sent to the phone. + The following actions are available to you:

    + +
      +
    • Voice - Enter a number in the Incoming number field and click + Call to send a simulated call to the emulator or phone. Click the + Hang up button to terminate the call.
    • + +
    • SMS - Enter a number in the Incoming number field and a message in the + Message: field and click the Send button to send the + message.
    • +
    + +

    Setting the location of the phone

    +

    If your application depends on the location of the phone, you can have DDMS send your + device or AVD a mock location. This is useful if you + want to test different aspects of your application's location specific features without + physically moving. The following geolocation data types are available to you:

    + +
      +
    • Manual - set the location by manually specifying decimal or sexagesimal longitude and + latitude values.
    • + +
    • GPX - GPS eXchange file
    • + +
    • KML - Keyhole Markup Language file
    • +
    + + For more information about providing mock location data, see + Location Strategies. + diff --git a/docs/html/tools/debugging/debugging-devtools.jd b/docs/html/tools/debugging/debugging-devtools.jd new file mode 100644 index 000000000000..3a051200422b --- /dev/null +++ b/docs/html/tools/debugging/debugging-devtools.jd @@ -0,0 +1,77 @@ +page.title=Using the Dev Tools App +parent.title=Debugging +parent.link=index.html +@jd:body + +

    The Dev Tools application is installed by default on all system images included with the SDK, + so you can use it with the Android Emulator. With the Dev Tools application, you can enable a + number of settings on your device that will make it easier to test and debug your applications.

    + +

    The Dev Tools application relies on a number of permissions that are not available for + third party applications. If you'd like to install the Dev Tools application + on a real development device, you'd have to build a system image for that device and sign + the Dev Tools application with the same key as used for the system image.

    + +

    To get started, launch the Dev Tools application and select Development Settings. This will + open the Development Settings page with the following options (among others):

    + +
    +
    Debug app
    + +
    + Lets you select the application to debug. You do not need to set this to attach a debugger, + but setting this value has two effects: + +
      +
    • It will prevent Android from throwing an error if you pause on a breakpoint for a long + time while debugging.
    • + +
    • It will enable you to select the Wait for Debugger option to pause application + startup until your debugger attaches (described next).
    • +
    +
    + +
    Wait for debugger
    + +
    Blocks the selected application from loading until a debugger attaches. This way you can + set a breakpoint in {@link android.app.Activity#onCreate onCreate()}, + which is important to debug the startup process of an Activity. + When you change this option, any currently running instances of the selected application will + be killed. In order to check this box, you must have selected a debug application as described + in the previous option. You can do the same thing by adding {@link + android.os.Debug#waitForDebugger()} to your code.
    + +
    Show screen updates
    + +
    Flashes a momentary pink rectangle on any screen sections that are being redrawn. This is + very useful for discovering unnecessary screen drawing.
    + +
    Immediately destroy activities
    + +
    Tells the system to destroy an activity as soon as it is stopped (as if Android had to + reclaim memory).  This is very useful for testing the {@link + android.app.Activity#onSaveInstanceState} / {@link + android.app.Activity#onCreate(android.os.Bundle)} code path, which would otherwise be difficult + to force. Choosing this option will probably reveal a number of problems in your application + due to not saving state. For more information about saving an activity's state, see the + Activities +document.
    + +
    Show CPU usage
    + +
    Displays CPU meters at the top of the screen, showing how much the CPU is being used. The + top red bar shows overall CPU usage, and the green bar underneath it shows the CPU time spent + in compositing the screen. +

    Note: You cannot turn this feature off once it is on, without + restarting the emulator.

    + +
    Show background
    + +
    Displays a background pattern when no activity screens are visible. This typically does not + happen, but can happen during debugging.
    +
    + +

    These settings will be remembered across emulator restarts.

    + + + diff --git a/docs/html/tools/debugging/debugging-log.jd b/docs/html/tools/debugging/debugging-log.jd new file mode 100644 index 000000000000..d2baaf26ce84 --- /dev/null +++ b/docs/html/tools/debugging/debugging-log.jd @@ -0,0 +1,308 @@ +page.title=Reading and Writing Logs +parent.title=Debugging +parent.link=index.html +@jd:body + + + +

    The Android logging system provides a mechanism for collecting and viewing system debug + output. Logcat dumps a log of system messages, which include things such as stack traces when the + emulator throws an error and messages that you have written from your application by using the + {@link android.util.Log} class. You can run LogCat through ADB or from DDMS, which allows you to + read the messages in real time.

    + +

    The Log class

    + +

    {@link android.util.Log} is a logging class that you can utilize in your code to print out + messages to the LogCat. Common logging methods include:

    + +
      +
    • {@link android.util.Log#v(String,String)} (verbose)
    • + +
    • {@link android.util.Log#d(String,String)} (debug)
    • + +
    • {@link android.util.Log#i(String,String)} (information)
    • + +
    • {@link android.util.Log#w(String,String)} (warning)
    • + +
    • {@link android.util.Log#e(String,String)} (error)
    • +
    For example: +
    +Log.i("MyActivity", "MyClass.getView() — get item number " + position);
    +
    + +

    The LogCat will then output something like:

    +
    +I/MyActivity( 1557): MyClass.getView() — get item number 1
    +
    + +

    Using LogCat

    + +

    You can use LogCat from within DDMS or call it on an ADB shell. For more information on how to + use LogCat within DDMS, see Using + DDMS. To run LogCat, through the ADB shell, the general usage is:

    +
    +[adb] logcat [<option>] ... [<filter-spec>] ...
    +
    + +

    You can use the logcat command from your development computer or from a remote + adb shell in an emulator/device instance. To view log output in your development computer, you + use

    +
    +$ adb logcat
    +
    + +

    and from a remote adb shell you use

    +
    +# logcat
    +
    + +

    The following table describes the logcat command line options:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    -cClears (flushes) the entire log and exits.
    -dDumps the log to the screen and exits.
    -f <filename>Writes log message output to <filename>. The default is + stdout.
    -gPrints the size of the specified log buffer and exits.
    -n <count>Sets the maximum number of rotated logs to <count>. The default value + is 4. Requires the -r option.
    -r <kbytes>Rotates the log file every <kbytes> of output. The default value is + 16. Requires the -f option.
    -sSets the default filter spec to silent.
    -v <format>Sets the output format for log messages. The default is brief format. For a + list of supported formats, see Controlling Log Output + Format.
    + +

    Filtering Log Output

    + +

    Every Android log message has a tag and a priority associated with it.

    + +
      +
    • The tag of a log message is a short string indicating the system component from which the + message originates (for example, "View" for the view system).
    • + +
    • The priority is one of the following character values, ordered from lowest to highest + priority:
    • + +
    • +
        +
      • V — Verbose (lowest priority)
      • + +
      • D — Debug
      • + +
      • I — Info
      • + +
      • W — Warning
      • + +
      • E — Error
      • + +
      • F — Fatal
      • + +
      • S — Silent (highest priority, on which nothing is ever printed)
      • +
      +
    • +
    + +

    You can obtain a list of tags used in the system, together with priorities, by running + LogCat and observing the first two columns of each message, given as + <priority>/<tag>.

    + +

    Here's an example of logcat output that shows that the message relates to priority level "I" + and tag "ActivityManager":

    +
    +I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}
    +
    + +

    To reduce the log output to a manageable level, you can restrict log output using filter + expressions. Filter expressions let you indicate to the system the tags-priority + combinations that you are interested in — the system suppresses other messages for the + specified tags.

    + +

    A filter expression follows this format tag:priority ..., where tag + indicates the tag of interest and priority indicates the minimum level of + priority to report for that tag. Messages for that tag at or above the specified priority are + written to the log. You can supply any number of tag:priority specifications in a + single filter expression. The series of specifications is whitespace-delimited.

    + +

    Here's an example of a filter expression that suppresses all log messages except those with + the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", + with priority "Debug" or above:

    +
    +adb logcat ActivityManager:I MyApp:D *:S
    +
    + +

    The final element in the above expression, *:S, sets the priority level for all + tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using + *:S is an excellent way to ensure that log output is restricted to the filters that + you have explicitly specified — it lets your filters serve as a "whitelist" for log + output.

    + +

    The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

    +
    +adb logcat *:W
    +
    + +

    If you're running LogCat from your development computer (versus running it on a + remote adb shell), you can also set a default filter expression by exporting a value for the + environment variable ANDROID_LOG_TAGS:

    +
    +export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"
    +
    + +

    Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device + instance, if you are running LogCat from a remote shell or using adb shell + logcat.

    + +

    Controlling Log Output Format

    + +

    Log messages contain a number of metadata fields, in addition to the tag and priority. You can + modify the output format for messages so that they display a specific metadata field. To do so, + you use the -v option and specify one of the supported output formats listed + below.

    + +
      +
    • brief — Display priority/tag and PID of the process issuing the + message (the default format).
    • + +
    • process — Display PID only.
    • + +
    • tag — Display the priority/tag only.
    • + +
    • raw — Display the raw log message, with no other metadata fields.
    • + +
    • time — Display the date, invocation time, priority/tag, and PID of the + process issuing the message.
    • + +
    • threadtime — Display the date, invocation time, priority, tag, and + the PID and TID of the thread issuing the message.
    • + +
    • long — Display all metadata fields and separate messages with blank + lines.
    • +
    + +

    When starting LogCat, you can specify the output format you want by using the + -v option:

    +
    +[adb] logcat [-v <format>]
    +
    + +

    Here's an example that shows how to generate messages in thread output + format:

    +
    +adb logcat -v thread
    +
    + +

    Note that you can only specify one output format with the -v option.

    + +

    Viewing Alternative Log Buffers

    + +

    The Android logging system keeps multiple circular buffers for log messages, and not all of + the log messages are sent to the default circular buffer. To see additional log messages, you can + run the logcat command with the -b option, to request viewing of an alternate + circular buffer. You can view any of these alternate buffers:

    + +
      +
    • radio — View the buffer that contains radio/telephony related + messages.
    • + +
    • events — View the buffer containing events-related messages.
    • + +
    • main — View the main log buffer (default)
    • +
    + +

    The usage of the -b option is:

    +
    +[adb] logcat [-b <buffer>]
    +
    + +

    Here's an example of how to view a log buffer containing radio and telephony messages:

    +
    +adb logcat -b radio
    +
    + +

    Viewing stdout and stderr

    + +

    By default, the Android system sends stdout and stderr + (System.out and System.err) output to /dev/null. In + processes that run the Dalvik VM, you can have the system write a copy of the output to the log + file. In this case, the system writes the messages to the log using the log tags + stdout and stderr, both with priority I.

    + +

    To route the output in this way, you stop a running emulator/device instance and then use the + shell command setprop to enable the redirection of output. Here's how you do it:

    +
    +$ adb shell stop
    +$ adb shell setprop log.redirect-stdio true
    +$ adb shell start
    +
    + +

    The system retains this setting until you terminate the emulator/device instance. To use the + setting as a default on the emulator/device instance, you can add an entry to + /data/local.prop on the device.

    + +

    Debugging Web Apps

    +

    + If you're developing a web application for Android, you can debug your JavaScript using the console JavaScript APIs, + which output messages to LogCat. For more information, see + Debugging Web Apps.

    diff --git a/docs/html/tools/debugging/debugging-projects-cmdline.jd b/docs/html/tools/debugging/debugging-projects-cmdline.jd new file mode 100644 index 000000000000..0b79575903a3 --- /dev/null +++ b/docs/html/tools/debugging/debugging-projects-cmdline.jd @@ -0,0 +1,78 @@ +page.title=Debugging from Other IDEs +parent.title=Debugging +parent.link=index.html +@jd:body + + + + +

    If you are not using Eclipse to develop, you can still take advantage of all the tools that + the Android SDK provides for debugging. A basic debugging environment consists of:

    + +
      +
    • ADB
    • + +
    • DDMS
    • + +
    • Java Debugger
    • +
    + +

    You need to obtain a JDWP-compliant Java debugger to properly debug your application. + Most Java IDEs will already have one included, or you can use a command line debugger, + such as JDB, if you are using a simple text editor to develop applications.

    + +

    Starting a debugging environment

    +

    A Java Debugger assists you in finding problems with + your code by letting you set breakpoints, step through execution of your application, and examine + variable values. Since you are not using Eclipse, you have to manually start up the debugging + environment yourself by running a few tools that are provided in the Android SDK. To begin + debugging your application, follow these general steps:

    + +
      +
    1. Load an AVD with the Android emulator or connect a device to your computer.
    2. + +
    3. Start DDMS from the sdk /tools directory. This also starts ADB if it is + not already started. You should see your device appear in DDMS.
    4. + +
    5. Install and run your .apk file on the device or emulator. In DDMS, you should see your + application running under the device that you installed it to.
    6. + +
    7. Attach your debugger to the debugging port 8700, or to the specific port shown for the + application in DDMS.
    8. +
    + +

    Configuring Your IDE to Attach to the Debugging Port

    + +

    DDMS assigns a specific debugging port to every virtual machine that it finds on the + emulator. You must either attach your IDE to that port (listed on the Info tab for that VM), or + you can use a default port 8700 to connect to whatever application is currently selected on the + list of discovered virtual machines.

    + +

    Your IDE should attach to your application running on the emulator, showing you its threads + and allowing you to suspend them, inspect their state, and set breakpoints. If you selected "Wait + for debugger" in the Development settings panel the application will run when Eclipse connects, + so you will need to set any breakpoints you want before connecting.

    + +

    Changing either the application being debugged or the "Wait for debugger" option causes the + system to kill the selected application if it is currently running. You can use this to kill your + application if it is in a bad state by simply going to the settings and toggling the + checkbox.

    + + + + + + + diff --git a/docs/html/tools/debugging/debugging-projects.jd b/docs/html/tools/debugging/debugging-projects.jd new file mode 100644 index 000000000000..2283f8be9f6d --- /dev/null +++ b/docs/html/tools/debugging/debugging-projects.jd @@ -0,0 +1,67 @@ +page.title=Debugging from Eclipse with ADT +parent.title=Debugging +parent.link=index.html +@jd:body + +
    +
    +

    In this document

    + +
      +
    1. The Debug Perspective
    2. + +
    3. The DDMS Perspective
    4. +
    +
    +
    + +

    If you are developing in Eclipse with the ADT plugin, you can use the built-in Java Debugger, + along with DDMS, to debug your applications. To access the debugger and + DDMS, Eclipse displays the debugger and DDMS features as perspectives, which are customized + Eclipse views that display certain tabs and windows depending on the perspective that you are in. + Eclipse also takes care of starting the ADB host daemon for you, so you do not have to run this + manually.

    + +

    The Debug Perspective in Eclipse

    + +

    The Debug Perspective in Eclipse gives you access to the following tabs:

    + +
      +
    • Debug - Displays previously and currently debugged Android applications and its currently + running threads
    • + +
    • Variables - When breakpoints are set, displays variable values during code execution
    • + +
    • Breakpoints - Displays a list of the set breakpoints in your application code
    • + +
    • LogCat - Allows you to view system log messages in real time. The LogCat tab is also + available in the DDMS perspective.
    • +
    +

    You can access the Debug Perspective by clicking Window > Open Perspective > + Debug. Refer to the appropriate documentation for the Eclipse debugger for more + information.

    + +

    The DDMS Perspective

    +

    The DDMS Perspective in Eclipse lets you access all of the features + of DDMS from within the Eclipse IDE. The following sections of DDMS are available to you:

    + +
      +
    • Devices - Shows the list of devices and AVDs that are connected to ADB.
    • + +
    • Emulator Control - Lets you carry out device functions.
    • + +
    • LogCat - Lets you view system log messages in real time.
    • + +
    • Threads - Shows currently running threads within a VM.
    • + +
    • Heap - Shows heap usage for a VM.
    • + +
    • Allocation Tracker - Shows the memory allocation of objects.
    • + +
    • File Explorer - Lets you explore the device's file system.
    • +
    +

    To access the DDMS perspective, go to Window > Open Perspective > + DDMS. If DDMS does not appear, go to Window > Open Perspective > Other + ... and select DDMS from the Open Perspective window that appears. For + more information on using DDMS, see Using the Dalvik Debug Monitor Server. +

    \ No newline at end of file diff --git a/docs/html/tools/debugging/debugging-tracing.jd b/docs/html/tools/debugging/debugging-tracing.jd new file mode 100644 index 000000000000..f0d0c0b52d6e --- /dev/null +++ b/docs/html/tools/debugging/debugging-tracing.jd @@ -0,0 +1,402 @@ +page.title=Profiling with Traceview and dmtracedump +parent.title=Debugging +parent.link=index.html +@jd:body + + + +

    Traceview is a graphical viewer for execution logs that you create by using the {@link + android.os.Debug} class to log tracing information in your code. Traceview can help you debug + your application and profile its performance.

    + +

    Traceview Layout

    + +

    When you have a trace log file (generated by adding tracing code to your application or by DDMS), + you can have Traceview load the log files and display their data in a window visualizes your application + in two panels:

    + +
      +
    • A timeline panel -- describes when each thread and method + started and stopped
    • + +
    • A profile panel -- provides a summary of what happened inside + a method
    • +
    + +

    The sections below provide addition information about the traceview output panes.

    + +

    Timeline Panel

    + +

    The image below shows a close up of the timeline panel. Each thread’s execution is shown + in its own row, with time increasing to the right. Each method is shown in another color (colors + are reused in a round-robin fashion starting with the methods that have the most inclusive time). + The thin lines underneath the first row show the extent (entry to exit) of all the calls to the + selected method. The method in this case is LoadListener.nativeFinished() and it was selected in + the profile view.

    + + Traceview timeline panel +

    Figure 1. The Traceview Timeline Panel

    + +

    Profile Panel

    + +

    Figure 2 shows the profile pane, a summary of all the time spent + in a method. The table shows both the inclusive and exclusive times (as well as the percentage of + the total time). Exclusive time is the time spent in the method. Inclusive time is the time spent + in the method plus the time spent in any called functions. We refer to calling methods as + "parents" and called methods as "children." When a method is selected (by clicking on it), it + expands to show the parents and children. Parents are shown with a purple background and children + with a yellow background. The last column in the table shows the number of calls to this method + plus the number of recursive calls. The last column shows the number of calls out of the total + number of calls made to that method. In this view, we can see that there were 14 calls to + LoadListener.nativeFinished(); looking at the timeline panel shows that one of those calls took + an unusually long time.

    + + Traceview profile panel. +

    Figure 2. The Traceview Profile Panel

    + +

    Traceview File Format

    + +

    Tracing creates two distinct pieces of output: a data file, which holds the trace + data, and a key file, which provides a mapping from binary identifiers to thread and + method names. The files are concatenated when tracing completes, into a single .trace + file.

    + +

    Note: The previous version of Traceview did not concatenate + these files for you. If you have old key and data files that you'd still like to trace, you can + concatenate them yourself with cat mytrace.key mytrace.data > + mytrace.trace.

    + +

    Data File Format

    + +

    The data file is binary, structured as follows (all values are stored in little-endian + order):

    +
    +* File format:
    +* header
    +* record 0
    +* record 1
    +* ...
    +*
    +* Header format:
    +* u4 magic 0x574f4c53 ('SLOW')
    +* u2 version
    +* u2 offset to data
    +* u8 start date/time in usec
    +*
    +* Record format:
    +* u1 thread ID
    +* u4 method ID | method action
    +* u4 time delta since start, in usec
    +
    + +

    The application is expected to parse all of the header fields, then seek to "offset to data" + from the start of the file. From there it just reads 9-byte records until EOF is reached.

    + +

    u8 start date/time in usec is the output from gettimeofday(). It's mainly there so + that you can tell if the output was generated yesterday or three months ago.

    + +

    method action sits in the two least-significant bits of the method word. The + currently defined meanings are:

    + +
      +
    • 0 - method entry
    • + +
    • 1 - method exit
    • + +
    • 2 - method "exited" when unrolled by exception handling
    • + +
    • 3 - (reserved)
    • +
    + +

    An unsigned 32-bit integer can hold about 70 minutes of time in microseconds.

    + +

    Key File Format

    + +

    The key file is a plain text file divided into three sections. Each section starts with a + keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start + of a new section.

    + +

    An example file might look like this:

    +
    +*version
    +1
    +clock=global
    +*threads
    +1 main
    +6 JDWP Handler
    +5 Async GC
    +4 Reference Handler
    +3 Finalizer
    +2 Signal Handler
    +*methods
    +0x080f23f8 java/io/PrintStream write ([BII)V
    +0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V
    +0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V
    +0x080da620 java/lang/RuntimeException   <init>    ()V
    +[...]
    +0x080f630c android/os/Debug startMethodTracing ()V
    +0x080f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String;I)V
    +*end
    +
    +

    The following list describes the major sections of a key file:

    +
    +
    version section
    + +
    The first line is the file version number, currently 1. The second line, + clock=global, indicates that we use a common clock across all threads. A future + version may use per-thread CPU time counters that are independent for every thread.
    + +
    threads section
    + +
    One line per thread. Each line consists of two parts: the thread ID, followed by a tab, + followed by the thread name. There are few restrictions on what a valid thread name is, so + include everything to the end of the line.
    + +
    methods section
    + +
    One line per method entry or exit. A line consists of four pieces, separated by tab marks: + method-ID [TAB] class-name [TAB] method-name [TAB] + signature . Only the methods that were actually entered or exited are included in the + list. Note that all three identifiers are required to uniquely identify a method.
    +
    + +

    Neither the threads nor methods sections are sorted.

    + +

    Creating Trace Files

    + +

    To use Traceview, you need to generate log files containing the trace information you want to + analyze.

    + +

    There are two ways to generate trace logs:

    +
      +
    • Include the {@link android.os.Debug} class in your code and call its + methods to start and stop logging of trace information to disk. This method is very precise because + you can specify in your code exactly where to start and stop logging trace data.
    • +
    • Use the method profiling feature of DDMS to generate trace logs. This method is less + precise since you do not modify code, but rather specify when to start and stop logging with + a DDMS. Although you have less control on exactly where the data is logged, this method is useful + if you don't have access to the application's code, or if you do not need the precision of the first method. +
    • +
    + +

    Before you start generating trace logs, be aware of the following restrictions:

    +
      +
    • If you are using the {@link android.os.Debug} class, your device or emulator must have an SD card + and your application must have permission to write to the SD card.
    • +
    • If you are using DDMS, Android 1.5 devices are not supported.
    • +
    • If you are using DDMS, Android 2.1 and earlier devices must + have an SD card present and your application must have permission to write to the SD card. +
    • If you are using DDMS, Android 2.2 and later devices do not need an SD card. The trace log files are + streamed directly to your development machine.
    • +
    + +

    This document focuses on using the {@link android.os.Debug} class to generate trace data. For more information on using DDMS + to generate trace data, see Using the Dalvik Debug Monitor Server. +

    + +

    To create the trace files, include the {@link android.os.Debug} class and call one of the + {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods. In the call, you + specify a base name for the trace files that the system generates. To stop tracing, call {@link + android.os.Debug#stopMethodTracing() stopMethodTracing()}. These methods start and stop method + tracing across the entire virtual machine. For example, you could call + {@link android.os.Debug#startMethodTracing() startMethodTracing()} in + your activity's {@link android.app.Activity#onCreate onCreate()} method, and call + {@link android.os.Debug#stopMethodTracing() stopMethodTracing()} in that activity's + {@link android.app.Activity#onDestroy()} method.

    +
    +    // start tracing to "/sdcard/calc.trace"
    +    Debug.startMethodTracing("calc");
    +    // ...
    +    // stop tracing
    +    Debug.stopMethodTracing();
    +
    + +

    When your application calls startMethodTracing(), the system creates a file called + <trace-base-name>.trace. This contains the binary method trace data and a + mapping table with thread and method names.

    + +

    The system then begins buffering the generated trace data, until your application calls + stopMethodTracing(), at which time it writes the buffered data to the output file. If the system + reaches the maximum buffer size before stopMethodTracing() is called, the system stops tracing + and sends a notification to the console.

    + +

    Interpreted code will run more slowly when profiling is enabled. Don't try to generate + absolute timings from the profiler results (i.e. "function X takes 2.5 seconds to run"). The + times are only useful in relation to other profile output, so you can see if changes have made + the code faster or slower.

    + +

    When using the Android emulator, you must specify an SD card when you create your AVD because the trace files + are written to the SD card. Your application must have permission to write to the SD card as well. + +

    The format of the trace files is previously described in this + document.

    + +

    Copying Trace Files to a Host Machine

    + +

    After your application has run and the system has created your trace files + <trace-base-name>.trace on a device or emulator, you must copy those files to + your development computer. You can use adb pull to copy the files. Here's an example + that shows how to copy an example file, calc.trace, from the default location on the emulator to + the /tmp directory on the emulator host machine:

    +
    +adb pull /sdcard/calc.trace /tmp
    +
    + +

    Viewing Trace Files in Traceview

    + +

    To run Traceview and view the trace files, enter traceview + <trace-base-name>. For example, to run Traceview on the example files copied in the + previous section, use:

    +
    +traceview /tmp/calc
    +
    + +

    Note: If you are trying to view the trace logs of an application + that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. + You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information + on this file, see the Proguard documentation.

    + +

    Using dmtracdedump

    + +

    dmtracedump is a tool that gives you an alternate way of generating + graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to + create the graphical output, so you need to install Graphviz before running dmtracedump.

    + +

    The dmtracedump tool generates the call stack data as a tree diagram, with each call + represented as a node. It shows call flow (from parent node to child nodes) using arrows. The + diagram below shows an example of dmtracedump output.

    + +

    Figure 3. Screenshot of dmtracedump

    + +

    For each node, dmtracedump shows <ref> + callname (<inc-ms>, <exc-ms>,<numcalls>), where

    + +
      +
    • <ref> -- Call reference number, as used in trace logs
    • + +
    • <inc-ms> -- Inclusive elapsed time (milliseconds spent in method, + including all child methods)
    • + +
    • <exc-ms> -- Exclusive elapsed time (milliseconds spent in method, + not including any child methods)
    • + +
    • <numcalls> -- Number of calls
    • +
    + +

    The usage for dmtracedump is:

    +
    +dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
    +
    + +

    The tool then loads trace log data from <trace-base-name>.data and + <trace-base-name>.key. The table below lists the options for dmtracedump.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OptionDescription
    -d <trace-base-name>Diff with this trace name
    -g <outfile>Generate output to <outfile>
    -hTurn on HTML output
    -oDump the trace file instead of profiling
    -d <trace-base-name>URL base to the location of the sortable javascript file
    -t <percent>Minimum threshold for including child nodes in the graph (child's inclusive time as a + percentage of parent inclusive time). If this option is not used, the default threshold + is 20%.
    + + + +

    Traceview Known Issues

    + +
    +
    Threads
    + +
    + Traceview logging does not handle threads well, resulting in these two problems: + +
      +
    1. If a thread exits during profiling, the thread name is not emitted;
    2. + +
    3. The VM reuses thread IDs. If a thread stops and another starts, they may get the same + ID.
    4. +
    +
    + +
    \ No newline at end of file diff --git a/docs/html/tools/debugging/debugging-ui.jd b/docs/html/tools/debugging/debugging-ui.jd new file mode 100644 index 000000000000..c1976b8de2ea --- /dev/null +++ b/docs/html/tools/debugging/debugging-ui.jd @@ -0,0 +1,547 @@ +page.title=Optimizing Your UI +parent.title=Debugging +parent.link=index.html +@jd:body + + + +

    +Sometimes your application's layout can slow down your application. + To help debug issues in your layout, the Android SDK provides the Hierarchy Viewer and + layoutopt tools. +

    + +

    The Hierarchy Viewer application allows you to debug and optimize your user interface. It + provides a visual representation of the layout's View hierarchy (the View Hierarchy window) + and a magnified view of the display (the Pixel Perfect window).

    + +

    layoutopt is a command-line tool that helps you optimize the layouts and layout + hierarchies of your applications. You can run it against your layout files or resource + directories to quickly check for inefficiencies or other types of problems that could be + affecting the performance of your application.

    + +

    Using Hierarchy Viewer

    + +

    Running Hierarchy Viewer and choosing a window

    +

    + To run Hierarchy Viewer, follow these steps:

    +
      +
    1. + Connect your device or launch an emulator. +

      + To preserve security, Hierarchy Viewer can only connect to devices running a + developer version of the Android system. +

      +
    2. +
    3. + If you have not done so already, install the application you want to work with. +
    4. +
    5. + Run the application, and ensure that its UI is visible. +
    6. +
    7. + From a terminal, launch hierarchyviewer from the + <sdk>/tools/ + directory. +
    8. +
    9. + The first window you see displays a list of devices and emulators. To expand the list + of Activity objects for a device or emulator, click the arrow on the left. This displays a + list of the Activity objects whose UI is currently visible on the device or emulator. The + objects are listed by their Android component name. The list includes both your application + Activity and system Activity objects. A screenshot of this window appears in + figure 1. +
    10. +
    11. + Select the name of your Activity from the list. You can now look at its view + hierarchy using the View Hierarchy window, or look at a magnified image of the UI using + the Pixel Perfect window. +
    12. +
    +

    + To learn how to use the View Hierarchy window, go to + About the View Hierarchy window. To learn how to use the + Pixel Perfect window, go to About the Pixel Perfect window. +

    + +

    Figure 1. Hierarchy Viewer device window

    +

    About the View Hierarchy window

    +

    + The View Hierarchy window displays the View objects that form the UI of the + Activity that is running on your device or emulator. You use it to look at individual + View objects within the context of the entire View tree. For each View object, the View + Hierarchy window also displays rendering performance data. +

    +

    + To see the View Hierarchy window, run Hierarchy Viewer as described in + the section Running Hierarchy Viewer and choosing a window. Next, click + View Hierarchy at the top of the device window. +

    +

    + You should see four panes: +

    +
      +
    • + Tree View: The left-hand pane displays the Tree View, + a diagram of the Activity object's hierarchy of views. Use Tree View to examine individual + View objects and see the relationships between View objects in your UI. +

      + To zoom in on the pane, use the slider at the bottom of the pane, or use your mouse + scroll wheel. To move around in the pane or reveal View objects that are not currently + visible, click and drag the pane. +

      +

      + To highlight the nodes in the tree whose class or ID match a search string, enter the + string in the Filter by class or id: edit box at the bottom of the + window. The background of nodes that match the search string will change from gray to + bright blue. +

      +

      + To save a screenshot of Tree View to a PNG file, click Save As PNG at + the top of the View Hierarchy window. This displays a dialog in which you can choose + a directory and file name. +

      +

      + To save a layered screenshot of your device or emulator to an Adobe Photoshop (PSD) + file, click Capture Layers at the top of the View Hierarchy window. + This displays a dialog in which you can choose a directory or file name. + Each View in the UI is saved as a separate Photoshop layer. +

      +

      + In Photoshop (or similar program that accepts .psd files), you can hide, show or edit a + layer independently of others. When you save a layered screenshot, you can examine and + modify the image of an individual View object. This helps you experiment with design + changes. +

      +
    • +
    • + The upper right-hand pane displays the Tree Overview, a smaller map + representation of the entire Tree View window. Use Tree Overview to identify the part of the + view tree that is being displayed in Tree View. +

      + You can also use Tree Overview to move around in the Tree View pane. Click and drag + the shaded rectangle over an area to reveal it in Tree View. +

      +
    • +
    • + The middle right-hand pane displays the Properties View, + a list of the properties for a selected View object. With Properties View, you can + examine all the properties without having to look at your application source. +

      + The properties are organized by category. To find an individual property, expand + a category name by clicking the arrow on its left. This reveals all the properties + in that category. +

      +
    • +
    • + The lower right-hand pane displays the Layout View, + a block representation of the UI. Layout View is another way to navigate through your UI. + When you click on a View object in Tree View, its position in the UI is highlighted. + Conversely, when you click in an area of Layout View, the View object for that area is + highlighted in Tree View. +

      + The outline colors of blocks in Layout View provide additional information: +

      +
        +
      • + Bold red: The block represents the the View that is currently selected in + Tree View. +
      • +
      • + Light red: The block represents the parent of the block outlined in bold red. +
      • +
      • + White: The block represents a visible View that is not a parent or child of the + View that is currently selected in Tree View. +
      • +
      +
    • +
    +

    + When the UI of the current Activity changes, the View Hierarchy window is not automatically + updated. To update it, click Load View Hierarchy at the top of the window. +

    +

    + Also, the window is not updated if you switch to a new Activity. To update it, start by + clicking the window selection icon in the bottom left-hand corner of the window. This + navigates back to the Window Selection window. From this window, click the Android + component name of the new Activity and then click Load View Hierarchy + at the top of the window. +

    +

    + A screenshot of the View Hierarchy window appears in figure 2. +

    + +

    Figure 2. The View Hierarchy window

    +

    Working with an individual View in Tree View

    +

    + Each node in Tree View represents a single View. Some information is always visible. Starting + at the top of the node, you see the following: +

    +
      +
    1. + View class: The View object's class. +
    2. +
    3. + View object address: A pointer to View object. +
    4. +
    5. + View object ID: The value of the + android:id + attribute. +
    6. +
    7. + Performance indicators: A set of three colored dots that indicate the rendering + speed of this View relative to other View objects in the tree. The three dots + represent (from left to right) the measure, layout, and draw times of the rendering. +

      + The colors indicate the following relative performance: +

      +
        +
      • + Green: For this part of the render time, this View is in the faster 50% of all + the View objects in the tree. For example, a green dot for the measure time means + that this View has a faster measure time than 50% of the View objects in the tree. +
      • +
      • + Yellow: For this part of the render time, this View is in the slower 50% of all + the View objects in the tree. For example, a yellow dot for the layout time means + that this View has a slower layout time than 50% of the View objects in the tree. +
      • +
      • + Red: For this part of the render time, this View is the slowest one in the tree. + For example, a red dot for the draw time means that this View takes the most + time to draw of all the View objects in the tree. +
      • +
      +
    8. +
    9. + View index: The zero-based index of the View in its parent View. If it is the only child, + this is 0. +
    10. +
    +

    + When you select a node, additional information for the View appears in a small window above + the node. When you click one of the nodes, you see the following: +

    +
      +
    • + Image: The actual image of the View, as it would appear in the emulator. If the View has + children, these are also displayed. +
    • +
    • + View count: The number of View objects represented by this node. This includes the View + itself and a count of its children. For example, this value is 4 for a View that has 3 + children. +
    • +
    • + Render times: The actual measure, layout, and draw times for the View rendering, in + milliseconds. These represent the same values as the performance indicators mentioned in + the preceding section. +
    • +
    +

    + An annotated screenshot of an individual node in the Tree View window appears in figure 3. +

    + +

    Figure 3. An annotated node in Tree View

    +

    Debugging with View Hierarchy

    +

    + The View Hierarchy window helps you debug an application by providing a static display + of the UI. The display starts with your application's opening screen. As you step through + your application, the display remains unchanged until you redraw it by invalidating and + then requesting layout for a View. +

    +

    + To redraw a View in the display: +

    +
      +
    • + Select a View in Tree View. As you move up towards the root of the tree (to the + left in the Tree View), you see the highest-level View objects. Redrawing a high-level + object usually forces the lower-level objects to redraw as well. +
    • +
    • + Click Invalidate at the top of the window. This marks the View as + invalid, and schedules it for a redraw at the next point that a layout is requested. +
    • +
    • + Click Request Layout to request a layout. The View and its children + are redrawn, as well as any other View objects that need to be redrawn. +
    • +
    +

    + Manually redrawing a View allows you to watch the View object tree and examine the properties of + individual View objects one step at a time as you go through breakpoints in your code. +

    +

    Optimizing with View Hierarchy

    +

    + View Hierarchy also helps you identify slow render performance. You start by looking at the + View nodes with red or yellow performance indicators to identify the slower View objects. As you + step through your application, you can judge if a View is consistently slow or slow only in + certain circumstances. +

    +

    + Remember that slow performance is not necessarily evidence of a problem, especially for + ViewGroup objects. View objects that have more children and more complex View objects render + more slowly. +

    +

    + The View Hierarchy window also helps you find performance issues. Just by looking at the + performance indicators (the dots) for each View node, you can see which View objects are the + slowest to measure, layout, and draw. From that, you can quickly identify the problems you + should look at first. +

    +

    Using Pixel Perfect

    +

    + Pixel Perfect is a tool for examining pixel properties and laying out UIs from a design drawing. +

    +

    About the Pixel Perfect window

    +

    + The Pixel Perfect window displays a magnified image of the screen that is currently + visible on the emulator or device. In it, you can examine the properties + of individual pixels in the screen image. You can also use the Pixel Perfect window + to help you lay out your application UI based on a bitmap design. +

    +

    + To see the Pixel Perfect window, run Hierarchy Viewer, as described in + the section Running Hierarchy Viewer and choosing a window. Next, click + Inspect Screenshot at the top of the device window. The Pixel Perfect window + appears. +

    +

    + In it, you see three panes: +

    +
      +
    • + View Object pane: This is a hierarchical list of the View objects that are currently + visible on the device or emulator screen, including both the ones in your application and + the ones generated by the system. The objects are listed by their View class. + To see the class names of a View object's children, expand the View by clicking the + arrow to its left. When you click a View, its position is highlighted in the Pixel Perfect + pane on the right. +
    • +
    • + Pixel Perfect Loupe pane: This is the magnified screen image. It is overlaid by a grid in + which each square represents one pixel. To look at the information for a pixel, click in its + square. Its color and X,Y coordinates appear at the bottom of the pane. +

      + The magenta crosshair in the pane corresponds to the positioning + crosshair in the next pane. It only moves when you move the crosshair in the next pane. +

      +

      + To zoom in or out on the image, use the Zoom slider at the bottom of + the pane, or use your mouse's scroll wheel. +

      +

      + When you select a pixel in the Loupe pane, you see the following information at the + bottom of the pane: +

      +
        +
      • + Pixel swatch: A rectangle filled with the same color as the pixel. +
      • +
      • + HTML color code: The hexadecimal RGB code corresponding to the pixel color +
      • +
      • + RGB color values: A list of the (R), green (G), and blue (B) color values of the + pixel color. Each value is in the range 0-255. +
      • +
      • + X and Y coordinates: The pixel's coordinates, in device-specific pixel units. + The values are 0-based, with X=0 at the left of the screen and Y=0 at the top. +
      • +
      +
    • +
    • + Pixel Perfect pane: This displays the currently visible screen as it would appear in the + emulator. +

      + You use the cyan crosshair to do coarse positioning. Drag the crosshair in the image, + and the Loupe crosshair will move accordingly. You can also click on a point in the + Pixel Perfect pane, and the crosshair will move to that point. +

      +

      + The image corresponding to the View object selected in the View Object pane is + outlined in a box that indicates the View object's position on the screen. For the + selected object, the box is bold red. Sibling and parent View objects have a light + red box. View objects that are neither parents nor siblings are in white. +

      +

      + The layout box may have other rectangles either inside or outside it, each of which + indicates part of the View. A purple or green rectangle indicates the View bounding box. + A white or black box inside the layout box represents the padding, the + defined distance between the View object's content and its bounding box. An outer white + or black rectangle represents the margins, the distance between the + View bounding box and adjacent View objects. The padding and margin boxes are white if + the layout background is black, and vice versa. +

      +

      + You can save the screen image being displayed in the Pixel Perfect pane as a PNG file. + This produces a screenshot of the current screen. To do this, click + Save as PNG at the top of the window. This displays a dialog, + in which you can choose a directory and filename for the file. +

      +
    • +
    +

    + The panes are not automatically refreshed when you change one of the View objects or go to + another Activity. To refresh the Pixel Perfect pane and the Loupe pane, click + Refresh Screenshot at the top of the window. This will change the panes + to reflect the current screen image. You still may need to refresh the View Object pane; + to do this, click Refresh Tree at the top of the window. +

    +

    + To automatically refresh the panes while you are debugging, set + Auto Refresh at the top of the window, and then set a refresh rate + with the Refresh Rate slider at the bottom of the Loupe pane. +

    +

    Working with Pixel Perfect overlays

    +

    + You often construct a UI based on a design done as a bitmap image. The Pixel Perfect window + helps you match up your View layout to a bitmap image by allowing you to load the bitmap as an + overlay on the screen image. +

    +

    + To use a bitmap image as an overlay: +

    +
      +
    • + Start your application in a device or emulator and navigate to the Activity whose UI you + want to work with. +
    • +
    • + Start Hierarchy Viewer and navigate to the Pixel Perfect window. +
    • +
    • + At the top of the window, click Load Overlay. A dialog opens, prompting + for the image file to load. Load the image file. +
    • +
    • + Pixel Perfect displays the overlay over the screen image in the Pixel Perfect pane. The + lower left corner of the bitmap image (X=0, Y=max value) is anchored on the lower + leftmost pixel (X=0, Y=max screen) of the screen. +

      + By default, the overlay has a 50% transparency, which allows you to see the screen + image underneath. You can adjust this with the Overlay: slider at the + bottom of the Loupe pane. +

      +

      + Also by default, the overlay is not displayed in the Loupe pane. To display it, + set Show in Loupe at the top of the window. +

      +
    • +
    +

    + The overlay is not saved as part of the screenshot when you save the screen image as a PNG + file. +

    +

    + A screenshot of the Pixel Perfect window appears in figure 4. +

    + +

    Figure 4. The Pixel Perfect window

    +

    Using layoutopt

    +

    + The layoutopt tool lets you analyze the XML files that define your + application's UI to find inefficiencies in the view hierarchy.

    + +

    + To run the tool, open a terminal and launch layoutopt <xmlfiles> + from your SDK tools/ directory. The <xmlfiles> argument is a space- + delimited list of resources you want to analyze, either uncompiled resource xml files or + directories of such files. +

    +

    + The tool loads the specified XML files and analyzes their definitions and + hierarchies according to a set of predefined rules. For every issue it detects, it + displays the following information: +

    +
      +
    • + The filename in which the issue was detected. +
    • +
    • + The line number for the issue. +
    • +
    • + A description of the issue, and for some types of issues it also suggests a resolution. +
    • +
    +

    The following is a sample of the output from the tool:

    +
    +$ layoutopt samples/
    +samples/compound.xml
    +   7:23 The root-level <FrameLayout/> can be replaced with <merge/>
    +   11:21 This LinearLayout layout or its FrameLayout parent is useless
    +samples/simple.xml
    +   7:7 The root-level <FrameLayout/> can be replaced with <merge/>
    +samples/too_deep.xml
    +   -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10!
    +   20:81 This LinearLayout layout or its LinearLayout parent is useless
    +   24:79 This LinearLayout layout or its LinearLayout parent is useless
    +   28:77 This LinearLayout layout or its LinearLayout parent is useless
    +   32:75 This LinearLayout layout or its LinearLayout parent is useless
    +   36:73 This LinearLayout layout or its LinearLayout parent is useless
    +   40:71 This LinearLayout layout or its LinearLayout parent is useless
    +   44:69 This LinearLayout layout or its LinearLayout parent is useless
    +   48:67 This LinearLayout layout or its LinearLayout parent is useless
    +   52:65 This LinearLayout layout or its LinearLayout parent is useless
    +   56:63 This LinearLayout layout or its LinearLayout parent is useless
    +samples/too_many.xml
    +   7:413 The root-level <FrameLayout/> can be replaced with <merge/>
    +   -1:-1 This layout has too many views: 81 views, it should have <= 80!
    +samples/useless.xml
    +   7:19 The root-level <FrameLayout/> can be replaced with <merge/>
    +   11:17 This LinearLayout layout or its FrameLayout parent is useless
    +
    diff --git a/docs/html/tools/debugging/index.jd b/docs/html/tools/debugging/index.jd new file mode 100644 index 000000000000..45fbc9e0a6fd --- /dev/null +++ b/docs/html/tools/debugging/index.jd @@ -0,0 +1,186 @@ +page.title=Debugging +@jd:body + + +
    +
    +

    In this document

    + +
      +
    1. Debugging Environment
    2. + +
    3. Additional Debugging Tools
    4. + +
    5. Debugging Tips
    6. +
    +
    +
    + +

    The Android SDK provides most of the tools that you need to debug your applications. You need + a JDWP-compliant debugger if you want to be able to do things such as step through code, + view variable values, and pause execution of an application. If you are using Eclipse, a + JDWP-compliant debugger is already included and there is no setup required. If you are using + another IDE, you can use the debugger that comes with it and attach the debugger to a special + port so it can communicate with the application VMs on your devices. The main components that + comprise a typical Android debugging environment are:

    + +
    +
    adb
    + +
    adb acts as a middleman between a device and your development system. It provides various + device management capabilities, including moving and syncing files to the emulator, running a + UNIX shell on the device or emulator, and providing a general means to communicate with + connected emulators and devices.
    + +
    Dalvik Debug Monitor + Server
    + +
    DDMS is a graphical program that communicates with your devices through adb. DDMS can + capture screenshots, gather thread and stack information, spoof incoming calls and SMS + messages, and has many other features.
    + +
    Device or + Android Virtual Device
    + +
    Your application must run in a device or in an AVD so that it can be debugged. An adb device + daemon runs on the device or emulator and provides a means for the adb host daemon to + communicate with the device or emulator.
    + +
    JDWP debugger
    + +
    The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to attach to + a VM. Each application runs in a VM and exposes a unique port that you can attach a debugger to + via DDMS. If you want to debug multiple applications, attaching to each port might become + tedious, so DDMS provides a port forwarding feature that can forward a specific VM's debugging + port to port 8700. You can switch freely from application to application by highlighting it in the + Devices tab of DDMS. DDMS forwards the appropriate port to port 8700. Most modern Java IDEs include a JDWP debugger, + or you can use a command line debugger such as + jdb.
    +
    + +

    Debugging Environment

    + +

    Figure 1 shows how the various debugging tools work together in a typical + debugging environment.

    + Debugging workflow +

    In addition to the main debugging tools, the Android SDK provides additional tools to help you + debug and profile your applications:

    + +
    +
    Heirarchy Viewer + and layoutopt
    + +
    Graphical programs that let you debug and profile user interfaces.
    + +
    Traceview
    + +
    A graphical viewer that displays trace file data for method calls and times saved by your + application, which can help you profile the performance of your application.
    + +
    Dev Tools + Android application
    + +
    The Dev Tools application included in the emulator system image exposes several settings + that provide useful information such as CPU usage and frame rate. You can also transfer the + application to a hardware device.
    +
    + + +

    Debugging Tips

    + +

    While debugging, keep these helpful tips in mind to help you figure out common problems with your +applications:

    + +
    +
    Dump the stack trace
    +
    To obtain a stack dump from emulator, you can log +in with adb shell, use ps to find the process you +want, and then kill -3. The stack trace appears in the log file. +
    + +
    Display useful info on the emulator screen
    +
    The device can display useful information such as CPU usage or highlights +around redrawn areas. Turn these features on and off in the developer settings +window as described in +Debugging with the Dev Tools App. +
    + +
    Get application and system state information from the emulator
    +
    You can access dumpstate information from the adb shell commands. See +dumpsys and +dumpstate on the adb topic page.
    + + + +
    Get wireless connectivity information
    +
    You can get information about wireless connectivity using DDMS. +From the Device menu, select Dump +radio state.
    + +
    Log trace data
    +
    You can log method calls and other tracing data in an activity by calling +{@link android.os.Debug#startMethodTracing(String) startMethodTracing()}. See Profiling with Traceview and +dmtracedump for details.
    + +
    Log radio data
    +
    By default, radio information is not logged to the system (it is a lot of +data). However, you can enable radio logging using the following commands: + +
    +adb shell
    +logcat -b radio
    +
    +
    + +
    Capture screenshots
    +
    The Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Select +Device > Screen capture.
    + +
    Use debugging helper classes
    +
    Android provides debug helper classes such as {@link android.util.Log + util.Log} and {@link android.os.Debug} for your convenience.
    + +
    Garbage collection
    +
    +The debugger and garbage collector are currently loosely integrated. The VM guarantees that any +object the debugger is aware of is not garbage collected until after the debugger disconnects. +This can result in a buildup of objects over time while the debugger is connected. For example, +if the debugger sees a running thread, the associated {@link java.lang.Thread} object is not +garbage collected even after the thread terminates. +
    + +
    + + + + + + + + diff --git a/docs/html/tools/device.jd b/docs/html/tools/device.jd new file mode 100644 index 000000000000..d5fd58122e4d --- /dev/null +++ b/docs/html/tools/device.jd @@ -0,0 +1,267 @@ +page.title=Using Hardware Devices +@jd:body + +
    +
    +

    In this document

    +
      +
    1. Setting up a Device for Development +
        +
      1. USB Vendor IDs
      2. +
      +
    2. +
    +

    See also

    +
      +
    1. Google USB Driver
    2. +
    3. OEM USB Drivers
    4. +
    +
    +
    + +

    When building a mobile application, it's important that you always test your application on a +real device before releasing it to users. This page describes how to set up your development +environment and Android-powered device for testing and debugging on the device.

    + +

    You can use any Android-powered device as an environment for running, +debugging, and testing your applications. The tools included in the SDK make it easy to install and +run your application on the device each time you compile. You can install your application on the +device directly from Eclipse or from the command line with ADB. If +you don't yet have a device, check with the service providers in your area to determine which +Android-powered devices are available.

    + +

    If you want a SIM-unlocked phone, then you might consider the Google Nexus S. To find a place +to purchase the Nexus S and other Android-powered devices, visit google.com/phone.

    + +

    Note: When developing on a device, keep in mind that you should +still use the Android emulator to test your +application +on configurations that are not equivalent to those of your real device. Although the emulator +does not allow you to test every device feature (such as the accelerometer), it does +allow you to verify that your application functions properly on different versions of the Android +platform, in different screen sizes and orientations, and more.

    + + +

    Setting up a Device for Development

    + +

    With an Android-powered device, you can develop and debug your Android applications just as you +would on the emulator. Before you can start, there are just a few things to do:

    + +
      +
    1. Declare your application as "debuggable" in your Android Manifest. +

      When using Eclipse, you can skip this step, because running your app directly from +the Eclipse IDE automatically enables debugging.

      +

      In the AndroidManifest.xml file, add android:debuggable="true" to +the <application> element.

      +

      Note: If you manually enable debugging in the manifest + file, be sure to disable it before you build for release (your published application +should usually not be debuggable).

    2. +
    3. Turn on "USB Debugging" on your device. +

      On the device, go to Settings > Applications > Development + and enable USB debugging + (on an Android 4.0 device, the setting is +located in Settings > Developer options).

      +
    4. +
    5. Set up your system to detect your device. +
        +
      • If you're developing on Windows, you need to install a USB driver for adb. For an +installation guide and links to OEM drivers, see the OEM USB +Drivers document.
      • +
      • If you're developing on Mac OS X, it just works. Skip this step.
      • +
      • If you're developing on Ubuntu Linux, you need to add a +udev rules file that contains a USB configuration for each type of device +you want to use for development. In the rules file, each device manufacturer +is identified by a unique vendor ID, as specified by the +ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on +Ubuntu Linux: + +
          +
        1. Log in as root and create this file: + /etc/udev/rules.d/51-android.rules. +

          Use this format to add each vendor to the file:
          + SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev" +

          + + In this example, the vendor ID is for HTC. The MODE +assignment specifies read/write permissions, and GROUP defines +which Unix group owns the device node.

          + +

          Note: The rule syntax +may vary slightly depending on your environment. Consult the udev +documentation for your system as needed. For an overview of rule syntax, see +this guide to writing udev +rules.

          +
        2. +
        3. Now execute:
          + chmod a+r /etc/udev/rules.d/51-android.rules +
        4. +
        +
      • +
      +
    6. +
    + +

    When plugged in over USB, can verify that your device is connected by executing adb +devices from your SDK {@code platform-tools/} directory. If connected, +you'll see the device name listed as a "device."

    + +

    If using Eclipse, run or debug your application as usual. You will be +presented with a Device Chooser dialog that lists the available +emulator(s) and connected device(s). Select the device upon which you want to +install and run the application.

    + +

    If using the Android +Debug Bridge (adb), you can issue commands with the -d flag to +target your connected device.

    + +

    USB Vendor IDs

    + +

    This table provides a reference to the vendor IDs needed in order to add USB +device support on Linux. The USB Vendor ID is the value given to the +ATTR{idVendor} property in the rules file, as described +above.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CompanyUSB Vendor ID
    Acer0502
    ASUS0b05
    Dell413c
    Foxconn0489
    Fujitsu04c5
    Fujitsu Toshiba04c5
    Garmin-Asus091e
    Google18d1
    Hisense109b
    HTC0bb4
    Huawei12d1
    K-Touch24e3
    KT Tech2116
    Kyocera0482
    Lenovo17ef
    LG1004
    Motorola22b8
    NEC0409
    Nook2080
    Nvidia0955
    OTGV2257
    Pantech10a9
    Pegatron1d4d
    Philips0471
    PMC-Sierra04da
    Qualcomm05c6
    SK Telesys1f53
    Samsung04e8
    Sharp04dd
    Sony054c
    Sony Ericsson0fce
    Teleepoch2340
    Toshiba0930
    ZTE19d2
    diff --git a/docs/html/tools/devices/emulator.jd b/docs/html/tools/devices/emulator.jd new file mode 100644 index 000000000000..cee6473d4453 --- /dev/null +++ b/docs/html/tools/devices/emulator.jd @@ -0,0 +1,1571 @@ +page.title=Using the Android Emulator +parent.title=Managing Virtual Devices +parent.link=index.html +@jd:body + + + +

    The Android SDK includes a virtual mobile device emulator +that runs on your computer. The emulator lets you prototype, develop and test +Android applications without using a physical device.

    + +

    The Android emulator mimics all of the hardware and software features +of a typical mobile device, except that it cannot place actual phone +calls. It provides a variety of navigation and control keys, which you can "press" +using your mouse or keyboard to generate events for your application. It also +provides a screen in which your application is displayed, together with any other +active Android applications.

    + + + +

    To let you model and test your application more easily, the emulator utilizes +Android Virtual Device (AVD) configurations. AVDs let you define certain hardware +aspects of your emulated phone and allow you to create many configurations to test +many Android platforms and hardware permutations. Once your application is running on +the emulator, it can use the services of the Android platform to invoke other +applications, access the network, play audio and video, store and retrieve data, +notify the user, and render graphical transitions and themes.

    + +

    The emulator also includes a variety of debug capabilities, such as a console +from which you can log kernel output, simulate application interrupts (such as +arriving SMS messages or phone calls), and simulate latency effects and dropouts +on the data network.

    + + + +

    Overview

    + +

    The Android emulator is an application that provides a virtual +mobile device on which you can run your Android applications. It runs a full +Android system stack, down to the kernel level, that includes a set of +preinstalled applications (such as the dialer) that you can access from your +applications. You can choose what version of the Android system you want to +run in the emulator by configuring AVDs, and you can also customize the +mobile device skin and key mappings. When launching the emulator and at runtime, +you can use a variety of commands and options to control its behavior. +

    + +

    The Android system images available through the Android SDK Manager contain +code for the Android Linux kernel, the native libraries, the Dalvik VM, and the +various Android packages (such as the Android framework and preinstalled +applications). The emulator provides dynamic binary translation of device +machine code to the OS and processor architecture of your development +machine.

    + +

    The Android emulator supports many hardware features likely to be found on +mobile devices, including:

    + +
      +
    • An ARMv5 CPU and the corresponding memory-management unit (MMU)
    • +
    • A 16-bit LCD display
    • +
    • One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone +buttons)
    • +
    • A sound chip with output and input capabilities
    • +
    • Flash memory partitions (emulated through disk image files on the +development machine)
    • +
    • A GSM modem, including a simulated SIM Card
    • +
    • A camera, using a webcam connected to your development computer.
    • +
    • Sensors like an accelerometer, using data from a USB-connected Android device.
    • +
    + +

    The following sections describe the emulator and its use for development of Android +applications in more detail.

    + + +

    Android Virtual Devices and the Emulator

    + +

    To use the emulator, you first must create one or more AVD configurations. In each +configuration, you specify an Android platform to run in the emulator and the set of hardware +options and emulator skin you want to use. Then, when you launch the emulator, you specify +the AVD configuration that you want to load.

    + +

    Each AVD functions as an independent device, with its own private storage for +user data, SD card, and so on. When you launch the emulator with an AVD configuration, +it automatically loads the user data and SD card data from the AVD directory. By default, +the emulator stores the user data, SD card data, and cache in the AVD directory.

    + +

    To create and manage AVDs you use the AVD Manager UI or the android tool +that is included in the SDK. +For complete information about how to set up AVDs, see Managing Virtual Devices.

    + + +

    Starting and Stopping the Emulator

    + +

    During development and testing of your application, you install and run your +application in the Android emulator. You can launch the emulator as a standalone +application from a command line, or you can run it from within your Eclipse +development environment. In either case, you specify the AVD configuration to +load and any startup options you want to use, as described in this document. +

    + +

    You can run your application on a single instance of the emulator or, +depending on your needs, you can start multiple emulator instances and run your +application in more than one emulated device. You can use the emulator's +built-in commands to simulate GSM phone calling or SMS between emulator +instances, and you can set up network redirection that allows emulators to send +data to one another. For more information, see Telephony +Emulation, SMS Emulation, and +Emulator Networking

    + +

    To start an instance of the emulator from the command line, navigate to the +tools/ folder of the SDK. Enter emulator command +like this:

    + +
    emulator -avd <avd_name> [<options>]
    + +

    This initializes the emulator, loads an AVD configuration and displays the emulator +window. For more information about command line options for the emulator, see the +Android Emulator tool reference.

    + +

    Note: You can run multiple +instances of the emulator concurrently, each with its own AVD configuration and +storage area for user data, SD card, and so on.

    + +

    If you are working in Eclipse, the ADT plugin for Eclipse installs your +application and starts the emulator automatically, when you run or debug +the application. You can specify emulator startup options in the Run/Debug +dialog, in the Target tab. When the emulator is running, you can issue +console commands as described later in this document.

    + +

    If you are not working in Eclipse, see Installing Applications +on the Emulator for information about how to install your application.

    + +

    To stop an emulator instance, just close the emulator's window.

    + +

    For a reference of the emulator's startup commands and keyboard mapping, see +the Android Emulator tool +reference.

    + + +

    Installing Applications on the Emulator

    + +

    If you don't have access to Eclipse or the ADT Plugin, you can install your application on the +emulator using the adb utility. Before +installing the application, you need to build and package it into an .apk as described +in Building and +Running Apps. Once the application is installed, you can start the emulator from the command +line as described previously, using any startup options necessary. +When the emulator is running, you can also connect to the emulator instance's +console to issue commands as needed.

    + +

    As you update your code, you periodically package and install it on the emulator. +The emulator preserves the application and its state data across restarts, +in a user-data disk partition. To ensure that the application runs properly +as you update it, you may need to delete the emulator's user-data partition. +To do so, start the emulator with the -wipe-data option. +For more information about the user-data partition and other emulator storage, +see Working with Emulator Disk Images.

    + + +

    Using Hardware Acceleration

    + +

    In order to make the Android emulator run faster and be more responsive, you can configure it to +take advantage of hardware acceleration, using a combination of configuration options, specific +Android system images and hardware drivers.

    + + +

    Configuring Graphics Acceleration

    + +

    Caution: As of SDK Tools Revision 17, the graphics +acceleration feature for the emulator is experimental; be alert for incompatibilities and +errors when using this feature.

    + +

    Graphics acceleration for the emulator takes advantage of your development computer's graphics +hardware, specifically its graphics processing unit (GPU), to make screen drawing faster. To use +the graphics acceleration feature, you must have the following versions of the Android development +tools installed:

    + +
      +
    • Android SDK Tools, Revision 17 or higher
    • +
    • Android SDK Platform API 15, Revision 3 or higher
    • +
    + +

    Use the Android SDK +Manager to install these components:

    + +

    Note: Not all applications are compatible with graphics hardware +acceleration. In particular, the Browser application and applications using the {@link +android.webkit.WebView} component are not compatible with graphics acceleration.

    + +

    To configure an AVD to use graphics acceleration:

    + +
      +
    1. Make sure you have the required SDK components installed (listed above).
    2. +
    3. Start the AVD Manager and create a new AVD with the Target value of +Android 4.0.3 (API Level 15), revision 3 or higher.
    4. +
    5. If you want to have graphics acceleration enabled by default for this AVD, in the +Hardware section, click New, select GPU emulation +and set the value to Yes. +

      Note: You can also enable graphics acceleration when you +start an emulator using command line options as describe in the next section.

      +
    6. +
    7. Name the AVD instance and select any other configuration options. +

      Caution: Do not select the Snapshot: Enabled +option. Snapshots are not supported for emulators with graphics acceleration enabled.

      +
    8. +
    9. Click Create AVD to save the emulator configuration.
    10. +
    + +

    If you set GPU emulation to Yes for your AVD, then graphics +acceleration is automatically enabled when you run it. If you did not enable GPU +emulation when you created the AVD, you can still enable it at runtime.

    + +

    To enable graphics acceleration at runtime for an AVD:

    + +
      +
    • If you are running the emulator from the command line, just include the {@code -gpu on} +option: +
      emulator -avd <avd_name> -gpu on
      +

      Note: You must specify an AVD configuration that uses +Android 4.0.3 (API Level 15, revision 3) or higher system image target. Graphics acceleration is not +available for earlier system images.

      +
    • +
    • If you are running the emulator from Eclipse, run your Android application using an AVD with +the {@code -gpu on} option enabled: +
        +
      1. In Eclipse, click your Android project folder and then select Run > Run +Configurations...
      2. +
      3. In the left panel of the Run Configurations dialog, select your Android +project run configuration or create a new configuration.
      4. +
      5. Click the Target tab.
      6. +
      7. Select the AVD you created in the previous procedure.
      8. +
      9. In the Additional Emulator Command Line Options field, enter:
        + {@code -gpu on}
      10. +
      11. Run your Android project using this run configuration.
      12. +
      +
    • +
    + + +

    Configuring Virtual Machine Acceleration

    + +

    Caution: As of SDK Tools Revision 17, the virtual machine +acceleration feature for the emulator is experimental; be alert for incompatibilities and errors +when using this feature.

    + +

    Many modern CPUs provide extensions for running virtual machines (VMs) more efficiently. Taking +advantage of these extensions with the Android emulator requires some additional configuration of +your development system, but can significantly improve the execution speed. Before attempting to use +this type of acceleration, you should first determine if your development system’s CPU supports one +of the following virtualization extensions technologies:

    + +
      +
    • Intel Virtualization Technology (VT, VT-x, vmx) extensions
    • +
    • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)
    • +
    + +

    The specifications from the manufacturer of your CPU should indicate if it supports +virtualization extensions. If your CPU does not support one of these virtualization technologies, +then you cannot use virtual machine acceleration.

    + +

    Note: Virtualization extensions are typically enabled through +your computer's BIOS and are frequently turned off by default. Check the documentation for your +system's motherboard to find out how to enable virtualization extensions.

    + +

    Once you have determined that your CPU supports virtualization extensions, make sure you can work +within these additional requirements of running an emulator inside an accelerated virtual +machine:

    + +
      +
    • x86 AVD Only - You must use an AVD that is uses an x86 system image target. +AVDs that use ARM-based system images cannot be accelerated using the emulator configurations +described here.
    • +
    • Not Inside a VM - You cannot run a VM-accelerated emulator inside another +virtual machine, such as a VirtualBox or VMWare-hosted virtual machine. You must run the emulator +directly on your system hardware.
    • +
    • Other VM Drivers - If you are running another virtualization technology on +your system such as VirtualBox or VMWare, you may need to unload the driver for that virtual machine +hosting software before running an accelerated emulator.
    • +
    • OpenGL® Graphics - Emulation of OpenGL ES graphics may not perform at the +same level as an actual device.
    • +
    + +

    To use virtual machine acceleration with the emulator, you need the following version of Android +development tools. Use the Android SDK +Manager to install these components:

    + +
      +
    • Android SDK Tools, Revision 17 or higher
    • +
    • Android x86-based system image
    • +
    + +

    If your development environment meets all of the requirements for running a VM-accelerated +emulator, you can use the AVD Manager to create an x86-based AVD configuration:

    + +
      +
    1. In the Android SDK Manager, make sure you have an x86-based System Image + installed for your target Android version. If you do not have an x86 System + Image installed, select one in the Android SDK Manager and install it. +

      Tip: System images are listed under each API Level in the SDK + Manager. An x86 system image may not be available for all API levels.

      +
    2. +
    3. Start the AVD Manager and create a new AVD with an x86 value for the +CPU/ABI field. You may need to select a specific Target value, or +select a Target value and then select a specific CPU/ABI +option.
    4. +
    5. Name the emulator instance and select any other configuration options.
    6. +
    7. Click Create AVD to save the emulator configuration.
    8. +
    + +

    Configuring VM Acceleration on Windows

    + +

    Virtual machine acceleration for Windows requires the installation of the Intel Hardware +Accelerated Execution Manager (Intel HAXM). The software requires an Intel CPU with +Virtualization Technology (VT) support and one of the following operating systems:

    + +
      +
    • Windows 7 (32/64-bit)
    • +
    • Windows Vista (32/64-bit)
    • +
    • Windows XP (32-bit only)
    • +
    + +

    To install the virtualization driver:

    + +
      +
    1. Start the Android SDK Manager, select Extras and then select Intel +Hardware Accelerated Execution Manager.
    2. +
    3. After the download completes, execute {@code +<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe}.
    4. +
    5. Follow the on-screen instructions to complete installation.
    6. +
    7. After installation completes, confirm that the virtualization driver is operating correctly by +opening a command prompt window and running the following command: +
      sc query intelhaxm
      +

      You should see a status message including the following information:

      +
      +SERVICE_NAME: intelhaxm
      +       ...
      +       STATE              : 4  RUNNING
      +       ...
      +
      +
    8. +
    + +

    To run an x86-based emulator with VM acceleration:

    +
      +
    • If you are running the emulator from the command line, just specify an x86-based AVD: +
      emulator -avd <avd_name>
      +

      Note: You must provide an x86-based AVD configuration +name, otherwise VM acceleration will not be enabled.

      +
    • +
    • If you are running the emulator from Eclipse, run your Android application with an x86-based +AVD: +
        +
      1. In Eclipse, click your Android project folder and then select Run > Run +Configurations...
      2. +
      3. In the left panel of the Run Configurations dialog, select your Android +project run configuration or create a new configuration.
      4. +
      5. Click the Target tab.
      6. +
      7. Select the x86-based AVD you created previously.
      8. +
      9. Run your Android project using this run configuration.
      10. +
      +
    • +
    + +

    You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running +its installer.

    + +

    You can stop using the virtualization driver by uninstalling it. Re-run the installer or use +the Control Panel to remove the software.

    + + +

    Configuring VM Acceleration on Mac

    + +

    Virtual machine acceleration on a Mac requires the installation of the Intel Hardware Accelerated +Execution Manager (Intel HAXM) kernel extension to allow the Android emulator to make use of CPU +virtualization extensions. The kernel extension is compatible with Mac OS X Snow Leopard (version +10.6.0) and higher.

    + +

    To install the Intel HAXM kernel extension:

    + +
      +
    1. Start the Android SDK Manager, select Extras and then select Intel +Hardware Accelerated Execution Manager. +
    2. After the download completes, execute + {@code <sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.dmg}.
    3. +
    4. Double click the IntelHAXM.mpkg icon to begin installation.
    5. +
    6. Follow the on-screen instructions to complete installation.
    7. +
    8. After installation completes, confirm that the new kernel extension is operating correctly by +opening a terminal window and running the following command: +
      kextstat | grep intel
      +

      You should see a status message containing the following extension name, indicating that the + kernel extension is loaded:

      +
      com.intel.kext.intelhaxm
      +
    9. +
    + +

    To run an x86-based emulator with VM acceleration:

    +
      +
    • If you are running the emulator from the command line, just specify an x86-based AVD: +
      emulator -avd <avd_name>
      +

      Note: You must provide an x86-based AVD configuration +name, otherwise VM acceleration will not be enabled.

      +
    • +
    • If you are running the emulator from Eclipse, run your Android application with an x86-based +AVD: +
        +
      1. In Eclipse, click your Android project folder and then select Run > Run +Configurations...
      2. +
      3. In the left panel of the Run Configurations dialog, select your Android +project run configuration or create a new configuration.
      4. +
      5. Click the Target tab.
      6. +
      7. Select the x86-based AVD you created previously.
      8. +
      9. Run your Android project using this run configuration.
      10. +
      +
    • +
    + +

    You can adjust the amount of memory available to the Intel HAXM kernel extension by re-running +the installer.

    + +

    You can stop using the virtualization kernel driver by uninstalling it. Before removing it, shut +down any running x86 emulators. To unload the virtualization kernel driver, run the following +command in a terminal window:

    + +
    sudo /System/Library/Extensions/intelhaxm.kext/Contents/Resources/uninstall.sh
    + +

    Configuring VM Acceleration on Linux

    + +

    Linux-based systems support virtual machine acceleration through the KVM software package. Follow +instructions for installing KVM on your +Linux system, and verify that KVM is enabled. In addition to following the installation +instructions, be aware of these configuration requirements:

    + +
      +
    • Running KVM requires specific user permissions, make sure you have sufficient permissions +according to the KVM installation instructions.
    • +
    • If you use another virtualization technology in your Linux platform, unload its kernel driver +before running the x86 emulator. For example, the VirtualBox driver program is {@code vboxdrv}.
    • +
    + +

    To run an x86-based emulator with VM acceleration:

    + +
      +
    • If you are running the emulator from the command line, start the emulator with an x86-based +AVD and include the KVM options: +
      emulator -avd <avd_name> -qemu -m 512 -enable-kvm
      +

      Note: You must provide an x86-based AVD configuration +name, otherwise VM acceleration will not be enabled.

      +
    • +
    • If you are running the emulator from Eclipse, run your Android application with an x86-based +AVD and include the KVM options: +
        +
      1. In Eclipse, click your Android project folder and then select Run > Run +Configurations...
      2. +
      3. In the left panel of the Run Configurations dialog, select your Android +project run configuration or create a new configuration.
      4. +
      5. Click the Target tab.
      6. +
      7. Select the x86-based AVD you created previously.
      8. +
      9. In the Additional Emulator Command Line Options field, enter: +
        -qemu -m 512 -enable-kvm
        +
      10. +
      11. Run your Android project using this run configuration.
      12. +
      +
    • +
    + +

    Important: When using the {@code -qemu} command line option, make sure +it is the last parameter in your command. All subsequent options are interpreted as qemu-specific +parameters.

    + + +

    SD Card Emulation

    + +

    You can create a disk image and then load it to the emulator at startup, to +simulate the presence of a user's SD card in the device. To do this, you can specify +an SD card image when you create an AVD, or you can use the mksdcard utility included +in the SDK.

    + +

    The following sections describe how to create an SD card disk image, how to copy +files to it, and how to load it in the emulator at startup.

    + +

    Note that you can only load a disk image at emulator startup. Similarly, you +can not remove a simulated SD card from a running emulator. However, you can +browse, send files to, and copy/remove files from a simulated SD card either +with adb or the emulator.

    + +

    The emulator supports emulated SDHC cards, so you can create an SD card image +of any size up to 128 gigabytes.

    + + +

    Creating an SD card image

    + +

    There are several ways of creating an SD card image. The easiest way is to use the +AVD Manager to create a new SD card by specifying a size when you create an AVD. +You can also use the {@code android} command line tool when creating an AVD. Just add the +-c option to your command:

    + +
    android create avd -n <avd_name> -t <targetID> -c <size>[K|M]
    + +

    The -c option can also be used to to specify a path to an SD card +image for the new AVD. For more information, see Managing Virtual Devices +from the Command Line. +

    + +

    You can also use the mksdcard tool, included in the SDK, to create a FAT32 disk +image that you can load in the emulator at startup. You can access mksdcard in +the tools/ directory of the SDK and create a disk image like this:

    + +
    mksdcard <size> <file>
    + +

    For example:

    + +
    mksdcard 1024M sdcard1.iso
    + +

    For more information, see mksdcard.

    + + +

    Copying files to an SD card image

    + +

    Once you have created the disk image, you can copy files to it prior to +loading it in the emulator. To copy files, you can mount the image as a loop +device and then copy the files to it, or you can use a utility such as {@code mtools} to +copy the files directly to the image. The {@code mtools} package is available for Linux, +Mac, and Windows.

    + +

    Alternatively, you can use the {@code adb push} command to move files onto an SD card image +while it is loaded in an emulator. For more information see the {@code adb push} documentation.

    + +

    Loading an SD card image

    + +

    By default, the emulator loads the SD card image that is stored with the active +AVD (see the -avd startup option).

    + +

    Alternatively, you can start the emulator with the +-sdcard flag and specify the name and path of your image (relative +to the current working directory):

    + +
    emulator -sdcard <filepath>
    + + +

    Working with Emulator Disk Images

    + +

    The emulator uses mountable disk images stored on your development machine to +simulate flash (or similar) partitions on an actual device. For example, it uses a +disk image containing an emulator-specific kernel, the Android system, a +ramdisk image, and writeable images for user data and simulated SD card.

    + +

    To run properly, the emulator requires access to a specific set of disk image +files. By default, the Emulator always looks for the disk images in the +private storage area of the AVD in use. If no images exist there when +the Emulator is launched, it creates the images in the AVD directory based on +default versions stored in the SDK.

    + +

    Note: The default storage location for +AVDs is in ~/.android/avd on OS X and Linux, C:\Documents and +Settings\<user>\.android\ on Windows XP, and +C:\Users\<user>\.android\ +on Windows Vista.

    + +

    To let you use alternate or custom versions of the image files, the emulator +provides startup options that override the default locations and filenames of +the image files. When you use one of these options, the emulator searches for the image +file under the image name or location that you specify; if it can not locate the +image, it reverts to using the default names and location.

    + +

    The emulator uses three types of image files: default image files, runtime +image files, and temporary image files. The sections below describe how to +override the location/name of each type of file.

    + +

    Default image files

    + +

    When the emulator launches, but does not find an existing user data image in +the active AVD's storage area, it creates a new one from a default version +included in the SDK. The default user data image is read-only. The image +files are read-only.

    + +

    The emulator provides the -system <dir> startup option to +let you override the location where the emulator looks for the default +user data image.

    + +

    The emulator also provides a startup option that lets you override the name +of the default user data image, as described in the following table. When you use the +option, the emulator looks in the default directory, or in a custom location +(if you specified -system <dir>).

    + + + + + + + + + + + + + + + + +
    NameDescriptionComments
    userdata.imgThe initial user-data disk imageOverride using -initdata <file>. Also see +-data <file>, below.
    + +

    Runtime images: user data and SD card

    + +

    At runtime, the emulator reads and writes data to two disk images: a +user-data image and (optionally) an SD card image. These images emulate the user-data +partition and removable storage media on actual device.

    + +

    The emulator provides a default user-data disk image. At startup, the emulator +creates the default image as a copy of the system user-data image (user-data.img), +described above. The emulator stores the new image with the files of the active AVD.

    + + + +

    The emulator provides startup options to let you override the actual names and storage +locations of the runtime images to load, as described in the following table. When you use one +of these options, the emulator looks for the specified file(s) in the current working directory, +in the AVD directory, or in a custom location (if you specified a path with the filename).

    + + + + + + + + + + + + + + + + + + + +
    NameDescriptionComments
    userdata-qemu.imgAn image to which the emulator writes runtime user-data for a unique user.Override using -data <filepath>, where <filepath> is the +path the image, relative to the current working directory. If you supply a filename only, +the emulator looks for the file in the current working directory. If the file at <filepath> does +not exist, the emulator creates an image from the default userdata.img, stores it under the name you +specified, and persists user data to it at shutdown.
    sdcard.imgAn image representing an SD card inserted into the emulated device.Override using -sdcard <filepath>, where <filepath> is the +path the image, relative to the current working directory. If you supply a filename only, +the emulator looks for the file in the current working directory.
    + +

    User-Data Image

    + +

    Each emulator instance uses a writeable user-data image to store user- and +session-specific data. For example, it uses the image to store a unique user's +installed application data, settings, databases, and files.

    + +

    At startup, the emulator attempts to load a user-data image stored during +a previous session. It looks for the file in the current working directory, +in the AVD directory described in a previous section and at the custom location/name +that you specified at startup.

    + +
      +
    • If it finds a user-data image, it mounts the image and makes it available +to the system for reading and writing of user data.
    • +
    • If it does not find one, it creates an image by copying the system user-data +image (userdata.img), described above. At device power-off, the system persists +the user data to the image, so that it will be available in the next session. +Note that the emulator stores the new disk image at the location/name that you +specify in -data startup option.
    • +
    + +

    Note: Because of the AVD configurations used in the emulator, +each emulator instance gets its own dedicated storage. There is no longer a need +to use the -d option to specify an instance-specific storage area.

    + +

    SD Card

    + +

    Optionally, you can create a writeable disk image that the emulator can use +to simulate removeable storage in an actual device. For information about how to create an +emulated SD card and load it in the emulator, see SD Card Emulation

    + +

    You can also use the android tool to automatically create an SD Card image +for you, when creating an AVD. For more information, see Managing Virtual Devices with AVD +Manager. + + +

    Temporary Images

    + +

    The emulator creates two writeable images at startup that it deletes at +device power-off. The images are:

    + +
      +
    • A writable copy of the Android system image
    • +
    • The /cache partition image
    • +
    + +

    The emulator does not permit renaming the temporary system image or +persisting it at device power-off.

    + +

    The /cache partition image is initially empty, and is used by +the browser to cache downloaded web pages and images. The emulator provides an +-cache <file>, which specifies the name of the file in which +to persist the /cache image at device power-off. If <file> + does not exist, the emulator creates it as an empty file.

    + +

    You can also disable the use of the cache partition by specifying the +-nocache option at startup.

    + + +

    Emulator Networking

    + +

    The emulator provides versatile networking capabilities that you can use to +set up complex modeling and testing environments for your application. The +sections below introduce the emulator's network architecture and capabilities. +

    + +

    Network Address Space

    + +

    Each instance of the emulator runs behind a virtual router/firewall service +that isolates it from your development machine's network interfaces and settings +and from the internet. An emulated device can not see your development machine +or other emulator instances on the network. Instead, it sees only that it is +connected through Ethernet to a router/firewall.

    + +

    The virtual router for each instance manages the 10.0.2/24 network address +space — all addresses managed by the router are in the form of +10.0.2.<xx>, where <xx> is a number. Addresses within this space are +pre-allocated by the emulator/router as follows:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Network AddressDescription
    10.0.2.1Router/gateway address
    10.0.2.2Special alias to your host loopback interface (i.e., 127.0.0.1 on your +development machine)
    10.0.2.3First DNS server
    10.0.2.4 / 10.0.2.5 / 10.0.2.6Optional second, third and fourth DNS server (if any)
    10.0.2.15The emulated device's own network/ethernet interface
    127.0.0.1The emulated device's own loopback interface
    + +

    Note that the same address assignments are used by all running emulator +instances. That means that if you have two instances running concurrently on +your machine, each will have its own router and, behind that, each will have an +IP address of 10.0.2.15. The instances are isolated by a router and can +not see each other on the same network. For information about how to +let emulator instances communicate over TCP/UDP, see Connecting Emulator Instances.

    + +

    Also note that the address 127.0.0.1 on your development machine corresponds +to the emulator's own loopback interface. If you want to access services running +on your development machine's loopback interface (a.k.a. 127.0.0.1 on your +machine), you should use the special address 10.0.2.2 instead.

    + +

    Finally, note that each emulated device's pre-allocated addresses are +specific to the Android emulator and will probably be very different on real +devices (which are also very likely to be NAT-ed, i.e., behind a +router/firewall)

    + + +

    Local Networking Limitations

    + +

    Android applications running in an emulator can connect to the network available on your +workstation. However, they connect through the emulator, not directly to hardware, and the emulator +acts like a normal application on your workstation. This means that the emulator, and thus your +Android applications, are subject to some limitations:

    + +
      +
    • Communication with the emulated device may be blocked by a firewall +program running on your machine.
    • +
    • Communication with the emulated device may be blocked by another +(physical) firewall/router to which your machine is connected.
    • +
    + +

    The emulator's virtual router should be able to handle all outbound TCP and +UDP connections/messages on behalf of the emulated device, provided your +development machine's network environment allows it to do so. There are no +built-in limitations on port numbers or ranges except the one imposed by your +host operating system and network.

    + +

    Depending on the environment, the emulator may not be able to support other +protocols (such as ICMP, used for "ping") might not be supported. Currently, the +emulator does not support IGMP or multicast.

    + +

    Using Network Redirection

    + +

    To communicate with an emulator instance behind its virtual router, you need +to set up network redirection on the virtual router. Clients can then connect +to a specified guest port on the router, while the router directs traffic +to/from that port to the emulated device's host port.

    + +

    To set up the network redirection, you create a mapping of host and guest +ports/addresses on the the emulator instance. There are two ways to set up +network redirection: using emulator console commands and using the ADB tool, as +described below.

    + + +

    Setting up Redirection through the Emulator Console

    + +

    Each emulator instance provides a control console the you can connect to, to +issue commands that are specific to that instance. You can use the +redir console command to set up redirection as needed for an +emulator instance.

    + +

    First, determine the console port number for the target emulator instance. +For example, the console port number for the first emulator instance launched is +5554. Next, connect to the console of the target emulator instance, specifying +its console port number, as follows:

    + +
    telnet localhost 5554
    + +

    Once connected, use the redir command to work with redirection. +To add a redirection, use:

    + +
    add <protocol>:<host-port>:<guest-port>
    +
    + +

    where <protocol> is either tcp or udp, +and <host-port> and <guest-port> sets the +mapping between your own machine and the emulated system, respectively.

    + +

    For example, the following command sets up a redirection that handles all +incoming TCP connections to your host (development) machine on 127.0.0.1:5000 +and will pass them through to the emulated system's 10.0.2.15:6000.:

    + +
    redir add tcp:5000:6000
    + +

    To delete a redirection, you can use the redir del command. To +list all redirection for a specific instance, you can use redir +list. For more information about these and other console commands, see +Using the Emulator Console.

    + +

    Note that port numbers are restricted by your local environment. this typically +means that you cannot use host port numbers under 1024 without special +administrator privileges. Also, you won't be able to set up a redirection for a +host port that is already in use by another process on your machine. In that +case, redir generates an error message to that effect.

    + +

    Setting Up Redirection through ADB

    + +

    The Android Debug Bridge (ADB) tool provides port forwarding, an alternate +way for you to set up network redirection. For more information, see Forwarding Ports in the ADB +documentation.

    + +

    Note that ADB does not currently offer any way to remove a redirection, +except by killing the ADB server.

    + + +

    Configuring the Emulator's DNS Settings

    + +

    At startup, the emulator reads the list of DNS servers that your system is +currently using. It then stores the IP addresses of up to four servers on this +list and sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, +10.0.2.5 and 10.0.2.6 as needed.

    + +

    On Linux and OS X, the emulator obtains the DNS server addresses by parsing +the file /etc/resolv.conf. On Windows, the emulator obtains the +addresses by calling the GetNetworkParams() API. Note that this +usually means that the emulator ignores the content of your "hosts" file +(/etc/hosts on Linux/OS X, %WINDOWS%/system32/HOSTS + on Windows).

    + +

    When starting the emulator at the command line, you can also use the +-dns-server <serverList> option to manually specify the +addresses of DNS servers to use, where <serverList> is a comma-separated +list of server names or IP addresses. You might find this option useful if you +encounter DNS resolution problems in the emulated network (for example, an +"Unknown Host error" message that appears when using the web browser).

    + + +

    Using the Emulator with a Proxy

    + +

    If your emulator must access the Internet through a proxy server, you can use +the -http-proxy <proxy> option when starting the emulator, to +set up the appropriate redirection. In this case, you specify proxy information +in <proxy> in one of these formats:

    + +
    http://<machineName>:<port>
    + +

    or

    + +
    http://<username>:<password>@<machineName>:<port>
    + +

    The -http-proxy option forces the emulator to use the specified +HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not +currently supported.

    + +

    Alternatively, you can define the environment variable +http_proxy to the value you want to use for +<proxy>. In this case, you do not need to specify a value for +<proxy> in the -http-proxy command — the +emulator checks the value of the http_proxy environment variable at +startup and uses its value automatically, if defined.

    + +

    You can use the -verbose-proxy option to diagnose proxy +connection problems.

    + + +

    Interconnecting Emulator Instances

    + +

    To allow one emulator instance to communicate with another, you must set up +the necessary network redirection as illustrated below.

    + +

    Assume that your environment is

    + +
      +
    • A is you development machine
    • +
    • B is your first emulator instance, running on A
    • +
    • C is your second emulator instance, also running on A
    • +
    + +

    and you want to run a server on B, to which C will connect, here is how you +could set it up:

    + +
      +
    1. Set up the server on B, listening to +10.0.2.15:<serverPort>
    2. +
    3. On B's console, set up a redirection from +A:localhost:<localPort> to +B:10.0.2.15:<serverPort>
    4. +
    5. On C, have the client connect to 10.0.2.2:<localPort>
    6. +
    + +

    For example, if you wanted to run an HTTP server, you can select +<serverPort> as 80 and <localPort> as +8080:

    + +
      +
    • B listens on 10.0.2.15:80
    • +
    • On B's console, issue redir add tcp:8080:80
    • +
    • C connects to 10.0.2.2:8080
    • +
    + +

    Sending a Voice Call or SMS to Another Emulator Instance

    + +

    The emulator automatically forwards simulated voice calls and SMS messages from one instance to +another. To send a voice call or SMS, use the dialer application or SMS application, respectively, +from one of the emulators.

    + +

    To initiate a simulated voice call to another emulator instance:

    +
      +
    1. Launch the dialer application on the originating emulator instance.
    2. +
    3. As the number to dial, enter the console port number of the instance you'd like to call. You can determine + the console port number of the target instance by checking its window title, where the + console port number is reported as "Android Emulator (<port>).
    4. +
    5. Press "Dial". A new inbound call appears in the target emulator instance.
    6. +
    + +

    To send an SMS message to another emulator instance, launch the SMS application (if available). Specify the console port number of the target emulator instance as as the SMS address, enter the message text, and send the message. The message is delivered to the target emulator instance.

    + +

    You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see Telephony Emulation and SMS Emulation. + + +

    Using the Emulator Console

    + +

    Each running emulator instance provides a console that lets you query and control the emulated +device environment. For example, you can use the console to manage port redirection, network +characteristics, and telephony events while your application is running on the emulator. To +access the console and enter commands, use telnet to connect to the console's port number.

    + +

    To connect to the console of any running emulator instance at any time, use this command:

    + +
    telnet localhost <console-port>
    + +

    An emulator instance occupies a pair of adjacent ports: a console port and an {@code adb} port. +The port numbers differ by 1, with the {@code adb} port having the higher port number. The console +of the first emulator instance running on a given machine uses console port 5554 and {@code adb} +port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, +5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.

    + +

    To connect to the emulator console, you must specify a valid console port. If multiple emulator instances are running, you need to determine the console port of the emulator instance you want to connect to. You can find the instance's console port listed in the title of the instance window. For example, here's the window title for an instance whose console port is 5554:

    + +

    Android Emulator (5554)

    + +

    Alternatively, you can use the adb devices command, which prints a list of running emulator instances and their console port numbers. For more information, see Querying for Emulator/Device Instances in the adb documentation.

    + +

    Note: The emulator listens for connections on ports 5554-5587 and accepts connections only from localhost.

    + +

    Once you are connected to the console, you can then enter help [command] to see a list of console commands and learn about specific commands.

    + +

    To exit the console session, use quit or exit.

    + +

    The following sections below describe the major functional areas of the console.

    + + +

    Port Redirection

    + +

    You can use the console to add and remove port redirection while the emulator is running. After +you connect to the console, manage port redirection by entering the following command:

    + +
    redir <list|add|del> 
    + +

    The redir command supports the subcommands listed in the table below.

    + + + + + + + + + + + + + + + + + + + + + + + + +
    Subcommand + DescriptionComments
    listList the current port redirection. 
    add <protocol>:<host-port>:<guest-port>Add a new port redirection.
    • <protocol> must be either "tcp" or "udp"
    • +
    • <host-port> is the port number to open on the host
    • +
    • <guest-port> is the port number to route data to on the emulator/device
    • +
    del <protocol>:<host-port>Delete a port redirection.The meanings of <protocol> and <host-port> are listed in the previous row.
    + + +

    Geo Location Provider Emulation

    + +

    You can use the console to set the geographic location reported to the applications running +inside an emulator. Use the geo command to send a simple GPS fix to the +emulator, with or without NMEA 1083 formatting:

    + +
    geo <fix|nmea>
    + +

    The geo command supports the subcommands listed in the table below.

    + + + + + + + + + + + + + + + + + + +
    SubcommandDescriptionComments
    fix <longitude> <latitude> [<altitude>]Send a simple GPS fix to the emulator instance.Specify longitude and latitude in decimal degrees. Specify altitude in meters.
    nmea <sentence>Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem.<sentence> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are currently supported.
    + +

    You can issue the geo command as soon as an emulator instance is running. The +emulator sets the location you enter by creating a mock location provider. This provider responds to +location listeners set by applications, and also supplies the location to the {@link +android.location.LocationManager}. Any application can query the location manager to obtain the +current GPS fix for the emulated device by calling: + +

    LocationManager.getLastKnownLocation("gps")
    + +

    For more information about the Location Manager, see {@link android.location.LocationManager}. +

    + +

    Hardware Events Emulation

    + +

    The {@code event} console commands sends hardware events to the emulator. The syntax for this +command is as follows:

    + +
    event <send|types|codes|text>
    + +

    The event command supports the subcommands listed in the table below.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Subcommand + DescriptionComments
    send <type>:<code>:<value> [...]Send one or more events to the Android kernel. You can use text names or integers for <type> and <value>.
    typesList all <type> string aliases supported by the event subcommands. 
    codes <type>List all <codes> string aliases supported by the event + subcommands for the specified <type>. 
    event text <message>Simulate keypresses to send the specified string of characters as a message,The message must be a UTF-8 string. Unicode posts will be reverse-mapped according to the current device keyboard. Unsupported characters will be discarded silently.
    + + +

    Device Power Characteristics

    + +

    The {@code power} command controls the power state reported by the emulator to applications. The +syntax for this command is as follows:

    + +
    power <display|ac|status|present|health|capacity>
    + +

    The event command supports the subcommands listed in the table below.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Subcommand DescriptionComments
    displayDisplay battery and charger state. 
    ac <on|off>Set AC charging state to on or off.  
    status <unknown|charging|discharging|not-charging|full>Change battery status as specified. 
    present <true|false>Set battery presence state. 
    health <unknown|good|overheat|dead|overvoltage|failure>Set battery health state. 
    power health <percent>Set remaining battery capacity state (0-100). 
    + + +

    Network Status

    + +

    You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use the netstatus command. Here's an example of the command and its output.

    + +
    network status
    +
    + + +

    Network Delay Emulation

    + +

    The emulator lets you simulate various network latency levels, so that you can test your +application in an environment more typical of the actual conditions in which it will run. You can +set a latency level or range at emulator startup or you can use the console to change the latency, +while the application is running in the emulator.

    + +

    To set latency at emulator startup, use the -netdelay emulator option with a +supported <delay> value, as listed in the table below. Here are some +examples:

    + +
    emulator -netdelay gprs
    +emulator -netdelay 40 100
    + +

    To make changes to network delay while the emulator is running, connect to the console and use +the netdelay command with a supported <delay> value from the table +below.

    + +
    network delay gprs
    + +

    The format of network <delay> is one of the following (numbers are milliseconds):

    + + + + + + + + + + + + + + + + + + + + + + + +
    ValueDescriptionComments
    gprsGPRS(min 150, max 550)
    edgeEDGE/EGPRS(min 80, max 400)
    umtsUMTS/3G(min 35, max 200)
    noneNo latency(min 0, max 0)
    <num>Emulate an exact latency (milliseconds). 
    <min>:<max>Emulate an specified latency range (min, max milliseconds). 
    + + +

    Network Speed Emulation

    + +

    The emulator also lets you simulate various network transfer rates. +You can set a transfer rate or range at emulator startup or you can use the console to change the +rate, while the application is running in the emulator.

    + +

    To set the network speed at emulator startup, use the -netspeed emulator option with a supported +<speed> value, as listed in the table below. Here are some examples:

    + +
    emulator -netspeed gsm
    +emulator -netspeed 14.4 80
    + +

    To make changes to network speed while the emulator is running, connect to the console and use +the netspeed command with a supported <speed> value from the table +below.

    + +
    network speed 14.4 80
    + +

    The format of network <speed> is one of the following (numbers are +kilobits/sec):

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ValueDescriptionComments
    gsmGSM/CSD(Up: 14.4, down: 14.4)
    hscsdHSCSD(Up: 14.4, down: 43.2)
    gprsGPRS(Up: 40.0, down: 80.0)
    edgeEDGE/EGPRS(Up: 118.4, down: 236.8)
    umtsUMTS/3G(Up: 128.0, down: 1920.0)
    hsdpaHSDPA(Up: 348.0, down: 14400.0)
    fullno limit(Up: 0.0, down: 0.0)
    <num>Set an exact rate used for both upload and download.
    <up>:<down>Set exact rates for upload and download separately.
    + + +

    Telephony Emulation

    + +

    The Android emulator includes its own GSM emulated modem that lets you simulate telephony +functions in the emulator. For example, you can simulate inbound phone calls, establish data +connections and terminate them. The Android system handles simulated calls exactly as it would +actual calls. The emulator does not support call audio.

    + +

    You can use the {@code gsm} command to access the emulator's telephony functions after connecting +to the console. The syntax for this command is as follows:

    + +
    gsm <call|accept|busy|cancel|data|hold|list|voice|status> 
    + +

    The gsm command supports the subcommands listed in the table below.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Subcommand DescriptionComments
    call <phonenumber>Simulate an inbound phone call from <phonenumber>. 
    accept <phonenumber>Accept an inbound call from <phonenumber> and change the call's state "active".You can change a call's state to "active" only if its current state is "waiting" or "held".
    busy <phonenumber>Close an outbound call to <phonenumber> and change the call's state to "busy".You can change a call's state to "busy" only if its current state is "waiting".
    cancel <phonenumber>Terminate an inbound or outbound phone call to/from <phonenumber>. 
    data <state>Change the state of the GPRS data connection to <state>.Supported <state> values are:
    +
      +
    • unregistered -- No network available
    • +
    • home -- On local network, non-roaming
    • +
    • roaming -- On roaming network
    • +
    • searching -- Searching networks
    • +
    • denied -- Emergency calls only
    • +
    • off -- Same as 'unregistered'
    • +
    • on -- same as 'home'
    • +
    +
    holdChange the state of a call to "held". You can change a call's state to "held" only if its current state is "active" or "waiting".
    listList all inbound and outbound calls and their states. 
    voice <state>Change the state of the GPRS voice connection to <state>.Supported <state> values are:
    +
      +
    • unregistered -- No network available
    • +
    • home -- On local network, non-roaming
    • +
    • roaming -- On roaming network
    • +
    • searching -- Searching networks
    • +
    • denied -- Emergency calls only
    • +
    • off -- Same as 'unregistered'
    • +
    • on -- Same as 'home'
    • +
    +
    statusReport the current GSM voice/data state.Values are those described for the voice and data commands.
    + + +

    SMS Emulation

    + +

    The Android emulator console lets you generate an SMS message and direct it to an emulator +instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using +the following command:

    + +
    sms send <senderPhoneNumber> <textmessage>
    + +

    where <senderPhoneNumber> contains an arbitrary numeric string.

    + +

    The console forwards the SMS message to the Android framework, which passes it through to an application that handles that message type.

    + + +

    VM State

    + +

    You can use the vm command to control the VM on an emulator instance. The syntax for +this command is as follows:

    + +
    vm <start|stop|status>
    + +

    The vm command supports the subcommands listed in the table below.

    + + + + + + + + + + + + + + + + + + + + + + +
    SubcommandDescriptionComments
    startStart the VM on the instance.  
    stopStop the VM on the instance.  
    startDisplay the current status of the VM (running or stopped).  
    + + +

    Emulator Window

    + +

    You can use the window command to manage the emulator window. The syntax for this +command is as follows:

    + +
    window <scale>
    + +

    The vm command supports the subcommands listed in the table below.

    + + + + + + + + + + + + +
    SubcommandDescriptionComments
    scale <scale>Scale the emulator window.A number between 0.1 and 3 that sets the scaling factor. You can + also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" + tells the emulator to select the best window size.
    + + +

    Terminating an Emulator Instance

    + +

    You can terminate an emulator instance through the console, using the kill command.

    + + +

    Emulator Limitations

    + +

    The functional limitations of the emulator include:

    +
      +
    • No support for placing or receiving actual phone calls. You can simulate phone calls (placed + and received) through the emulator console, however.
    • +
    • No support for USB connections
    • +
    • No support for device-attached headphones
    • +
    • No support for determining network connected state
    • +
    • No support for determining battery charge level and AC charging state
    • +
    • No support for determining SD card insert/eject
    • +
    • No support for Bluetooth
    • +
    + + +

    Troubleshooting Emulator Problems

    + +

    The {@code adb} utility sees the emulator as an actual physical device. For this reason, you +might have to use the {@code -d} flag with some common {@code adb} commands, such as +install. The {@code -d} flag lets you specify which of several connected devices to use +as the target of a command. If you don't specify {@code -d}, the emulator targets the first +device in its list. For more information about {@code adb}, see Android Debug Bridge.

    + +

    For emulators running on Mac OS X, if you see an error {@code Warning: No DNS servers found} +when starting the emulator, check to see whether you have an /etc/resolv.conf file. If +not, please run the following line in a command window:

    +
    ln -s /private/var/run/resolv.conf /etc/resolv.conf
    + +

    See Frequently Asked Questions for more +troubleshooting information.

    diff --git a/docs/html/tools/devices/index.jd b/docs/html/tools/devices/index.jd new file mode 100644 index 000000000000..bec226810323 --- /dev/null +++ b/docs/html/tools/devices/index.jd @@ -0,0 +1,78 @@ +page.title=Managing Virtual Devices +@jd:body + + +

    An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual + device by defining hardware and software options to be emulated by the Android Emulator.

    + +

    The easiest way to create an AVD is to use the graphical AVD Manager, which you launch + from Eclipse by clicking Window > AVD Manager. You can also start the AVD +Manager from the command line by calling the android tool with the avd +options, from the <sdk>/tools/ directory.

    + +

    You can also create AVDs on the command line by passing the android tool options. + For more information on how to create AVDs in this manner, see Managing Virtual + Devices from the Command Line.

    + +

    An AVD consists of:

    + +
      +
    • A hardware profile: Defines the hardware features of the virtual + device. For example, you can define whether the device has a camera, whether it uses a physical + QWERTY keyboard or a dialing pad, how much memory it has, and so on.
    • + +
    • A mapping to a system image: You can define what version of the Android platform will run + on the virtual device. You can choose a version of the standard Android platform or the system + image packaged with an SDK add-on.
    • + +
    • Other options: You can specify the emulator skin you want to use with the AVD, which lets + you control the screen dimensions, appearance, and so on. You can also specify the emulated SD + card to use with the AVD.
    • + +
    • A dedicated storage area on your development machine: the device's user data (installed + applications, settings, and so on) and emulated SD card are stored in this area.
    • +
    + +

    You can create as many AVDs as you need, based on the types of device you want to model. + To thoroughly test your application, you should create an AVD for each general device configuration + (for example, different screen sizes and platform versions) with which your application is compatible + and test your application on each one.

    + +

    Keep these points in mind when you are selecting a system image target for your AVD:

    + +
      +
    • The API Level of the target is important, because your application will not be able to run + on a system image whose API Level is less than that required by your application, as specified + in the + minSdkVersion attribute of the application's manifest file. For more + information about the relationship between system API Level and application + minSdkVersion, see Specifying Minimum System API Version.
    • + +
    • You should create at least one AVD that uses a target whose API Level is greater than that required + by your application, because it allows you to test the + forward-compatibility of your application. Forward-compatibility testing ensures that, when + users who have downloaded your application receive a system update, your application will + continue to function normally.
    • + +
    • If your application declares a + uses-library + element in its manifest file, the application can only run on a system image in which that external + library is present. If you want to run your application on an emulator, create an AVD that + includes the required library. Usually, you must create such an AVD using an Add-on component for the + AVD's platform (for example, the Google APIs Add-on contains the Google Maps library).
    • +
    + +

    To learn how to manage AVDs using a graphical tool, read Managing AVDs with AVD Manager. To +learn how to manage AVDs on the command line, read + Managing AVDs + from the Command Line.

    + + + + + + diff --git a/docs/html/tools/devices/managing-avds-cmdline.jd b/docs/html/tools/devices/managing-avds-cmdline.jd new file mode 100644 index 000000000000..ba353c1538da --- /dev/null +++ b/docs/html/tools/devices/managing-avds-cmdline.jd @@ -0,0 +1,369 @@ +page.title=Managing AVDs from the Command Line +parent.title=Managing Virtual Devices +parent.link=index.html +@jd:body + + + + +

    The android tool lets you manage AVDs on the command line. For a complete reference +of the command line options that you can use, see the reference for the +android tool.

    + + + +

    Listing Targets

    + +

    To generate a list of system image targets, use this command:

    + +
    android list targets
    + +

    The android tool scans the <sdk>/platforms/ and +<sdk>/add-ons/ directories looking for valid system images and +then generates the list of targets. Here's an example of the command output: +

    + +
    Available Android targets:
    +id: 1 or "android-3"
    +     Name: Android 1.5
    +     Type: Platform
    +     API level: 3
    +     Revision: 4
    +     Skins: QVGA-L, HVGA-L, HVGA (default), HVGA-P, QVGA-P
    +id: 2 or "android-4"
    +     Name: Android 1.6
    +     Type: Platform
    +     API level: 4
    +     Revision: 3
    +     Skins: QVGA, HVGA (default), WVGA800, WVGA854
    +id: 3 or "android-7"
    +     Name: Android 2.1-update1
    +     Type: Platform
    +     API level: 7
    +     Revision: 2
    +     Skins: QVGA, WQVGA400, HVGA (default), WVGA854, WQVGA432, WVGA800
    +id: 4 or "android-8"
    +     Name: Android 2.2
    +     Type: Platform
    +     API level: 8
    +     Revision: 2
    +     Skins: WQVGA400, QVGA, WVGA854, HVGA (default), WVGA800, WQVGA432
    +id: 5 or "android-9"
    +     Name: Android 2.3
    +     Type: Platform
    +     API level: 9
    +     Revision: 1
    +     Skins: HVGA (default), WVGA800, WQVGA432, QVGA, WVGA854, WQVGA400
    +
    + + + +

    Creating AVDs

    + +

    In addition to creating AVDs with the +AVD Manager user interface, +you can also create them by passing in command line arguments to the android tool. +

    + +

    Open a terminal window and change to +the <sdk>/tools/ directory, if needed.

    + +

    To create each AVD, you issue the command android create avd, +with options that specify a name for the new AVD and the system image you want +to run on the emulator when the AVD is invoked. You can specify other options on +the command line also, such as the emulated SD card size, the emulator skin, or a custom +location for the user data files.

    + +

    Here's the command-line usage for creating an AVD:

    + +
    android create avd -n <name> -t <targetID> [-<option> <value>] ... 
    + +

    You can use any name you want for the AVD, but since you are likely to be +creating multiple AVDs, you should choose a name that lets you recognize the +general characteristics offered by the AVD. The target ID is an integer assigned by the +android tool. The target ID is not derived from the system image name, +version, or API Level, or other attribute, so you need to run the android list targets +command to list the target ID of each system image. You should do this before you run +the android create avd command. See the android +tool documentation for more information on the command line options.

    + + +

    When you've selected the target you want to use and made a note of its ID, +use the android create avd command to create the AVD, supplying the +target ID as the -t argument. Here's an example that creates an +AVD with name "my_android1.5" and target ID "2" (the standard Android 1.5 +system image in the list above):

    + +
    android create avd -n my_android1.5 -t 2
    + +

    If the target you selected was a standard Android system image ("Type: +platform"), the android tool next asks you whether you want to +create a custom hardware profile.

    +
    Android 1.5 is a basic Android platform.
    +Do you wish to create a custom hardware profile [no]
    + +

    If you want to set custom hardware emulation options for the AVD, enter +"yes" and set values as needed. If you want to use the default hardware +emulation options for the AVD, just press the return key (the default is "no"). +The android tool creates the AVD with name and system image mapping you +requested, with the options you specified. For more information, see +Setting Hardware Emulation Options. + +

    Note: If you are creating an AVD whose target is an SDK add-on, the +android tool does not allow you to set hardware emulation options. +It assumes that the provider of the add-on has set emulation options +appropriately for the device that the add-on is modeling, and so prevents you +from resetting the options.

    + + +

    Customize the device resolution or density

    + +

    When testing your application, we recommend that you test your application in several different +AVDs, using different screen configurations (different combinations of size and density). In +addition, you should set up the AVDs to run at a physical size that closely matches an actual +device.

    + +

    To set up your AVDs for a specific resolution or density, follow these steps:

    + +
      +
    1. Use the create avd command to create a new AVD, specifying +the --skin option with a value that references either a default +skin name (such as "WVGA800") or a custom skin resolution (such as 240x432). +Here's an example: +
      android create avd -n <name> -t <targetID> --skin WVGA800
      +
    2. +
    3. To specify a custom density for the skin, answer "yes" when asked whether +you want to create a custom hardware profile for the new AVD.
    4. +
    5. Continue through the various profile settings until the tool asks you to +specify "Abstracted LCD density" (hw.lcd.density). Enter an appropriate +value, such as "120" for a low-density screen, "160" for a medium density screen, +or "240" for a high-density screen.
    6. +
    7. Set any other hardware options and complete the AVD creation.
    8. +
    + +

    In the example above (WVGA medium density), the new AVD will emulate a 5.8" +WVGA screen.

    + +

    As an alternative to adjusting the emulator skin configuration, you can use +the emulator skin's default density and add the -dpi-device option +to the emulator command line when +starting the AVD. For example:

    + +
    emulator -avd WVGA800 -scale 96dpi -dpi-device 160
    + + + +

    Default location of AVD files

    + +

    When you create an AVD, the android tool creates a dedicated directory for it +on your development computer. The directory contains the AVD configuration file, +the user data image and SD card image (if available), and any other files +associated with the device. Note that the directory does not contain a system +image — instead, the AVD configuration file contains a mapping to the +system image, which it loads when the AVD is launched.

    + +

    The android tool also creates an <AVD_name>.ini file for the AVD at the +root of the .android/avd/ directory on your computer. The file specifies the +location of the AVD directory and always remains at the root the .android +directory.

    + +

    By default, the android tool creates the AVD directory inside +~/.android/avd/ (on Linux/Mac), C:\Documents and +Settings\<user>\.android\ on Windows XP, and +C:\Users\<user>\.android\ on Windows 7 and Vista. +If you want to use a custom location for the AVD directory, you +can do so by using the -p <path> option when +you create the AVD:

    + +
    android create avd -n my_android1.5 -t 2 -p path/to/my/avd
    + +

    If the .android directory is hosted on a network drive, we recommend using +the -p option to place the AVD directory in another location. +The AVD's .ini file remains in the .android directory on the network +drive, regardless of the location of the AVD directory. + + +

    Setting hardware emulation options

    + +

    When you are creating a new AVD that uses a standard Android system image ("Type: +platform"), the android tool lets you set hardware emulation +options for virtual device. The table below lists the options available and the +default values, as well as the names of properties that store the emulated +hardware options in the AVD's configuration file (the config.ini file in the +AVD's local directory).

    + +

    Table 1. Available hardware profile options for AVDs and +the default values

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CharacteristicDescriptionProperty
    Device ram sizeThe amount of physical RAM on the device, in megabytes. Default value is "96". +hw.ramSize
    Touch-screen supportWhether there is a touch screen or not on the device. Default value is "yes".hw.touchScreen + +
    Trackball support Whether there is a trackball on the device. Default value is "yes".hw.trackBall
    Keyboard supportWhether the device has a QWERTY keyboard. Default value is "yes".hw.keyboard
    DPad supportWhether the device has DPad keys. Default value is "yes".hw.dPad
    GSM modem supportWhether there is a GSM modem in the device. Default value is "yes".hw.gsmModem
    Camera supportWhether the device has a camera. Default value is "no".hw.camera
    Maximum horizontal camera pixelsDefault value is "640".hw.camera.maxHorizontalPixels
    Maximum vertical camera pixelsDefault value is "480".hw.camera.maxVerticalPixels
    GPS supportWhether there is a GPS in the device. Default value is "yes".hw.gps
    Battery supportWhether the device can run on a battery. Default value is "yes".hw.battery
    AccelerometerWhether there is an accelerometer in the device. Default value is "yes".hw.accelerometer
    Audio recording supportWhether the device can record audio. Default value is "yes".hw.audioInput
    Audio playback supportWhether the device can play audio. Default value is "yes".hw.audioOutput
    SD Card supportWhether the device supports insertion/removal of virtual SD Cards. Default value is "yes".hw.sdCard
    Cache partition supportWhether we use a /cache partition on the device. Default value is "yes".disk.cachePartition
    Cache partition sizeDefault value is "66MB".disk.cachePartition.size
    Abstracted LCD densitySets the generalized density characteristic used by the AVD's screen. Default value is "160".hw.lcd.density
    Trackball supportWhether there is a trackball present.hw.trackBall
    + + +

    Moving an AVD

    + +

    If you want to move or rename an AVD, you can do so using this command:

    + +
    android move avd -n <name> [-<option> <value>] ...
    + +

    Updating an AVD

    + +

    If, for any reason, the platform/add-on root folder has its name changed (maybe because the user has installed an update of the platform/add-on) then the AVD will not be able to load the system image that it is mapped to. In this case, the android list targets command will produce this output: + +

    The following Android Virtual Devices could not be loaded: 
    +Name: foo 
    +Path: <path>/.android/avd/foo.avd 
    +Error: Invalid value in image.sysdir. Run 'android update avd -n foo' 
    + +

    To fix this error, use the android update avd command to recompute the path to the system images.

    + +

    Deleting an AVD

    + +

    You can use the android tool to delete an AVD. Here is the command usage:

    + +
    android delete avd -n <name> 
    + +

    When you issue the command, the android tool looks for an AVD matching the +specified name deletes the AVD's directory and files.

    diff --git a/docs/html/tools/devices/managing-avds.jd b/docs/html/tools/devices/managing-avds.jd new file mode 100644 index 000000000000..412bd913d613 --- /dev/null +++ b/docs/html/tools/devices/managing-avds.jd @@ -0,0 +1,237 @@ +page.title=Managing AVDs with AVD Manager +parent.title=Managing Virtual Devices +parent.link=index.html +@jd:body + +
    +
    +

    In this document

    + +
      +
    1. Creating an AVD +
        +
      1. Hardware options
      2. +
      +
    2. +
    +
    +
    + +

    The AVD Manager is an easy to use user interface to manage your AVD (Android Virtual Device) + configurations. An AVD is a device configuration for the Android emulator that allows you to + model different configurations of Android-powered devices. When you start the AVD Manager in Eclipse + or run the android tool on the command line, you will see the AVD Manager as shown in + figure 1:

    + + + +

    Figure 1. Screenshot of the AVD Manager.

    + +

    From the main screen, you can create, delete, repair and start AVDs as well as see the details + of each AVD.

    + + +

    Creating an AVD

    + +

    You can create as many AVDs as you would like to test on. It is recommended that you test your + applications on all API levels higher than the target API level for your application.

    + +

    To create an AVD:

    + +
      +
    1. Start the AVD Manager: + +
        +
      • In Eclipse: select Window > AVD Manager, or click + the AVD Manager icon in the Eclipse toolbar.
      • + +
      • In other IDEs: Navigate to your SDK's tools/ directory and execute the + android tool with no arguments.
      • +
      +
    2. + +
    3. In the Virtual Devices panel, you'll see a list of existing AVDs. Click + New to create a new AVD. The Create New AVD dialog appears.

      + + AVD Dialog +

      Figure 2. Screenshot of the Create AVD window

      +
    4. + +
    5. Fill in the details for the AVD. + +

      Give it a name, a platform target, an SD card size, and a skin (HVGA is default). You can + also add specific hardware features of the emulated device by clicking the + New... button and selecting the feature. For a list of hardware features, + see Hardware options.

      + +

      Note: Be sure to define a target for your AVD that satisfies + your application's Build Target (the AVD platform target must have an API Level equal to or + greater than the API Level that your application compiles against).

      +
    6. + +
    7. Click Create AVD.
    8. +
    + +

    Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or + launch an emulator with the AVD by selecting a device and clicking Start.

    + +

    Hardware options

    +

    If you are creating a new AVD, you can specify the following hardware options for the AVD +to emulate:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CharacteristicDescriptionProperty
    Device ram sizeThe amount of physical RAM on the device, in megabytes. Default value is "96".hw.ramSize
    Touch-screen supportWhether there is a touch screen or not on the device. Default value is "yes".hw.touchScreen
    Trackball supportWhether there is a trackball on the device. Default value is "yes".hw.trackBall
    Keyboard supportWhether the device has a QWERTY keyboard. Default value is "yes".hw.keyboard
    DPad supportWhether the device has DPad keys. Default value is "yes".hw.dPad
    GSM modem supportWhether there is a GSM modem in the device. Default value is "yes".hw.gsmModem
    Camera supportWhether the device has a camera. Default value is "no".hw.camera
    Maximum horizontal camera pixelsDefault value is "640".hw.camera.maxHorizontalPixels
    Maximum vertical camera pixelsDefault value is "480".hw.camera.maxVerticalPixels
    GPS supportWhether there is a GPS in the device. Default value is "yes".hw.gps
    Battery supportWhether the device can run on a battery. Default value is "yes".hw.battery
    AccelerometerWhether there is an accelerometer in the device. Default value is "yes".hw.accelerometer
    Audio recording supportWhether the device can record audio. Default value is "yes".hw.audioInput
    Audio playback supportWhether the device can play audio. Default value is "yes".hw.audioOutput
    SD Card supportWhether the device supports insertion/removal of virtual SD Cards. Default value is + "yes".hw.sdCard
    Cache partition supportWhether we use a /cache partition on the device. Default value is "yes".disk.cachePartition
    Cache partition sizeDefault value is "66MB".disk.cachePartition.size
    Abstracted LCD densitySets the generalized density characteristic used by the AVD's screen. Default value is + "160".hw.lcd.density
    + diff --git a/docs/html/tools/eclipse-adt.html b/docs/html/tools/eclipse-adt.html new file mode 100644 index 000000000000..0d59d4989735 --- /dev/null +++ b/docs/html/tools/eclipse-adt.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/tools/extras/index.jd b/docs/html/tools/extras/index.jd new file mode 100644 index 000000000000..8da26dcdab12 --- /dev/null +++ b/docs/html/tools/extras/index.jd @@ -0,0 +1,5 @@ +page.title=Extras +page.noplus=1 +@jd:body + +

    SDK extras add functionality to your development environment. You can download all of the SDK extras into your development environment using the SDK Manager.

    diff --git a/docs/html/tools/extras/oem-usb.jd b/docs/html/tools/extras/oem-usb.jd new file mode 100644 index 000000000000..f7aa192db548 --- /dev/null +++ b/docs/html/tools/extras/oem-usb.jd @@ -0,0 +1,328 @@ +page.title=OEM USB Drivers +@jd:body + +
    + +
    + +

    If you are developing on Windows and would like to connect an Android-powered device +to test your applications, then you need to install the appropriate USB driver. This document +provides links to the web sites for several original equipment manufacturers (OEMs), +where you can download the appropriate USB driver for your device. However, this list is +not exhaustive for all available Android-powered devices.

    + +

    If you're developing on Mac OS X or Linux, then you probably don't need to install a USB driver. +To start developing with your device, read Using Hardware Devices.

    + +

    Note: If your device is one of the Android Developer Phones +(ADP), a Nexus One, or a Nexus S, then you need +the Google USB Driver, instead of an OEM driver. The Galaxy +Nexus driver, however, is distributed by Samsung +(listed as model SCH-I515).

    + + +

    Installing a USB Driver

    + +

    First, find the appropriate driver for your device from the OEM drivers +table below.

    + +

    Once you've downloaded your USB driver, follow the instructions below to install or upgrade the +driver, based on your version of Windows and whether you're installing for the first time +or upgrading an existing driver.

    + +

    Tip: When you finish the USB driver installation, +see Using Hardware Devices for +other important information about using an Android-powered device for +development.

    + +
      +
    1. Windows 7
    2. +
    3. Windows XP
    4. +
    5. Windows Vista
    6. +
    + + +

    Caution: +You may make changes to android_winusb.inf file found inside +usb_driver\ (for example, to add support for other devices), +however, this will lead to security warnings when you install or upgrade the +driver. Making any other changes to the driver files may break the installation +process.

    + + +

    Windows 7

    + + +

    To install the Android USB driver on Windows 7 for the first time:

    +
      +
    1. Connect your Android-powered device to your computer's USB port.
    2. +
    3. Right-click on Computer from your desktop or Windows Explorer, + and select Manage.
    4. +
    5. Select Devices in the left pane.
    6. +
    7. Locate and expand Other device in the right pane.
    8. +
    9. Right-click the device name (such as Nexus S) and select Update + Driver Software. + This will launch the Hardware Update Wizard.
    10. +
    11. Select Browse my computer for driver software and click + Next.
    12. +
    13. Click Browse and locate the USB driver folder. (The Google USB +Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    14. +
    15. Click Next to install the driver.
    16. +
    + +

    Or, to upgrade an existing Android USB driver on Windows 7 with the new +driver:

    + +
      +
    1. Connect your Android-powered device to your computer's USB port.
    2. +
    3. Right-click on Computer from your desktop or Windows Explorer, + and select Manage.
    4. +
    5. Select Device Manager in the left pane of the Computer Management + window.
    6. +
    7. Locate and expand Android Phone in the right pane.
    8. +
    9. Right-click Android Composite ADB Interface and select Update + Driver. + This will launch the Hardware Update Wizard.
    10. +
    11. Select Install from a list or specific location and click + Next.
    12. +
    13. Select Search for the best driver in these locations; un-check +Search removable media; and check Include this location in the +search.
    14. +
    15. Click Browse and locate the USB driver folder. (The Google USB +Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    16. +
    17. Click Next to upgrade the driver.
    18. +
    + + + + + +

    Windows XP

    + +

    To install the Android USB driver on Windows XP for the first time:

    + +
      +
    1. Connect your Android-powered device to your computer's USB port. Windows + will detect the device and launch the Hardware Update Wizard.
    2. +
    3. Select Install from a list or specific location and click + Next.
    4. +
    5. Select Search for the best driver in these locations; un-check +Search + removable media; and check Include +this location in the search.
    6. +
    7. Click Browse and locate the USB driver folder. (The Google USB +Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    8. +
    9. Click Next to install the driver.
    10. +
    + +

    Or, to upgrade an existing Android USB driver on Windows XP with the new +driver:

    + +
      +
    1. Connect your Android-powered device to your computer's USB port.
    2. +
    3. Right-click on My Computer from your desktop or Windows Explorer, + and select Manage.
    4. +
    5. Select Device Manager in the left pane.
    6. +
    7. Locate and expand Android Phone in the right pane.
    8. +
    9. Right-click Android Composite ADB Interface and select Update + Driver. + This will launch the Hardware Update Wizard.
    10. +
    11. Select Install from a list or specific location and click + Next.
    12. +
    13. Select Search for the best driver in these locations; un-check Search + removable media; and check Include +this location in the search.
    14. +
    15. Click Browse and locate the USB driver folder. (The Google USB +Driver is located in {@code <sdk>\extras\google\usb_driver\}.)
    16. +
    17. Click Next to upgrade the driver.
    18. +
    + + + +

    Windows Vista

    + +

    To install the Android USB driver on Windows Vista for the first time:

    + +
      +
    1. Connect your Android-powered device to your computer's USB port. Windows + will detect the device and launch the Found New Hardware wizard.
    2. +
    3. Select Locate and install driver software.
    4. +
    5. Select Don't search online.
    6. +
    7. Select I don't have the disk. Show me other options.
    8. +
    9. Select Browse my computer for driver software.
    10. +
    11. Click Browse and locate the USB driver folder. (The Google USB +Driver is located in {@code <sdk>\extras\google\usb_driver\}.) As long as you specified the +exact location of the + installation package, you may leave Include subfolders checked or + unchecked—it doesn't matter.
    12. +
    13. Click Next. Vista may prompt you to confirm the privilege elevation + required for driver installation. Confirm it.
    14. +
    15. When Vista asks if you'd like to install the Google ADB Interface device, + click Install to install the driver.
    16. +
    + +

    Or, to upgrade an existing Android USB driver on Windows Vista with the new +driver:

    + +
      +
    1. Connect your Android-powered device to your computer's USB port.
    2. +
    3. Right-click on Computer from your desktop or Windows Explorer, + and select Manage.
    4. +
    5. Select Device Manager in the left pane.
    6. +
    7. Locate and expand ADB Interface in the right pane.
    8. +
    9. Right-click on HTC Dream Composite ADB Interface, and select Update + Driver Software.
    10. +
    11. When Vista starts updating the driver, a prompt will ask how you want to + search for the driver + software. Select Browse my computer for driver software.
    12. +
    13. Click Browse and locate the USB driver folder. (The Google USB +Driver is located in {@code <sdk>\extras\google\usb_driver\}.) As long as you specified the +exact location of the + installation package, you may leave Include subfolders checked or + unchecked—it doesn't matter.
    14. +
    15. Click Next. Vista might prompt you to confirm the privilege elevation + required for driver installation. Confirm it.
    16. +
    17. When Vista asks if you'd like to install the Google ADB Interface device, + click Install to upgrade the driver.
    18. +
    + + +

    OEM Drivers

    + +

    Note: If your device is one of the Android Developer Phones +(purchased from the Google Play publisher site), a Nexus One, or a Nexus S, then you need +the Google USB Driver, instead of an OEM driver. The Galaxy +Nexus driver, however, is distributed by Samsung +(listed as model SCH-I515).

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OEMDriver URL
    Acer http://www.acer.com/worldwide/support/mobile.html +
    alcatel one touchhttp://www.alcatel-mobilephones.com/global/Android-Downloads
    Asushttp://support.asus.com/download/
    + Dell + + http://support.dell.com/support/downloads/index.aspx?c=us&cs=19&l=en&s=dhs&~ck=anavml
    Foxconn http://drivers.cmcs.com.tw/
    + Fujitsu + http://www.fmworld.net/product/phone/sp/android/develop/ +
    + Fujitsu Toshiba + http://www.fmworld.net/product/phone/sp/android/develop/ +
    + Garmin-Asus + https://www.garminasus.com/en_US/support/pcsync/
    Hisensehttp://app.hismarttv.com/dss/resourcecontent.do?method=viewResourceDetail&resourceId=16&type=5
    HTC http://www.htc.com
    Click on the +support tab to select your products/device. Different regions will have different links.
    Huawei http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index
    Intel http://www.intel.com/software/android
    KT Tech http://www.kttech.co.kr/cscenter/download05.asp for EV-S100 (Take)
    + Kyocera + http://www.kyocera-wireless.com/support/phone_drivers.htm +
    Lenevohttp://developer.lenovomm.com/developer/download.jsp +
    LGE http://www.lg.com/us/mobile-phones/mobile-support/mobile-lg-mobile-phone-support.jsp
    Motorola http://developer.motorola.com/docstools/USB_Drivers/
    Pantech http://www.isky.co.kr/cs/software/software.sky?fromUrl=index
    Pegatron http://www.pegatroncorp.com/download/New_Duke_PC_Driver_0705.zip (ZIP download)
    Samsung http://www.samsung.com/us/support/downloads
    Sharp http://k-tai.sharp.co.jp/support/
    SK Telesys http://www.sk-w.com/service/wDownload/wDownload.jsp
    Sony Ericsson http://developer.sonyericsson.com/wportal/devworld/search-downloads/driver?cc=gb&lc=en
    Teleepoch http://www.teleepoch.com/android.html
    Yulong Coolpad http://www.yulong.com/product/product/product/downloadList.html#downListUL
    ZTE http://support.zte.com.cn/support/news/NewsDetail.aspx?newsId=1000442
    diff --git a/docs/html/tools/extras/support-library.jd b/docs/html/tools/extras/support-library.jd new file mode 100644 index 000000000000..7258c773cfe9 --- /dev/null +++ b/docs/html/tools/extras/support-library.jd @@ -0,0 +1,507 @@ +page.title=Support Library + +@jd:body + + + +

    Minimum API level supported: 4

    + +

    The Support Package includes static "support libraries" that you can add to your Android +application in order to use APIs that are either not available for older platform versions or that +offer "utility" APIs that aren't a part of the framework APIs. The goal is to simplify your +development by offering more APIs that you can bundle with your application so you can +worry less about platform versions.

    + +

    Note: The Support Package includes more than one support +library. Each one has a different minimum API level. For example, one library requires API +level 4 or higher, while another requires API level 13 or higher (v13 is a superset of v4 and +includes additional +support classes to work with v13 APIs). The minimum version is indicated +by the directory name, such as {@code v4/} and {@code v13/}.

    + + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the Support Package, as denoted by revision number.

    + +
    + +

    + + Support Package, revision 8 (April 2012) +

    + +
    +
    +
    Changes for v4 support library:
    +
    +
      +
    • Fixed intent flags for {@link android.app.PendingIntent} objects generated + by {@link android.support.v4.app.TaskStackBuilder}.
    • +
    • Removed unused attributes from the gridlayout library projects to make sure + the library can be built with API Level 7 and higher.
    • +
    • Added {@code .classpath} and {@code .project} files for the gridlayout + library project.
    • +
    +
    +
    +
    + +
    + +

    + + Support Package, revision 7 (March 2012) +

    + +
    +
    +
    Changes for v4 support library:
    +
    +
      +
    • Added {@link android.support.v4.app.ShareCompat}, which provides helper classes +for sending and receiving content for social sharing applications, including new metadata for +attributing shared data to the source app. This class also provides compatible integration with the +new {@link android.widget.ShareActionProvider} in Android 4.0.
    • +
    • Added {@link android.support.v4.app.NavUtils} and {@link +android.support.v4.app.TaskStackBuilder} to provide support for implementing the +Android Design guidelines for navigation. These +additions include a way to implement the action bar's Up button across versions. +For an example implementation of this pattern, see the AppNavigation sample in +({@code <sdk>/samples/<platform>/AppNavigation}).
    • +
    • Added {@link android.support.v4.app.NotificationCompat.Builder} to provide a +compatibility implementation of Android 3.0's {@link android.app.Notification.Builder} helper class +for creating standardized system notifications.
    • +
    +
    +
    +
    + +
    + +

    + + Support Package, revision 6 (December 2011) +

    + +
    +

    Note: Reference for support library APIs are now available with + the framework references, for example: {@link android.support.v4.app}.

    +
    +
    Changes for v4 support library:
    +
    +
      +
    • Changes to ViewPager: +
        +
      • Added extra decorative view support for {@link android.support.v4.view.ViewPager}. + Decorative views may be supplied as child views of a pager in XML layout.
      • +
      • Added {@link android.support.v4.view.PagerAdapter#getPageTitle + PagerAdapter.getPageTitle()} to supply title strings for pages, which defaults to no + title for each page.
      • +
      • Added {@link android.support.v4.view.PagerTitleStrip}, a non-interactive title + strip, that can be added as a child of ViewPager. Developers can supply text + appearance and color, as well as layout sizing and gravity information.
      • +
      • Updated {@link android.support.v4.view.PagerAdapter} methods to take ViewGroup + objects, rather than View to avoid class casting in adapter implementations.
      • +
      • Updated {@link android.support.v4.view.ViewPager} to use Launcher-style + fling behavior.
      • +
      • Bug fixes for user interface interaction and test automation.
      • +
      +
    • + +
    • Support for Fragments: +
        +
      • Changed {@code setStartDeferred()} method to {@link + android.support.v4.app.Fragment#setUserVisibleHint}.
      • +
      • Added deferred start for off-screen pages to improve performance.
      • +
      +
    • + +
    • Support for Accessiblity APIs: +
        +
      • Updated {@link android.support.v4.view.AccessibilityDelegateCompat} methods + to return empty lists instead of null.
      • +
      • Added new APIs needed by the v4 samples.
      • +
      +
    • + +
    +
    +
    +
    + +
    + +

    + + Support Package, revision 5 (December 2011) +

    + +
    +
    +
    Changes for v4 support library:
    +
    +
      +
    • Support for Accessiblity APIs: +
        +
      • Added {@link android.support.v4.view.AccessibilityDelegateCompat} + to support {@link android.view.View.AccessibilityDelegate}.
      • + +
      • Added {@link android.support.v4.view.accessibility.AccessibilityEventCompat} + to support {@link android.view.accessibility.AccessibilityEvent}.
      • + +
      • Added {@link android.support.v4.view.accessibility.AccessibilityManagerCompat} + to support {@link android.view.accessibility.AccessibilityManager}.
      • + +
      • Added {@link android.support.v4.view.accessibility.AccessibilityNodeInfoCompat} + to support {@link android.view.accessibility.AccessibilityNodeInfo}.
      • + +
      • Added {@link android.support.v4.view.accessibility.AccessibilityRecordCompat} + to support {@link android.view.accessibility.AccessibilityRecord}.
      • + +
      • Added {@link + android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat} + to support {@link android.accessibilityservice.AccessibilityServiceInfo}.
      • + +
      • Added {@link android.support.v4.view.ViewGroupCompat} + to support accessibility features in {@link android.view.ViewGroup}. +
      • + +
      • Modified {@link android.support.v4.view.ViewCompat} + to support accessibility features in {@link android.view.View}.
      • +
      +
    • + +
    • Changes to ViewPager: +
        +
      • Added support for margins between pages. + An optional {@link android.graphics.drawable.Drawable} can be provided + to fill the margins.
      • +
      • Added support for {@link android.widget.EdgeEffect}.
      • +
      • Added support for keyboard navigation
      • +
      • Added support to control how many pages are kept to either side + of the current page.
      • +
      • Improved touch physics.
      • +
      • Bug fixes for user interface behavior.
      • +
      +
    • +
    +
    +
    +
    + +
    + +

    + + Support Package, revision 4 (October 2011) +

    + +
    +
    +
    Changes for v4 support library:
    +
    +
      +
    • Added EdgeEffectCompat to + support {@link android.widget.EdgeEffect}.
    • + +
    • Added LocalBroadcastManager to allow applications to easily + register for and receive intents within a single application without + broadcasting them globally.
    • + +
    • Added support in ViewCompat to check for and set overscroll + modes for {@link android.view.View}s on Android 2.3 and later.
    • +
    • Changes to Fragment APIs: +
        +
      • Added new APIs to control the visibility of new menus.
      • +
      • Added custom animation APIs.
      • +
      • Added APIs in FragmentActivity to retain custom, + non-configuration instance data.
      • +
      • Various bug fixes.
      • +
      +
    • + +
    • Fixed a {@link android.content.Loader} bug that caused issues in + canceling {@link android.os.AsyncTask}s when running on Froyo and older + versions of the platform. The support + code now uses its own version of {@link android.os.AsyncTask} to keep the same + behavior on all platform versions.
    • + +
    +
    +
    +
    + + + +
    + + +
    + +

    + + Compatibility Package, revision 3 (July 2011) +

    + +
    +
    +
    Changes for v4 support library:
    +
    +
      +
    • Adds support for {@link android.app.Fragment.SavedState}
    • +
    • Adds {@code MotionEventCompat} to support newer {@link +android.view.MotionEvent} APIs
    • +
    • Adds {@code VelocityTrackerCompat} to support a newer {@link +android.view.VelocityTracker} APIs
    • +
    • Adds {@code ViewConfigurationCompat} to support a newer {@link +android.view.ViewConfiguration} APIs
    • +
    • All new APIs (available only in the support library) that allow you to create UIs +with horizontal paging, allowing users to swipe left and right between content views. Classes to +support this include: +
        +
      • {@code ViewPager}: A {@link android.view.ViewGroup} that manages the +layout for the child views, which the user can swipe between.
      • +
      • {@code PagerAdapter}: An adapter that populates the {@code ViewPager} with the +views that represent each page.
      • +
      • {@code FragmentPagerAdapter}: An extension of {@code PagerAdapter} for flipping +between fragments.
      • +
      • {@code FragmentStatePagerAdapter}: An extension of {@code PagerAdapter} for +flipping between fragments that uses the library's support for {@link +android.app.Fragment.SavedState}.
      • +
      +
    • +
    +
    +
    New v13 support library:
    +
    +
      +
    • Includes the {@code FragmentPagerAdapter} and {@code FragmentStatePagerAdapter} +to support the horizontal paging. +

      These are exactly the same as the APIs added to the v4 support library, but rely on +other platform components in Android 3.2. Use this library instead of v4 if you're developing for +Android 3.2 and higher (all other APIs in the v4 library are already available with API level +13).

      +
    • +
    +
    +
    +
    + +
    + + +
    + +

    + + Compatibility Package, revision 2 (May 2011) +

    + +
    +
    +
    Changes for v4 library:
    +
    +
      +
    • Support for fragment animations
    • +
    • Fix {@code android.support.v4.app.Fragment#onActivityResult Fragment.onActivityResult()} + bug
    • +
    +
    +
    +
    + +
    + + +
    + +

    + + Compatibility Package, revision 1 (March 2011) +

    + +
    +

    Initial release with the v4 library.

    +
    + +
    + + + +

    Downloading the Support Package

    + +

    The Support Package is provided as a downloadable package from the Android SDK +Manager. To install:

    + +
      +
    1. Launch the Android SDK Manager. +

      From Eclipse, you can select Window +> Android SDK Manager. Or, launch {@code SDK Manager.exe} from +the {@code <sdk>/} directory (on Windows only) or {@code android} from the {@code +<sdk>/tools/} directory.

    2. +
    3. Expand the Android Repository, check Android Support package +and click Install selected.
    4. +
    5. Proceed to install the package.
    6. +
    + +

    When done, all files (including source code, samples, and the {@code .jar} files) are saved +into the <sdk>/extras/android/support/ directory. This directory contains +each of the different support libraries, such as the library for API level 4 and up and the library +for API level 13 and up, each named with the respective version (such as {@code v4/}).

    + + +

    Setting Up a Project to Use a Library

    + +

    To add one of the libraries to your Android project:

    +
      +
    1. In your Android project, create a directory named {@code libs} at the root of your +project (next to {@code src/}, {@code res/}, etc.)
    2. +
    3. Locate the JAR file for the library you want to use and copy it into the {@code +libs/} directory. +

      For example, the library that supports API level 4 and up is located at {@code +<sdk>/extras/android/support/v4/android-support-v4.jar}.

      +
    4. +
    5. Add the JAR to your project build path. +

      In Eclipse, right-click the JAR file in the Package Explorer, select Build +Path > Add to Build Path.

      +
    6. +
    + +

    Your application is now ready to use the library APIs. All the +provided APIs are available in the {@code android.support} package (for +example, {@code android.support.v4}).

    + +

    Tip: To see the library APIs in action, take a look at the sample +apps in {@code <sdk>/extras/android/support/<version>/samples/}.

    + +

    Warning: Be certain that you not confuse the standard +{@code android} packages with those in {@code android.support} library. Some code completion tools +might +get this wrong, especially if you're building against recent versions of the platform. To be safe, +keep your build target set to the same version as you have defined for your {@code android:minSdkVersion} +and double check the import statements for classes that also exist in the support library, such as +{@code SimpleCursorAdapter}.

    + + +

    Using the v4 Library APIs

    + +

    The support library for v4 provides access to several classes introduced with Android 3.0 and +beyond, plus some updated version of existing classes, and even some APIs that currently don't +exist in the Android platform. Some of the most useful and notable classes that have +counterparts in the v4 support library are:

    + +
      +
    • {@link android.app.Fragment}
    • +
    • {@link android.app.FragmentManager}
    • +
    • {@link android.app.FragmentTransaction}
    • +
    • {@link android.app.ListFragment}
    • +
    • {@link android.app.DialogFragment}
    • +
    • {@link android.app.LoaderManager}
    • +
    • {@link android.content.Loader}
    • +
    • {@link android.content.AsyncTaskLoader}
    • +
    • {@link android.content.CursorLoader}
    • +
    + +

    For each of the classes above (and others not listed), the APIs work almost exactly the same +as the counterparts in the latest Android platform. Thus, you can usually refer to +the online documentation for information about the supported APIs. There are some +differences, however. Most notably:

    + +
      +
    • When creating an activity to use fragments, you must declare your activity to extend the +{@link android.support.v4.app.FragmentActivity} class (instead of the traditional +{@link android.app.Activity} class).
    • +
    • To manage your fragments and loaders, you must use the methods + {@link android.support.v4.app.FragmentActivity#getSupportFragmentManager + FragmentActivity.getSupportFragmentManager()} and + {@link android.support.v4.app.FragmentActivity#getSupportLoaderManager + FragmentActivity.getSupportLoaderManager()} (instead of the + {@link android.app.Activity#getFragmentManager()} and + {@link android.app.Activity#getLoaderManager()} methods).
    • +
    • The {@link android.app.ActionBar} is not supported by the library. +However, when creating your Options +Menu, you can declare which items should be added to the Action Bar when it's available (on +Android 3.0 or later). You can do so with the +{@link android.support.v4.view.MenuCompat#setShowAsAction MenuCompat.setShowAsAction()} method, for +example: +
      +public boolean onCreateOptionsMenu(Menu menu) {
      +    MenuInflater inflater = getMenuInflater();
      +    inflater.inflate(R.menu.options, menu);
      +    MenuCompat.setShowAsAction(menu.findItem(R.id.action_search), 1);
      +    return true;
      +}
      +
      +

      Also see the Action Bar +Compatibility sample for a demonstration of how to use {@link android.app.ActionBar} on Android +3.0+ and also support action bar functionality on older versions.

      +
    • +
    + +

    Tip: To enable the Holographic theme on devices +running Android 3.0 or higher, declare in your manifest file that your application targets +API level 11, for example:

    +
    +<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="11" />
    +
    +

    This way, your application automatically receives the Holographic theme and the Action Bar for +each activity when running on Android 3.0 and higher.

    +
    + +

    For more information about how you can optimize your application for the latest +Android-powered devices, read Optimizing +Apps for Android 3.0.

    + + +

    Reference Docs

    + +

    The reference documentation for the Support Packages is included as part of the Android +online developer documentation:

    + + + + +

    Samples

    + +

    If you want to see some code that uses the support libraries, samples are included with the +Support Package, inside each support library directory, for example; {@code +<sdk>/extras/android/support/v4/samples/}. You can also view these samples as part of the +Android online developer documentation:

    + + + +

    Additionally, the Google I/O App is a complete +application that uses the v4 support library to provide a single APK for both handsets and tablets +and also demonstrates some of Android's best practices in Android UI design.

    diff --git a/docs/html/tools/help/MonkeyDevice.jd b/docs/html/tools/help/MonkeyDevice.jd new file mode 100644 index 000000000000..e7612e664093 --- /dev/null +++ b/docs/html/tools/help/MonkeyDevice.jd @@ -0,0 +1,1355 @@ +page.title=MonkeyDevice +parent.title=monkeyrunner +parent.link=index.html +@jd:body + +

    + A monkeyrunner class that represents a device or emulator accessible by the workstation running +monkeyrunner. +

    +

    + This class is used to control an Android device or emulator. The methods send UI events, + retrieve information, install and remove applications, and run applications. +

    +

    + You normally do not have to create an instance of MonkeyDevice. Instead, you + use + +MonkeyRunner.waitForConnection() to create a new object from a connection to a device or +emulator. For example, instead of +using:

    +
    +newdevice = MonkeyDevice()
    +
    +

    + you would use: +

    +
    +newdevice = MonkeyRunner.waitForConnection()
    +
    +

    Summary

    + + + + + + + + + + + + + + + + + + + +
    Constants
    stringDOWN + Use this with the type argument of + press() or touch() + + to send a DOWN event. +
    stringUP + Use this with the type argument of + press() or touch() + + to send an UP event. +
    stringDOWN_AND_UP + Use this with the type argument of + press() or touch() + + to send a DOWN event immediately followed by an UP event. +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Methods
    + + void + + + + + broadcastIntent + + (string uri, + string action, + string data, + string mimetype, + iterable categories + dictionary extras, + component component, + iterable flags) + +
    + Broadcasts an Intent to this device, as if the Intent were coming from an + application. +
    +
    + + void + + + + + drag + + (tuple start, + tuple end, + float duration, + integer steps) + +
    + Simulates a drag gesture (touch, hold, and move) on this device's screen. +
    +
    + + object + + + + + getProperty + + (string key) + +
    + Given the name of a system environment variable, returns its value for this device. + The available variable names are listed in the + detailed description of this method. +
    +
    + + object + + + + + getSystemProperty + + (string key) + +
    +. The API equivalent of adb shell getprop <key>. This is provided for use + by platform developers. +
    +
    + + void + + + + + installPackage + + (string path) + +
    + Installs the Android application or test package contained in packageFile onto this + device. If the application or test package is already installed, it is replaced. +
    +
    + + dictionary + + + + + instrument + + (string className, + dictionary args) + +
    + Runs the specified component under Android instrumentation, and returns the results + in a dictionary whose exact format is dictated by the component being run. The + component must already be present on this device. +
    +
    + + void + + + + + press + + (string name, + dictionary type) + +
    + Sends the key event specified by type to the key specified by + keycode. +
    +
    + + void + + + + + reboot + + (string into) + +
    + Reboots this device into the bootloader specified by bootloadType. +
    +
    + + void + + + + + removePackage + + (string package) + +
    + Deletes the specified package from this device, including its data and cache. +
    +
    + + object + + + + + shell + + (string cmd) + +
    + Executes an adb shell command and returns the result, if any. +
    +
    + + void + + + + + startActivity + + (string uri, + string action, + string data, + string mimetype, + iterable categories + dictionary extras, + component component, + flags) + +
    + Starts an Activity on this device by sending an Intent constructed from the + supplied arguments. +
    +
    + + + + MonkeyImage + + + + + + + takeSnapshot() + + +
    + Captures the entire screen buffer of this device, yielding a + + + MonkeyImage + + object containing a screen capture of the current display. +
    +
    + + void + + + + + touch + + (integer x, + integer y, + integer type) + +
    + Sends a touch event specified by type to the screen location specified + by x and y. +
    +
    + + void + + + + + type + + (string message) + +
    + Sends the characters contained in message to this device, as if they + had been typed on the device's keyboard. This is equivalent to calling + press() for each keycode in message + using the key event type DOWN_AND_UP. +
    +
    + + void + + + + + wake + + () + +
    + Wakes the screen of this device. +
    +
    + +

    Constants

    + +
    +

    + + string + + DOWN +

    +
    +
    +

    + press() or + touch() value. + Specifies that a DOWN event type should be sent to the device, corresponding to + pressing down on a key or touching the screen. +

    +
    +
    +
    + +
    +

    + + string + + UP +

    +
    +
    +

    + press() or + touch() value. + Specifies that an UP event type should be sent to the device, corresponding to + releasing a key or lifting up from the screen. +

    +
    +
    +
    + + +
    +

    + + string + + DOWN_AND_UP +

    +
    +
    +

    + press(), + touch() or + type() value. + Specifies that a DOWN event type followed by an UP event type should be sent to the + device, corresponding to typing a key or clicking the screen. +

    +
    +
    +
    + + +

    Public Methods

    + +
    +

    + + void + + broadcastIntent + + ( + string uri, + string action, + string data, + string mimetype, + iterable categories + dictionary extras, + component component, + iterable flags) + +

    +
    + +
    +

    + Broadcasts an Intent to this device, as if the Intent were coming from an + application. See {@link android.content.Intent Intent} for more information about the + arguments. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    uri + The URI for the Intent. + (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). +
    action + The action for this Intent + (see {@link android.content.Intent#setAction(java.lang.String) Intent.setAction()}). +
    data + The data URI for this Intent + (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). +
    mimetype + The MIME type for the Intent + (see {@link android.content.Intent#setType(java.lang.String) Intent.setType()}). +
    categories + An iterable data structure containing strings that define categories for this + Intent + (see + {@link android.content.Intent#addCategory(java.lang.String) Intent.addCategory()}). +
    extras + A dictionary of extra data for this Intent + (see {@link android.content.Intent#putExtra(java.lang.String,java.lang.String) + Intent.putExtra()} + for an example). +

    + The key for each dictionary item should be a string. The item's value + can be any simple or structured data type. +

    +
    component + The component for this Intent (see {@link android.content.ComponentName}). + Using this argument will direct the Intent to a specific class within a specific + Android package. +
    flags + An iterable data structure containing flags that control how the Intent is handled + (see {@link android.content.Intent#setFlags(int) Intent.setFlags()}). +
    +
    +
    +
    + +
    +

    + + void + + drag + + ( + tuple start, + tuple end, + float duration, + integer steps) + +

    +
    + +
    +

    + Simulates a drag gesture (touch, hold, and move) on this device's screen. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + + + + + +
    start + The starting point of the drag gesture, in the form of a tuple + (x,y) where x and y are integers. +
    end + The end point of the drag gesture, in the form of a tuple (x,y) + where x and y are integers. +
    durationThe duration of the drag gesture in seconds. The default is 1.0 seconds.
    stepsThe number of steps to take when interpolating points. The default is 10.
    +
    +
    +
    + +
    +

    + + object + + getProperty + + (string key) + +

    +
    + +
    +

    + Given the name of a system environment variable, returns its value for this device. +

    +
    +
    +
    Arguments
    + + + + + +
    key + The name of the system environment variable. The available variable names are listed in + Table 1. Property variable names at the end of this topic. +
    +
    +
    +
    Returns
    +
      +
    • + The value of the variable. The data format varies according to the variable requested. +
    • +
    +
    +
    +
    + +
    +

    + + object + + getSystemProperty + + (string key) + +

    +
    + +
    +

    + Synonym for getProperty(). +

    +
    +
    +
    Arguments
    + + + + + +
    key + The name of the system environment variable. The available variable names are listed in + Table 1. Property Variable Names. +
    +
    +
    +
    Returns
    +
      +
    • + The value of the variable. The data format varies according to the variable requested. +
    • +
    +
    +
    +
    + +
    +

    + + void + + installPackage + + (string path) + +

    +
    + +
    +

    + Installs the Android application or test package contained in packageFile + onto this device. If the application or test package is already installed, it is + replaced. +

    +
    +
    +
    Arguments
    + + + + + +
    path + The fully-qualified path and filename of the .apk file to install. +
    +
    +
    +
    + +
    +

    + + dictionary + + instrument + + ( + string className, + dictionary args) + +

    +
    + +
    +

    + Runs the specified component with Android instrumentation, and returns the results + in a dictionary whose exact format is dictated by the component being run. The + component must already be present on this device. +

    +

    + Use this method to start a test case that uses one of Android's test case classes. + See Testing + Fundamentals to learn more about unit testing with the Android testing + framework. +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    className + The name of an Android component that is already installed on this device, in the + standard form packagename/classname, where packagename is the + Android package name of a .apk file on this device, and + classname is the class name of an Android component (Activity, + ContentProvider, Service, or BroadcastReceiver) in that file. Both + packagename and classname must be fully qualified. See + {@link android.content.ComponentName} for more details. +
    args + A dictionary containing flags and their values. These are passed to the component as it + is started. If the flag does not take a value, set its dictionary value to an empty + string. +
    +
    +
    Returns
    +
      +
    • +

      + A dictionary containing the component's output. The contents of the dictionary + are defined by the component itself. +

      +

      + If you use {@link android.test.InstrumentationTestRunner} as the class name in + the componentName argument, then the result dictionary contains + the single key "stream". The value of "stream" is a string containing + the test output, as if InstrumentationTestRunner was run from the + command line. The format of this output is described in + + Testing in Other IDEs. +

      +
    • +
    +
    +
    +
    +
    + +
    +

    + + void + + press + + (string name, + integer type) + +

    +
    +
    +

    + Sends the key event specified by type to the key specified by + keycode. +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    name + The name of the keycode to send. See {@link android.view.KeyEvent} for a list of + keycode names. Use the keycode name, not its integer value. +
    type + The type of key event to send. The allowed values are + DOWN, UP, and + DOWN_AND_UP. +
    +
    +
    +
    + +
    +

    + + void + + reboot + + (string bootloadType) + +

    +
    + +
    +

    + Reboots this device into the bootloader specified by bootloadType. +

    +
    +
    +
    Arguments
    + + + + + +
    into + The type of bootloader to reboot into. The allowed values are + "bootloader", "recovery", or "None". +
    +
    +
    +
    + +
    +

    + + void + + removePackage + + (string package) + +

    +
    + +
    +

    + Deletes the specified package from this device, including its data and cache. +

    +
    +
    +
    Arguments
    + + + + +
    package + The Android package name of an .apk file on this device. +
    +
    +
    +
    + +
    +

    + + object + + shell + + (string cmd) + +

    +
    +
    +

    + Executes an adb shell command and returns the result, if any. +

    +
    +
    +
    Arguments
    + + + + + +
    cmd + The command to execute in the adb shell. The form of these commands is + described in the topic Android + Debug Bridge. +
    +
    +
    +
    Returns
    +
      +
    • + The results of the command, if any. The format of the results is determined by the + command. +
    • +
    +
    +
    +
    + +
    +

    + + void + + startActivity + + ( + string uri, + string action, + string data, + string mimetype, + iterable categories + dictionary extras, + component component, + iterable flags) + +

    +
    +
    +

    + Starts an Activity on this device by sending an Intent constructed from the + supplied arguments. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    uri + The URI for the Intent. + (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). +
    action + The action for the Intent + (see {@link android.content.Intent#setAction(java.lang.String) Intent.setAction()}). +
    data + The data URI for the Intent + (see {@link android.content.Intent#setData(android.net.Uri) Intent.setData()}). +
    mimetype + The MIME type for the Intent + (see {@link android.content.Intent#setType(java.lang.String) Intent.setType()}). +
    categories + An iterable data structure containing strings that define categories for the + Intent + (see + {@link android.content.Intent#addCategory(java.lang.String) Intent.addCategory()}). +
    extras + A dictionary of extra data for the Intent + (see + {@link android.content.Intent#putExtra(java.lang.String,java.lang.String) + Intent.putExtra()} + for an example). +

    + The key for each dictionary item should be a string. The item's value + can be any simple or structured data type. +

    +
    component + The component for the Intent + (see {@link android.content.ComponentName}). Using this argument will direct the + Intent to a specific class within a specific Android package. +
    flags + An iterable data structure containing flags that control how the Intent is handled + (see {@link android.content.Intent#setFlags(int) Intent.setFlags()}). +
    +
    +
    +
    + +
    +

    + + + + MonkeyImage + + + + takeSnapshot + + () + +

    +
    +
    +

    + Captures the entire screen buffer of this device, yielding a + screen capture of the current display. +

    +
    +
    +
    Returns
    +
      +
    • + A + MonkeyImage object containing the image of the current display. +
    • +
    +
    +
    +
    + +
    +

    + + void + + touch + + ( + integer x, + integer y, + string type) + +

    +
    +
    +

    + Sends a touch event specified by type to the screen location specified + by x and y. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + +
    x + The horizontal position of the touch in actual device pixels, starting from the left of + the screen in its current orientation. +
    y + The vertical position of the touch in actual device pixels, starting from the top of + the screen in its current orientation. +
    type + The type of key event to send. The allowed values are + DOWN, UP, and + DOWN_AND_UP. +
    +
    +
    +
    + +
    +

    + + void + + type + + (string message) + +

    +
    +
    +

    + Sends the characters contained in message to this device, as if they + had been typed on the device's keyboard. This is equivalent to calling + press() for each keycode in message + using the key event type DOWN_AND_UP. +

    +
    +
    +
    Arguments
    + + + + + +
    message + A string containing the characters to send. +
    +
    +
    +
    + +
    +

    + + void + + wake + + () + +

    +
    +
    +

    + Wakes the screen of this device. +

    +
    +
    +
    +
    +

    Appendix

    +

    + Table 1.Property variable names used with + getProperty() and + getSystemProperty(). +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Property Group + + Property + + Description + + Notes +
    buildboardCode name for the device's system board + See {@link android.os.Build} +
    brandThe carrier or provider for which the OS is customized.
    deviceThe device design name.
    fingerprintA unique identifier for the currently-running build.
    host
    IDA changelist number or label.
    modelThe end-user-visible name for the device.
    productThe overall product name.
    tagsComma-separated tags that describe the build, such as "unsigned" and "debug".
    typeThe build type, such as "user" or "eng".
    user
    CPU_ABI + The name of the native code instruction set, in the form CPU type plus + ABI convention. +
    manufacturerThe product/hardware manufacturer.
    version.incremental + The internal code used by the source control system to represent this version + of the software. +
    version.releaseThe user-visible name of this version of the software.
    version.sdkThe user-visible SDK version associated with this version of the OS.
    version.codename + The current development codename, or "REL" if this version of the software has been + released. +
    displaywidthThe device's display width in pixels. + See + {@link android.util.DisplayMetrics} for details. +
    heightThe device's display height in pixels.
    density + The logical density of the display. This is a factor that scales + DIP (Density-Independent Pixel) units to the device's resolution. DIP is adjusted so + that 1 DIP is equivalent to one pixel on a 160 pixel-per-inch display. For example, + on a 160-dpi screen, density = 1.0, while on a 120-dpi screen, density = .75. +

    + The value does not exactly follow the real screen size, but is adjusted to + conform to large changes in the display DPI. See + {@link android.util.DisplayMetrics#density} for more details. +

    +
    am.currentpackageThe Android package name of the currently running package. + The am.current keys return information about the currently-running + Activity. +
    action + The current activity's action. This has the same format as the name + attribute of the action element in a package manifest. +
    comp.class + The class name of the component that started the current Activity. See + comp.package for more details.
    comp.package + The package name of the component that started the current Activity. A component + is specified by a package name and the name of class that the package contains. +
    dataThe data (if any) contained in the Intent that started the current Activity.
    categoriesThe categories specified by the Intent that started the current Activity.
    clockrealtime + The number of milliseconds since the device rebooted, including deep-sleep + time. + + See {@link android.os.SystemClock} for more information. +
    uptime + The number of milliseconds since the device rebooted, not including + deep-sleep time +
    milliscurrent time since the UNIX epoch, in milliseconds.
    diff --git a/docs/html/tools/help/MonkeyImage.jd b/docs/html/tools/help/MonkeyImage.jd new file mode 100644 index 000000000000..79f49489640e --- /dev/null +++ b/docs/html/tools/help/MonkeyImage.jd @@ -0,0 +1,437 @@ +page.title=MonkeyImage +parent.title=monkeyrunner +parent.link=index.html +@jd:body + + +

    + A monkeyrunner class to hold an image of the device or emulator's screen. The image is + copied from the screen buffer during a screenshot. This object's methods allow you to + convert the image into various storage formats, write the image to a file, copy parts of + the image, and compare this object to other MonkeyImage objects. +

    +

    + You do not need to create new instances of MonkeyImage. Instead, use + +MonkeyDevice.takeSnapshot() to create a new instance from a screenshot. For example, use: +

    +
    +newimage = MonkeyDevice.takeSnapshot()
    +
    +

    Summary

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Methods
    + + string + + + + + convertToBytes + + (string format) + +
    + Converts the current image to a particular format and returns it as a + string that you can then access as an iterable of binary bytes. +
    +
    + + tuple + + + + + getRawPixel + + (integer x, + integer y) + +
    + Returns the single pixel at the image location (x,y), as an + a tuple of integer, in the form (a,r,g,b). +
    +
    + + integer + + + + + getRawPixelInt + + (integer x, + integer y) + +
    + Returns the single pixel at the image location (x,y), as + a 32-bit integer. +
    +
    + + + MonkeyImage + + + + + + getSubImage + + (tuple rect) + +
    + Creates a new MonkeyImage object from a rectangular selection of the + current image. +
    +
    + + boolean + + + + + sameAs + + (MonkeyImage + other, + float percent) + +
    + Compares this MonkeyImage object to another and returns the result of + the comparison. The percent argument specifies the percentage + difference that is allowed for the two images to be "equal". +
    +
    + + void + + + + + writeToFile + + (string path, + string format) + +
    + Writes the current image to the file specified by filename, in the + format specified by format. +
    +
    + + +

    Public Methods

    + +
    +

    + + string + + convertToBytes + + ( + string format) + +

    +
    + +
    +

    + Converts the current image to a particular format and returns it as a string + that you can then access as an iterable of binary bytes. +

    +
    +
    +
    Arguments
    + + + + + +
    format + The desired output format. All of the common raster output formats are supported. + The default value is "png" (Portable Network Graphics). +
    +
    +
    +
    + +
    +

    + + tuple + + getRawPixel + + (integer x, + integer y) + +

    +
    + +
    +

    + Returns the single pixel at the image location (x,y), as an + a tuple of integer, in the form (a,r,g,b). +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    x + The horizontal position of the pixel, starting with 0 at the left of the screen in the + orientation it had when the screenshot was taken. +
    y + The vertical position of the pixel, starting with 0 at the top of the screen in the + orientation it had when the screenshot was taken. +
    +
    +
    +
    Returns
    +
      +
    • + A tuple of integers representing the pixel, in the form (a,r,g,b) where + a is the alpha channel value, and r, g, and b are the red, green, and blue values, + respectively. +
    • +
    +
    +
    +
    + +
    +

    + + tuple + + getRawPixelInt + + (integer x, + integer y) + +

    +
    + +
    +

    + Returns the single pixel at the image location (x,y), as an + an integer. Use this method to economize on memory. +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    x + The horizontal position of the pixel, starting with 0 at the left of the screen in the + orientation it had when the screenshot was taken. +
    y + The vertical position of the pixel, starting with 0 at the top of the screen in the + orientation it had when the screenshot was taken. +
    +
    +
    +
    Returns
    +
      +
    • + The a,r,g, and b values of the pixel as 8-bit values combined into a 32-bit + integer, with a as the leftmost 8 bits, r the next rightmost, and so forth. +
    • +
    +
    +
    +
    + +
    +

    + + + MonkeyImage + + + getSubImage + + (tuple rect) + +

    +
    + +
    +

    + Creates a new MonkeyImage object from a rectangular selection of the + current image. +

    +
    +
    +
    Arguments
    + + + + + +
    rect + A tuple (x, y, w, h) specifying the selection. x and y specify the 0-based pixel + position of the upper left-hand corner of the selection. w specifies the width of the + region, and h specifies its height, both in units of pixels. +

    + The image's orientation is the same as the screen orientation at the time the + screenshot was made. +

    +
    +
    +
    +
    Returns
    +
      +
    • + A new MonkeyImage object containing the selection. +
    • +
    +
    +
    +
    + +
    +

    + + boolean + + sameAs + + ( + + MonkeyImage + otherImage, + float percent + ) + +

    +
    + +
    +

    + Compares this MonkeyImage object to another and returns the result of + the comparison. The percent argument specifies the percentage + difference that is allowed for the two images to be "equal". +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    other + Another MonkeyImage object to compare to this one. +
    + percent + + A float in the range 0.0 to 1.0, inclusive, indicating + the percentage of pixels that need to be the same for the method to return + true. The default is 1.0, indicating that all the pixels + must match. +
    +
    +
    +
    Returns
    +
      +
    • + Boolean true if the images match, or boolean false otherwise. +
    • +
    +
    +
    +
    + +
    +

    + + void + + writeToFile + + (string filename, + string format) + +

    +
    + +
    +

    + Writes the current image to the file specified by filename, in the + format specified by format. +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    path + The fully-qualified filename and extension of the output file. +
    + format + + The output format to use for the file. If no format is provided, then the + method tries to guess the format from the filename's extension. If no + extension is provided and no format is specified, then the default format of + "png" (Portable Network Graphics) is used. +
    +
    +
    +
    diff --git a/docs/html/tools/help/MonkeyRunner.jd b/docs/html/tools/help/MonkeyRunner.jd new file mode 100644 index 000000000000..a924d2dcaf71 --- /dev/null +++ b/docs/html/tools/help/MonkeyRunner.jd @@ -0,0 +1,448 @@ +page.title=MonkeyRunner +parent.title=monkeyrunner +parent.link=index.html +@jd:body + + +

    + A monkeyrunner class that contains static utility methods. +

    +

    Summary

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Methods
    + + void + + + + + alert + + (string message, + string title, + string okTitle) + +
    + Displays an alert dialog to the process running the current + program. +
    +
    + + integer + + + + + choice + + (string message, + iterable choices, + string title) + +
    + Displays a dialog with a list of choices to the process running the current program. +
    +
    + + void + + + + + help + + (string format) + +
    + Displays the monkeyrunner API reference in a style similar to that of Python's + pydoc tool, using the specified format. +
    +
    + + string + + + + + input + + (string message, + string initialValue, + string title, + string okTitle, + string cancelTitle) + +
    + Displays a dialog that accepts input. +
    +
    + + void + + + + + sleep + + (float seconds) + +
    + Pauses the current program for the specified number of seconds. +
    +
    + + + MonkeyDevice + + + + + + waitForConnection + + (float timeout, + string deviceId) + +
    + Tries to make a connection between the monkeyrunner backend and the + specified device or emulator. +
    +
    + + +

    Public Methods

    + +
    +

    + + string + + alert + + ( + string message, + string title, + string okTitle) + +

    +
    + +
    +

    + Displays an alert dialog to the process running the current + program. The dialog is modal, so the program pauses until the user clicks the dialog's + button. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + +
    message + The message to display in the dialog. +
    title + The dialog's title. The default value is "Alert". +
    okTitle + The text displayed in the dialog button. The default value is "OK". +
    +
    +
    +
    + +
    +

    + + integer + + choice + + (string message, + iterable choices, + string title) + +

    +
    + +
    +

    + Displays a dialog with a list of choices to the process running the current program. The + dialog is modal, so the program pauses until the user clicks one of the dialog's + buttons. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + +
    message + The prompt message displayed in the dialog. +
    choices + A Python iterable containing one or more objects that are displayed as strings. The + recommended form is an array of strings. +
    + title + + The dialog's title. The default is "Input". +
    +
    +
    +
    Returns
    +
      +
    • + If the user makes a selection and clicks the "OK" button, the method returns + the 0-based index of the selection within the iterable. + If the user clicks the "Cancel" button, the method returns -1. +
    • +
    +
    +
    +
    + +
    +

    + + void + + help + + (string format) + +

    +
    + +
    +

    + Displays the monkeyrunner API reference in a style similar to that of Python's + pydoc tool, using the specified format. +

    +
    +
    +
    Arguments
    + + + + + +
    format + The markup format to use in the output. The possible values are "text" for plain text + or "html" for HTML. +
    +
    +
    +
    + +
    +

    + + string + + input + + (string message + string initialValue, + string title, + string okTitle, + string cancelTitle) + +

    +
    + +
    +

    + Displays a dialog that accepts input and returns it to the program. The dialog is + modal, so the program pauses until the user clicks one of the dialog's buttons. +

    +

    + The dialog contains two buttons, one of which displays the okTitle value + and the other the cancelTitle value. If the user clicks the okTitle button, + the current value of the input box is returned. If the user clicks the cancelTitle + button, an empty string is returned. +

    +
    +
    +
    Arguments
    + + + + + + + + + + + + + + + + + + + + + +
    message + The prompt message displayed in the dialog. +
    initialValue + The initial value to display in the dialog. The default is an empty string. +
    title + The dialog's title. The default is "Input". +
    okTitle + The text displayed in the okTitle button. The default is "OK". +
    cancelTitle + The text displayed in the cancelTitle button. The default is "Cancel". +
    +
    +
    +
    Returns
    +
      +
    • + If the user clicks the okTitle button, then the method returns the current value of + the dialog's input box. If the user clicks the cancelTitle button, the method returns + an empty string. +
    • +
    +
    +
    +
    + +
    +

    + + void + + sleep + + ( + float seconds + ) + +

    +
    + +
    +

    + Pauses the current program for the specified number of seconds. +

    +
    +
    +
    Arguments
    + + + + + +
    seconds + The number of seconds to pause. +
    +
    +
    +
    + +
    +

    + + + MonkeyDevice + + + waitForConnection + + (float timeout, + string deviceId) + +

    +
    + +
    +

    + Tries to make a connection between the monkeyrunner backend and the + specified device or emulator. +

    +
    +
    +
    Arguments
    + + + + + + + + + +
    timeout + The number of seconds to wait for a connection. The default is to wait forever. +
    + deviceId + + A regular expression that specifies the serial number of the device or emulator. See + the topic + Android Debug Bridge + for a description of device and emulator serial numbers. +
    +
    +
    +
    Returns
    +
      +
    • + A MonkeyDevice + instance for the device or emulator. Use this object to control and communicate with the + device or emulator. +
    • +
    +
    +
    +
    diff --git a/docs/html/tools/help/aapt.html b/docs/html/tools/help/aapt.html new file mode 100644 index 000000000000..ebd375d312f0 --- /dev/null +++ b/docs/html/tools/help/aapt.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/tools/help/adb.jd b/docs/html/tools/help/adb.jd new file mode 100644 index 000000000000..ddebed605b89 --- /dev/null +++ b/docs/html/tools/help/adb.jd @@ -0,0 +1,669 @@ +page.title=Android Debug Bridge +parent.title=Tools +parent.link=index.html +@jd:body + +
    +
    +

    ADB quickview

    +
      +
    • Manage the state of an emulator or device
    • +
    • Run shell commands on a device
    • +
    • Manage port forwarding on an emulator or device
    • +
    • Copy files to/from an emulator or device
    • +
    + +

    In this document

    +
      +
    1. Issuing ADB Commands
    2. +
    3. Querying for Emulator/Device Instances
    4. +
    5. Directing Commands to a Specific Emulator/Device Instance
    6. +
    7. Installing an Application
    8. +
    9. Forwarding Ports
    10. +
    11. Copying Files to or from an Emulator/Device Instance
    12. +
    13. Listing of adb Commands
    14. +
    15. Issuing Shell Commands
    16. +
    17. Enabling logcat Logging
    18. +
    19. Stopping the adb Server
    20. +
    + +

    See also

    +
      +
    1. Emulator
    2. +
    + +
    +
    + +

    Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an +emulator instance or connected Android-powered device. It is a client-server program that includes +three components:

    + +
      +
    • A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.
    • +
    • A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.
    • +
    • A daemon, which runs as a background process on each emulator or device instance.
    • +
    + +

    You can find the {@code adb} tool in {@code <sdk>/platform-tools/}.

    + +

    When you start an adb client, the client first checks whether there is an adb server process already running. If there isn't, it starts the server process. When the server starts, it binds to local TCP port 5037 and listens for commands sent from adb clients—all adb clients use port 5037 to communicate with the adb server.

    + +

    The server then sets up connections to all running emulator/device instances. It locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device instance acquires a pair of sequential ports — an even-numbered port for console connections and an odd-numbered port for adb connections. For example:

    + +

    +Emulator 1, console: 5554
    +Emulator 1, adb: 5555
    +Emulator 2, console: 5556
    +Emulator 2, adb: 5557 ... +

    + +

    As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554.

    + +

    Once the server has set up connections to all emulator instances, you can use adb commands to control and access those instances. Because the server manages connections to emulator/device instances and handles commands from multiple adb clients, you can control any emulator/device instance from any client (or from a script).

    + +

    The sections below describe the commands that you can use to access adb capabilities and manage the state of an emulator/device. Note that if you are developing Android applications in Eclipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a transparent integration of adb into the Eclipse IDE. However, you can still use adb directly as necessary, such as for debugging.

    + + + +

    Issuing adb Commands

    + +

    You can issue adb commands from a command line on your development machine or from a script. The usage is:

    + +
    adb [-d|-e|-s <serialNumber>] <command> 
    + +

    When you issue a command, the program invokes an adb client. The client is not specifically associated with any emulator instance, so if multiple emulators/devices are running, you need to use the -d option to specify the target instance to which the command should be directed. For more information about using this option, see Directing Commands to a Specific Emulator/Device Instance.

    + + + +

    Querying for Emulator/Device Instances

    + +

    Before issuing adb commands, it is helpful to know what emulator/device instances are connected to the adb server. You can generate a list of attached emulators/devices using the devices command:

    + +
    adb devices
    + +

    In response, adb prints this status information for each instance:

    + +
      +
    • Serial number — A string created by adb to uniquely identify an emulator/device instance by its + console port number. The format of the serial number is <type>-<consolePort>. + Here's an example serial number: emulator-5554
    • +
    • State — The connection state of the instance. Three states are supported: +
        +
      • offline — the instance is not connected to adb or is not responding.
      • +
      • device — the instance is now connected to the adb server. Note that this state does not + imply that the Android system is fully booted and operational, since the instance connects to adb + while the system is still booting. However, after boot-up, this is the normal operational state of + an emulator/device instance.
      • +
      +
    • +
    + +

    The output for each instance is formatted like this:

    + +
    [serialNumber] [state]
    + +

    Here's an example showing the devices command and its output:

    + +
    $ adb devices
    +List of devices attached 
    +emulator-5554  device
    +emulator-5556  device
    +emulator-5558  device
    + +

    If there is no emulator/device running, adb returns no device.

    + + + + +

    Directing Commands to a Specific Emulator/Device Instance

    + +

    If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is:

    + +
    adb -s <serialNumber> <command> 
    + +

    As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator/device instances.

    + +

    Here is an example:

    + +
    adb -s emulator-5556 install helloWorld.apk
    + +

    Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error. + + + +

    Installing an Application

    +

    You can use adb to copy an application from your development computer and install it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install:

    + +
    adb install <path_to_apk>
    + +

    For more information about how to create an .apk file that you can install on an emulator/device +instance, see Building and Running

    + +

    Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you.

    + + + + +

    Forwarding Ports

    + +

    You can use the forward command to set up arbitrary port forwarding — forwarding of requests on a specific host port to a different port on an emulator/device instance. Here's how you would set up forwarding of host port 6100 to emulator/device port 7100:

    +
    adb forward tcp:6100 tcp:7100
    +

    You can also use adb to set up forwarding to named abstract UNIX domain sockets, as illustrated here:

    +
    adb forward tcp:6100 local:logd 
    + + + +

    Copying Files to or from an Emulator/Device Instance

    + +

    You can use the adb commands pull and push to copy files to and from an emulator/device instance's data file. Unlike the install command, which only copies an .apk file to a specific location, the pull and push commands let you copy arbitrary directories and files to any location in an emulator/device instance.

    + +

    To copy a file or directory (recursively) from the emulator or device, use

    +
    adb pull <remote> <local>
    + +

    To copy a file or directory (recursively) to the emulator or device, use

    +
    adb push <local> <remote>
    + +

    In the commands, <local> and <remote> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote).

    + +

    Here's an example:

    +
    adb push foo.txt /sdcard/foo.txt
    + + + +

    Listing of adb Commands

    + +

    The table below lists all of the supported adb commands and explains their meaning and usage.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CategoryCommandDescriptionComments
    Options-dDirect an adb command to the only attached USB device.Returns an error if more than one USB device is attached.
    -eDirect an adb command to the only running emulator instance.Returns an error if more than one emulator instance is running.
    -s <serialNumber>Direct an adb command a specific emulator/device instance, referred to by its adb-assigned serial number (such as "emulator-5556").If not specified, adb generates an error.
    GeneraldevicesPrints a list of all attached emulator/device instances.See Querying for Emulator/Device Instances for more information.
    helpPrints a list of supported adb commands. 
    versionPrints the adb version number.  
    Debuglogcat [<option>] [<filter-specs>]Prints log data to the screen.  
    bugreportPrints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting.  
    jdwpPrints a list of available JDWP processes on a given device. You can use the forward jdwp:<pid> port-forwarding specification to connect to a specific JDWP process. For example:
    + adb forward tcp:8000 jdwp:472
    + jdb -attach localhost:8000

    +
    Datainstall <path-to-apk>Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device.  
    pull <remote> <local>Copies a specified file from an emulator/device instance to your development computer.  
    push <local> <remote>Copies a specified file from your development computer to an emulator/device instance.  
    Ports and Networkingforward <local> <remote>Forwards socket connections from a specified local port to a specified remote port on the emulator/device instance. Port specifications can use these schemes: +
    • tcp:<portnum>
    • +
    • local:<UNIX domain socket name>
    • +
    • dev:<character device name>
    • +
    • jdwp:<pid>
    +
    ppp <tty> [parm]...Run PPP over USB. +
      +
    • <tty> — the tty for PPP stream. For example dev:/dev/omap_csmi_ttyl.
    • +
    • [parm]... — zero or more PPP/PPPD options, such as defaultroute, local, notty, etc.
    + +

    Note that you should not automatically start a PPP connection.

    Scriptingget-serialnoPrints the adb instance serial number string.See Querying for Emulator/Device Instances for more information.
    get-statePrints the adb state of an emulator/device instance.
    wait-for-deviceBlocks execution until the device is online — that is, until the instance state is device.You can prepend this command to other adb commands, in which case adb will wait until the emulator/device instance is connected before issuing the other commands. Here's an example: +
    adb wait-for-device shell getprop
    + +Note that this command does not cause adb to wait until the entire system is fully booted. For that reason, you should not prepend it to other commands that require a fully booted system. As an example, the install requires the Android package manager, which is available only after the system is fully booted. A command such as + +
    adb wait-for-device install <app>.apk
    + +would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system was fully booted, so it would result in an error.
    Serverstart-serverChecks whether the adb server process is running and starts it, if not. 
    kill-serverTerminates the adb server process. 
    ShellshellStarts a remote shell in the target emulator/device instance.See Issuing Shell Commands for more information.
    shell [<shellCommand>]Issues a shell command in the target emulator/device instance and then exits the remote shell.
    + + + + +

    Issuing Shell Commands

    + +

    Adb provides an ash shell that you can use to run a variety of commands on an emulator +or device. The command binaries are stored in the file system of the emulator or device, +in this location:

    + +
    /system/bin/...
    + +

    You can use the shell command to issue commands, with or without entering the adb remote shell on the emulator/device.

    + +

    To issue a single command without entering a remote shell, use the shell command like this:

    + +
    adb [-d|-e|-s {<serialNumber>}] shell <shellCommand>
    + +

    To drop into a remote shell on a emulator/device instance, use the shell command like this:

    + +
    adb [-d|-e|-s {<serialNumber>}] shell
    + +

    When you are ready to exit the remote shell, use CTRL+D or exit to end the shell session.

    + +

    The sections below provide more information about shell commands that you can use.

    + + + +

    Examining sqlite3 Databases from a Remote Shell

    + +

    From an adb remote shell, you can use the +sqlite3 command-line program to +manage SQLite databases created by Android applications. The +sqlite3 tool includes many useful commands, such as +.dump to print out the contents of a table and +.schema to print the SQL CREATE statement for an existing table. +The tool also gives you the ability to execute SQLite commands on the fly.

    + +

    To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data/<package_name>/databases/.

    + +

    Here's an example:

    + +
    $ adb -s emulator-5554 shell
    +# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db
    +SQLite version 3.3.12
    +Enter ".help" for instructions
    +.... enter commands, then quit...
    +sqlite> .exit 
    + +

    Once you've invoked sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb remote shell, use exit or CTRL+D. + + + + +

    UI/Application Exerciser Monkey

    + +

    The Monkey is a program that runs on your emulator or device and generates pseudo-random +streams of user events such as clicks, touches, or gestures, as well as a number of system-level +events. You can use the Monkey to stress-test applications that you are developing, +in a random yet repeatable manner.

    + +

    The simplest way to use the monkey is with the following command, which will launch your +application and send 500 pseudo-random events to it.

    + +
    $ adb shell monkey -v -p your.package.name 500
    + +

    For more information about command options for Monkey, see the complete +UI/Application Exerciser Monkey documentation page.

    + + + + +

    Other Shell Commands

    + +

    The table below lists several of the adb shell commands available. For a complete list of commands and programs, start an emulator instance and use the adb -help command.

    + +
    adb shell ls /system/bin
    + +

    Help is available for most of the commands.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Shell CommandDescriptionComments
    dumpsysDumps system data to the screen.The Dalvik Debug Monitor Server +(DDMS) tool offers integrated debug environment that you may find easier to use.
    dumpstateDumps state to a file.
    logcat [<option>]... [<filter-spec>]...Enables radio logging and prints output to the screen.
    dmesgPrints kernel debugging messages to the screen.
    startStarts (restarts) an emulator/device instance. 
    stopStops execution of an emulator/device instance. 
    + + + +

    Enabling logcat Logging

    + +

    The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command.

    + + + +

    Using logcat Commands

    + +

    You can use the logcat command to view and follow the contents of the system's log buffers. The general usage is:

    + +
    [adb] logcat [<option>] ... [<filter-spec>] ...
    + +

    The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options.

    + +

    You can use the logcat command from your development computer or from a remote adb shell in an emulator/device instance. To view log output in your development computer, you use

    + +
    $ adb logcat
    + +

    and from a remote adb shell you use

    + +
    # logcat
    + + + +

    Filtering Log Output

    + +

    Every Android log message has a tag and a priority associated with it.

    + +
      +
    • The tag of a log message is a short string indicating the system component from which the message originates (for example, "View" for the view system).
    • + +
    • The priority is one of the following character values, ordered from lowest to highest priority:
    • + +
        +
      • V — Verbose (lowest priority)
      • +
      • D — Debug
      • +
      • I — Info (default priority)
      • +
      • W — Warning
      • +
      • E — Error
      • +
      • F — Fatal
      • +
      • S — Silent (highest priority, on which nothing is ever printed)
      • +
      +
    + +

    You can obtain a list of tags used in the system, together with priorities, by running logcat and observing the first two columns +of each message, given as <priority>/<tag>.

    + +

    Here's an example of logcat output that shows that the message relates to priority level "I" and tag "ActivityManager":

    + +
    I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action...}
    + +

    To reduce the log output to a manageable level, you can restrict log output using filter expressions. Filter expressions let you indicate to the system the tags-priority combinations that you are interested in — the system suppresses other messages for the specified tags.

    + +

    A filter expression follows this format tag:priority ..., where tag indicates the tag of interest and priority indicates the minimum level of priority to report for that tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single filter expression. The series of specifications is whitespace-delimited. The default output is to show all log messages with the Info priority (*:I).

    + +

    Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

    + +
    adb logcat ActivityManager:I MyApp:D *:S
    + +

    The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed. Using *:S is an excellent way to ensure that log output is restricted to the filters that you have explicitly specified — it lets your filters serve as a "whitelist" for log output.

    + +

    The following filter expression displays all log messages with priority level "warning" and higher, on all tags:

    + +
    adb logcat *:W
    + +

    If you're running logcat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by exporting a value for the environment variable ANDROID_LOG_TAGS:

    + +
    export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"
    + +

    Note that ANDROID_LOG_TAGS filter is not exported to the emulator/device instance, if you are running logcat from a remote shell or using adb shell logcat.

    + + + + +

    Controlling Log Output Format

    + +

    Log messages contain a number of metadata fields, in addition to the tag and priority. You can modify the output format for messages so that they display a specific metadata field. To do so, you use the -v option and specify one of the supported output formats listed below.

    + +
      +
    • brief — Display priority/tag and the PID of process issuing the message (the default format).
    • +
    • process — Display PID only.
    • +
    • tag — Display the priority/tag only.
    • +
    • raw — Display the raw log message, with no other metadata fields.
    • +
    • time — Display the date, invocation time, priority/tag, and PID of the process issuing the message.
    • +
    • threadtime — Display the date, invocation time, priority, tag, and the PID and TID of the thread issuing the message.
    • +
    • long — Display all metadata fields and separate messages with a blank lines.
    • +
    + +

    When starting logcat, you can specify the output format you want by using the -v option:

    + +
    [adb] logcat [-v <format>]
    + +

    Here's an example that shows how to generate messages in thread output format:

    + +
    adb logcat -v thread
    + +

    Note that you can only specify one output format with the -v option.

    + + + +

    Viewing Alternative Log Buffers

    + +

    The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see additional log messages, you can start logcat with the -b option, to request viewing of an alternate circular buffer. You can view any of these alternate buffers:

    + +
      +
    • radio — View the buffer that contains radio/telephony related messages.
    • +
    • events — View the buffer containing events-related messages.
    • +
    • main — View the main log buffer (default)
    • +
    + +

    The usage of the -b option is:

    + +
    [adb] logcat [-b <buffer>]
    + +

    Here's an example of how to view a log buffer containing radio and telephony messages:

    + +
    adb logcat -b radio
    + + + +

    Viewing stdout and stderr

    + +

    By default, the Android system sends stdout and stderr (System.out and System.err) output to /dev/null. In +processes that run the Dalvik VM, you can have the system write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priority I.

    + +

    To route the output in this way, you stop a running emulator/device instance and then use the shell command setprop to enable the redirection of output. Here's how you do it:

    + +
    $ adb shell stop
    +$ adb shell setprop log.redirect-stdio true
    +$ adb shell start
    + +

    The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop +on the device.

    + + + +

    Listing of logcat Command Options

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OptionDescription
    -b <buffer>Loads an alternate log buffer for viewing, such as event or radio. The main buffer is used by default. See Viewing Alternative Log Buffers.
    -cClears (flushes) the entire log and exits.
    -dDumps the log to the screen and exits.
    -f <filename>Writes log message output to <filename>. The default is stdout.
    -gPrints the size of the specified log buffer and exits.
    -n <count>Sets the maximum number of rotated logs to <count>. The default value is 4. Requires the -r option.
    -r <kbytes>Rotates the log file every <kbytes> of output. The default value is 16. Requires the -f option.
    -sSets the default filter spec to silent.
    -v <format>Sets the output format for log messages. The default is brief format. For a list of supported formats, see Controlling Log Output Format.
    + + + +

    Stopping the adb Server

    + +

    In some cases, you might need to terminate the adb server process and then restart it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem.

    + +

    To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command.

    + + diff --git a/docs/html/tools/help/adt.jd b/docs/html/tools/help/adt.jd new file mode 100644 index 000000000000..cd5bc67e6a3b --- /dev/null +++ b/docs/html/tools/help/adt.jd @@ -0,0 +1,527 @@ +page.title=Android Developer Tools +@jd:body + + + +

    ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of + tools that are integrated with the Eclipse IDE. It offers you access to many features that help + you develop Android applications quickly. ADT + provides GUI access to many of the command line SDK tools as well as a UI design tool for rapid + prototyping, designing, and building of your application's user interface.

    + +

    Because ADT is a plugin for Eclipse, you get the functionality of a well-established IDE, + along with Android-specific features that are bundled with ADT. The following + describes important features of Eclipse and ADT:

    + +
    +
    Integrated Android project creation, building, packaging, installation, and + debugging
    + +
    ADT integrates many development workflow tasks into Eclipse, making it easy for you to + rapidly develop and test your Android applications.
    + +
    SDK Tools integration
    + +
    Many of the SDK tools are integrated into Eclipse's menus, + perspectives, or as a part of background processes ran by ADT.
    + +
    Java programming language and XML editors
    + +
    The Java programming language editor contains common IDE features such as compile time + syntax checking, auto-completion, and integrated documentation for the Android framework APIs. + ADT also provides custom XML editors that let you + edit Android-specific XML files in a form-based UI. A graphical layout editor lets you design + user interfaces with a drag and drop interface.
    + +
    Integrated documentation for Android framework APIs
    +
    You can access documentation by hovering over classes, methods, or variables.
    +
    + +

    You can find the most up-to-date and more detailed information about changes and new features +on the Recent Changes page at the Android Tools +Project site.

    + +

    SDK Tools Integration

    + + + +

    Many of the tools that you can start or run from the command line are integrated into ADT. + They include:

    + +
      +
    • Traceview: + Allows you to profile your program's execution + (Window > Open Perspective > Traceview).
    • + +
    • android: Provides access to + the Android SDK Manager and AVD Manager. Other android features such as creating or + updating projects (application and library) are integrated throughout the Eclipse IDE.
    • + +
    • Hierarchy + Viewer: Allows you to visualize your application's view hierarchy to find inefficiencies + (Window > Open Perspective > Hierarchy Viewer).
    • + +
    • Pixel + Perfect: Allows you to closely examine your UI to help with designing and building. + (Window > Open Perspective > Pixel Perfect).
    • + +
    • DDMS: Provides + debugging features including: screen capturing, thread and heap information, and logcat + (Window > Open Perspective > DDMS).
    • + +
    • adb: Provides access to + a device from your development system. Some features of + adb are integrated into ADT such as project installation (Eclipse run menu), + file transfer, device enumeration, and logcat (DDMS). You must access the more advanced + features of adb, such as shell commands, from the command line.
    • + +
    • ProGuard: Allows code obfuscation, + shrinking, and optimization. ADT integrates ProGuard as part of the build, if you enable it.
    • +
    + +

    Code Editors

    + +

    In addition to Eclipse's standard editor features, ADT provides custom XML editors to help + you create and edit Android manifests, resources, menus, and layouts in a form-based or graphical + mode. Double-clicking on an XML file in Eclipse's package explorer opens the + appropriate XML editor. + +

    + +

    Note: You can edit Android-specific XML files (such as a layout +or manifest) in both a graphical mode and also an XML markup mode. You can switch between +these modes with the pair of tabs at the bottom of each custom XML editor.

    + +

    In addition, some special file types that don't have custom editors, such as drawables, animations, + and color files offer editing enhancements such as XML tag completion.

    + +

    ADT provides the following custom, form-based XML editors:

    + +
    + +
    Graphical Layout Editor
    + +
    Edit and design your XML layout files with a drag and drop interface. The layout editor + renders your interface as well, offering you a preview as you design your layouts. This editor + is invoked when you open an XML file with a view declared (usually declared in + res/layout. For more information, see Graphical Layout + Editor.
    + +
    Android Manifest Editor
    + +
    Edit Android manifests with a simple graphical interface. This editor is invoked + when you open an AndroidManifest.xml file.
    + +
    Menu Editor
    + +
    Edit menu groups and items with a simple graphical interface. This editor is + invoked when you open an XML file with a <menu> declared (usually located in + the res/menu folder).
    + +
    Resources Editor
    + +
    Edit resources with a simple graphical interface. This editor is invoked when + you open an XML file with a <resources> tag declared.
    + +
    XML Resources Editor
    + +
    Edit XML resources with a simple graphical interface. This editor is invoked + when you open an XML file.
    +
    + + +

    Resource linking enhancements

    +

    In addition to the normal code editing features of Eclipse, ADT provides enhancements to the Android + development experience that allow you to quickly jump to declarations of various types of resources such + as strings or layout files. You can access these enhancements by holding down the control key and + clicking on the following items: + +

      + +
    • A resource identifier, such as R.id.button1, jumps + to the XML definition of the view.
    • + +
    • A declaration in the R.java file, such as public + static final int Button01=0x7f050000", jumps to the corresponding XML definition.
    • + +
    • An activity or service definition in your manifest, such as + <activity android:name=".TestActivity">, jumps to the corresponding Java class. You can + jump from an activity definition (or service definition) into the corresponding Java class.
    • + +
    • You can jump to any value definition (e.g. @string:foo), regardless of +which XML file + "foo" is defined in.
    • + +
    • Any file-based declaration, such as @layout/bar, opens the file.
    • + +
    • Non-XML resources, such as @drawable/icon, launches + Eclipse's default application for the given file type, which in this case is an + image.
    • + +
    • @android namespace resources opens the resources found in + the SDK install area.
    • + +
    • Custom views in XML layouts, such as <foo.bar.MyView></foo.bar.MyView>, + or <view class="foo.bar.MyView">) jump to the corresponding custom view classes.
    • + +
    • An XML attribute such as @android:string/ok or android.R.string.id in Java code + opens the file that declares the strings. The XML tab opens when doing this, not + the form-based editor.
    • + +
    + +

    Graphical Layout Editor

    + +

    ADT provides many features to allow you to design and build your application's user interface. + Many of these features are in the graphical layout editor, which you can access by opening one of + your application's XML layout files in Eclipse. +

    + +

    The graphical layout editor is the main screen that you use to visually design and build your + UI. It is split up into the following parts:

    + +
    +
    Canvas
    + +
    In the middle of the editor is the canvas. It provides the rendered view of your + layout and supports dragging and dropping of UI widgets + directly from the palette. You can select the platform version used to render the items in + the canvas. Each platform version has its own look and feel, which might be the similar to or + radically different from another platform version. The canvas renders the appropriate look + and feel for the currently selected platform version. + This platform version does not need to be the same as the version that your + application targets. + +

    The canvas also provides + context-sensitive actions in the layout actions bar, such as adjusting layout margins and +orientation. + The layout actions bar displays available actions depending on the selected UI element in the + canvas.

    +
    + +
    Outline
    + +
    On the right side of the editor is the outline view. It displays a hierarchical + view of your layout where you can do things such as reorder of views. The outline + view exposes similar functionality as the canvas but displays your layout in an ordered + list instead of a rendered preview.
    + +
    Palette
    + +
    On the left side of the editor is the palette. It provides a set of widgets that + you can drag onto the canvas. The palette shows rendered previews of the + widgets for easy lookup of desired UI widgets.
    + +
    Configuration Chooser
    + +
    At the top of the editor is the configuration chooser. + It provides options to change a layout's rendering mode or screen type.
    +
    + + graphical layout editor screenshot + +

    Figure 1. Graphical layout editor

    + +

    Canvas and outline view

    + + + +

    The canvas is the area where you can drag and drop UI widgets from the palette to design your + layout. The canvas offers a rendered preview of your layout depending on factors such as the + selected platform version, screen orientation, and currently selected theme that you specify in + the configuration chooser. You can also drag and drop + items into the outline view, which displays your layout in a hierarchical list. The outline view + exposes much of the same functionality as the canvas but offers another method of organization + that is beneficial for ordering and quickly selecting items. When you right-click a specific item + in the canvas or outline view, you can access a context-sensitive menu that lets you modify the + following attributes of the layout or view:

    + +
    +
    View and layout properties
    + +
    + When you right-click a view or layout in the canvas or outline view, it brings up a + context-sensitive menu that lets you set things such as: + +
      +
    • ID of the view or layout
    • + +
    • Text of the view
    • + +
    • Layout width
    • + +
    • Layout height
    • + +
    • Properties such as alpha or clickable
    • +
    +
    + +
    Animation preview and creation
    + +
    + If your layout or view is animated, you can preview the animation directly in the canvas + (when you select Android 3.0 or later as the platform version in the configuration chooser). + Right-click an item in the canvas and select Play Animation. If + animation is not associated with item, an option is available in the menu to create one. + +

    View the segment on the animation features for more + information.

    +
    + +
    Extract as Include
    + +
    You can extract parts of a current layout into its own layout file, + which you can then include in any layout with a single line of XML. See Layout Refactoring Support for more information.
    +
    + +

    Other canvas features

    + +

    The canvas has additional features not available in the outline view:

    + +
      + +
    • Edit views with the layout actions bar: The context-sensitive layout actions bar allows you to + edit how a view is laid out in your UI. The available actions depend on the currently + selected view and its parent layout. Some common actions include + toggling the fill mode of the view and specifying margins. For instance, if you select a + {@link android.widget.Button} + in a {@link android.widget.LinearLayout}, you see actions related to the {@link +android.widget.LinearLayout}, such as a toggle to switch + between horizontal and vertical layout, and a toggle to control whether its children are + aligned along their text baseline. You will also see toolbar actions to control the individual + layout attributes of the child, such as whether the child should stretch out to match its + parent's width and height, a dropdown action to set the child's layout gravity, a button to open + a margin editor, and a layout weight editor.
    • + +
    • Edit a nested layout in its current context: If you are editing a layout + that includes another layout, you can edit the included layout in the layout that included + it.
    • + +
    • Preview drag and drop location: When you drag and drop a UI widget onto the canvas, ruler + markers appear showing you the approximate location of the UI widget depending on the + type of layout, such as {@link android.widget.RelativeLayout} or {@link + android.widget.LinearLayout}.
    • + +
    • Preview animations: You can preview view and layout animations when you select Android 2.1 + or later for the platform version in the configuration bar.
    • + +
    • Render layouts in real-time: Layouts are rendered as accurately as possible according to + the platform version, including the appropriate system and action bars.
    • + +
    • Support for fragments: Fragments can be rendered in the same screen as the layout that + includes the fragments.
    • + +
    + + screenshot of the canvas + +

    Figure 2. Canvas portion of the layout editor showing + a rendered preview of an application

    + + screenshot of the outline view + +

    Figure 3. Outline view showing current layout's structure

    + +

    Palette

    + + + +

    The palette contains the UI widgets that you can drag and drop onto the canvas and add to your + layout. The pallete categorizes the widgets and shows rendered previews + for easier lookup. The main features of the palette include:

    + +
      +
    • Different modes of rendered previews include: icons only, icons and text, tiny previews, + small previews, and previews (rendered in real size). Previews are only available for layouts + rendered with the latest revisions of Android 2.1 (API Level 7) or later.
    • + +
    • Custom views in your project or library projects are added under custom views + category.
    • + +
    • Arrange UI widgets alphabetically or by category.
    • +
    + palette screenshot + +

    Figure 4. Palette showing available UI widgets

    + +

    Configuration chooser

    + + + + +

    The configuration chooser allows you to create and configure different configurations of + a layout for different situations, such as one for landscape and one for portrait mode. You can + set the following options for each configuration of a layout: +

    +
      +
    • Screen type combo box: Predefined screen settings for common device configurations. You + can also create your own by selecting Custom....
    • + +
    • Screen orientation combo box: Portrait or Landscape screen orientation.
    • + +
    • Theme combo box: Predefined themes or a custom theme that you have created.
    • + +
    • Platform combo box: Platform version used to render the canvas and palette as well as + displaying appropriate themes.
    • + +
    • Custom layout combo boxes: The locale, dock, and time of day combo boxes let you select + different versions of the same layout depending on the device's current state. You can + create a new version of a layout with the Create button.
    • +
    + + + + +

    Figure 5. Configuration chooser

    + +

    Layout Refactoring Support

    + + + +

    In both the graphical and XML layout editor, there are many features that help you quickly + refactor your layouts. The following list describes the major refactoring support:

    + +
    + +
    Change layout
    +
    This lets you change the layout on the fly and re-renders the canvas for you. + You can apply this refactoring to any layout and the layout is converted to the new type if + possible. In many cases, the opening and closing tags of the layout's XML element are changed + along with things such as ID attributes and their references. However, for some supported + types, ADT attempts to preserve the layout, such as changing a {@link + android.widget.LinearLayout} to a {@link android.widget.RelativeLayout}.
    + +
    Change widget
    +
    This lets you select one or more widgets and converts them to a new widget type. In + addition to changing the element name, it also removes any + attributes that are not supported by the new widget type and adds in any mandatory attributes + required by the new widget type. If the current ID of a widget includes the + current widget type in its ID (such as a <Button> widget named + "button1"), then the ID is changed to match the new widget type and all + references are updated.
    + +
    Extract as include
    +
    This lets you extract views inside of an existing layout into their own separate layout + file. An include tag that points to the newly created layout file is inserted + into the existing layout file. Right-click the view or layout and select Extract as + Include....
    + +
    Extract string
    +
    Extract strings from either XML or Java files into their own separate resource file.
    + +
    Extract style
    +
    Extract style-related attributes from a layout and define them in a new + styles.xml file. You can select multiple views and this refactoring extracts all + of the same styles into one style and assigns that style to all the views that use it.
    + +
    Wrap-in container
    +
    This lets you select one or more sibling elements and wrap them in a new container. This + can be applied to the root element as well, in which case the namespace declaration attributes + will be transferred to the new root. This refactoring also transfers layout_ + attribute references to the new root, For example, suppose you have a {@link android.widget.RelativeLayout}. + If other widgets have layout constraints pointing to your widget, wrapping the widget causes + these constraints to point to the parent instead.
    + +
    Quick Assistant
    +
    Provides refactoring suggestions depending on the current context. Press + Ctrl-1 (or Cmd-1 on + Mac) in an editor, and Eclipse provides a list of possible refactorings depending on the + context. The Quick Assistant provides fast access to all of the above refactorings, where applicable. + For example, if you are editing an XML value and decide you want to extract it out + as a string, place the text cursor in the string and press Ctrl-1 to see the refactoring context + menu.
    +
    diff --git a/docs/html/tools/help/android.jd b/docs/html/tools/help/android.jd new file mode 100644 index 000000000000..282c791c10d4 --- /dev/null +++ b/docs/html/tools/help/android.jd @@ -0,0 +1,393 @@ +page.title=android +parent.title=Tools +parent.link=index.html +@jd:body + +

    {@code android} is an important development tool that lets you:

    + + If you are using Eclipse, the android tool's features are integrated + into ADT, so you should not need to use this tool directly. + +

    Note: The documentation of options below is not exhaustive +and may be out of date. For the most current list of options, execute android +--help.

    + + + + +

    Syntax

    +
    android [global options] action [action options]
    + +

    Global Options

    + +
    +
    -s
    + +
    Silent mode: only errors are printed out
    + +
    -h
    + +
    Usage help
    + +
    -v
    + +
    Verbose mode: errors, warnings and informational messages are printed.
    +
    + +

    AVD actions and options

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ActionOptionDescriptionComments
    avdNoneLaunch the AVD Manager
    sdkNoneLaunch the Android SDK Manager
    create avd-n <name>The name for the AVD.Required
    -t <targetID>Target ID of the system image to use with the new AVD. To obtain a list of available + targets, use android list targetsRequired
    -c <path>|<size>[K|M]The path to the SD card image to use with this AVD or the size of a new SD card image to + create for this AVD. For example, -c path/to/sdcard or -c + 1000M.
    -fForce creation of the AVD
    -p <path>Path to the location at which to create the directory for this AVD's files.
    -s <name>|<width>-<height>The skin to use for this AVD, identified by name or dimensions. The android + tool scans for a matching skin by name or dimension in the skins/ directory of + the target referenced in the -t <targetID> argument. For example, -s + HVGA-L
    delete avd-n <name>The name of the AVD to deleteRequired
    move avd-n <name>The name of the AVD to moveRequired
    -p <path>Path to the location at which to create the directory for this AVD's files.
    -r <new-name>New name of the AVD if you want to rename it
    update avd-n <name>The name of the AVD to moveRequired
    + +

    Project actions and options

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ActionOptionDescriptionComments
    create project-n <name>The name for the projectRequired
    -t <targetID>Target ID of the system image to use with the new AVD. To obtain a list of available + targets, use android list targetsRequired
    -k <path>|<size>[K|M]Package namespaceRequired
    -aName for the default Activity classRequired
    -p <path>Location of your project directoryRequired
    update project-n <name>The name of the project to update
    -p <path>Location path of the projectRequired
    -l <library path>Location path of an Android Library to add, relative to the main project
    -s <subprojects>Update any projects in subfolders such as test projects
    -t <targetID>Target id to set for the project
    create-test-project-n <name>The name of the project
    -p <path>Location path of the projectRequired
    -m <main>The name of the projectRequired
    update-test-project-p <path>Location path of the project to test, relative to the new projectRequired
    -m <main>The main class of the project to testRequired
    create-lib-project-k <packageName>(Required) Package name of the library projectRequired
    -p <path>Location path of the projectRequired
    -t <targetID>Target ID of the library projectRequired
    -n <name>The name of the projectRequired
    update-lib-project-p <path>Location path of the projectRequired
    -l <libraryPath>Location path of an Android Library to add, relative to the main project
    -t <name>Target ID of the library project
    + +

    Update actions

    +
    +
    update adb
    +
    Updates adb to support the USB devices declared in the SDK add-ons.
    + +
    update sdk
    +
    Updates the SDK by suggesting new platforms to install if available.
    diff --git a/docs/html/tools/help/bmgr.jd b/docs/html/tools/help/bmgr.jd new file mode 100644 index 000000000000..2248fa6712e3 --- /dev/null +++ b/docs/html/tools/help/bmgr.jd @@ -0,0 +1,193 @@ +page.title=bmgr +parent.title=Tools +parent.link=index.html +@jd:body + + + +
    +
    +

    bmgr quickview

    +

    bmgr lets you control the backup/restore system on an Android device. + +

    In this document

    +
      +
    1. Forcing a Backup Operation
    2. +
    3. Forcing a Restore Operation
    4. +
    5. Other Commands
    6. +
    + +

    See also

    +
      +
    1. Data Backup
    2. +
    + +
    +
    + + + +

    bmgr is a shell tool you can use to interact with the Backup Manager +on Android devices supporting API Level 8 or greater. It provides commands to induce backup +and restore operations so that you don't need to repeatedly wipe data or take similar +intrusive steps in order to test your application's backup agent. These commands are +accessed via the adb shell. + +

    For information about adding support for backup in your application, read Data Backup, which includes a guide to testing +your application using {@code bmgr}.

    + + +

    Forcing a Backup Operation

    + +

    Normally, your application must notify the Backup Manager when its data has changed, via {@link +android.app.backup.BackupManager#dataChanged()}. The Backup Manager will then invoke your +backup agent's {@link +android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor) +onBackup()} implementation at some time in the future. However, instead of calling {@link +android.app.backup.BackupManager#dataChanged()}, you can invoke a backup request from the command +line by running the bmgr backup command: + +

    adb shell bmgr backup <package>
    + +

    <package> is the formal package name of the application you wish to +schedule for +backup. When you execute this backup command, your application's backup agent will be invoked to +perform a backup operation at some time in the future (via your {@link +android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor,BackupDataOutput,ParcelFileDescriptor) +onBackup()} method), though there is no guarantee when it will occur. However, you can force all +pending backup operations to run immediately by using the bmgr run command: + +

    adb shell bmgr run
    + +

    This causes a backup pass to execute immediately, invoking the backup agents of all applications +that had previously called {@link android.app.backup.BackupManager#dataChanged()} since the +last backup operation, plus any applications which had been manually scheduled for +backup via bmgr backup. + + + +

    Forcing a Restore Operation

    + +

    Unlike backup operations, which are batched together and run on an occasional basis, restore +operations execute immediately. The Backup Manager currently provides two kinds of restore +operations. The first kind restores an entire device with the data that has been backed up. This +is typically performed only when a device is first provisioned (to replicate settings and other +saved state from the user's previous device) and is an operation that only the system can +perform. The second kind of restore operation restores +a single application to its "active" data set; that is, the application will abandon its current +data and revert to the last-known-good data that is held in the current backup image. You can +invoke this second restore operation with the {@link +android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method. The +Backup Manager will then invoke your backup agent's {@link +android.app.backup.BackupAgent#onRestore(BackupDataInput,int,ParcelFileDescriptor) +onRestore()} implementation. + +

    While testing your application, you can immediately invoke the restore operation (bypassing the +{@link android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method) +for your application by using the bmgr restore command: + +

    adb shell bmgr restore <package>
    + +

    <package> is the formal Java-style package name of the application +participating in the backup/restore mechanism, which you would like to restore. The Backup +Manager will immediately instantiate the application's backup agent and invoke it for restore. This +will happen even if your application is not currently running. + + + + + +

    Other Commands

    + +

    Wiping data

    + +

    The data for a single application can be erased from the active data set on demand. This is +very useful while you're developing a backup agent, in case bugs lead you to write corrupt data +or saved state information. You can wipe an application's data with the bmgr wipe +command: + +

    adb shell bmgr wipe <package>
    + +

    <package> is the formal package name of the application whose data +you wish to +erase. The next backup operation that the application's agent processes will look as +though the application had never backed anything up before. + + +

    Enabling and disabling backup

    + +

    You can see whether the Backup Manager is operational at all with the bmgr +enabled command: + +

    adb shell bmgr enabled
    + +

    This might be useful if your application's backup agent is never being invoked for backup, to +verify whether the operating system thinks it should be performing such operations at all.

    + +

    You can also directly disable or enable the Backup Manager with this command: + +

    adb shell bmgr enable <boolean>
    + +

    <boolean> is either true or false. +This is equivalent to disabling or enabling backup in the device's main Settings UI.

    + +

    Warning! When backup is disabled, the current backup transport +will explicitly wipe +the entire active data set from its backend storage. This is so that when a user says +they do not want their data backed up, the Backup Manager respects that wish. No further +data will be saved from the device, and no restore operations will be possible, unless the Backup +Manager is re-enabled (either through Settings or through the above bmgr command). + + + + + diff --git a/docs/html/tools/help/ddms.html b/docs/html/tools/help/ddms.html new file mode 100644 index 000000000000..d885d561dd00 --- /dev/null +++ b/docs/html/tools/help/ddms.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/tools/help/dmtracedump.jd b/docs/html/tools/help/dmtracedump.jd new file mode 100644 index 000000000000..bdc820d87ffd --- /dev/null +++ b/docs/html/tools/help/dmtracedump.jd @@ -0,0 +1,66 @@ +page.title=dmtracedump +parent.title=Tools +parent.link=index.html +@jd:body + + +

    dmtracedump is a tool that gives you an alternate way of generating + graphical call-stack diagrams from trace log files (instead of using Traceview).

    + +

    This document is a reference to the available command line options. For more information on generating trace + logs, see Profiling with + Traceview and dmtracedump.

    + +

    The usage for dmtracedump is:

    +
    +dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
    +
    + +

    The tool then loads trace log data from <trace-base-name>.data and + <trace-base-name>.key. The table below lists the options for dmtracedump.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OptionDescription
    -d <trace-base-name>Diff with this trace name
    -g <outfile>Generate output to <outfile>
    -hTurn on HTML output
    -oDump the trace file instead of profiling
    -d <trace-base-name>URL base to the location of the sortable javascript file
    -t <percent>Minimum threshold for including child nodes in the graph (child's inclusive time as a + percentage of parent inclusive time). If this option is not used, the default threshold is + 20%.
    \ No newline at end of file diff --git a/docs/html/tools/help/draw9patch.jd b/docs/html/tools/help/draw9patch.jd new file mode 100644 index 000000000000..7cf0e4b1d861 --- /dev/null +++ b/docs/html/tools/help/draw9patch.jd @@ -0,0 +1,59 @@ +page.title=Draw 9-patch +parent.title=Tools +parent.link=index.html +@jd:body + +

    The Draw 9-patch tool allows you to easily create a + {@link android.graphics.NinePatch} graphic using a WYSIWYG editor.

    +

    For an introduction to Nine-patch graphics and how they work, please read +the section about Nine-patch in the +2D Graphics +document.

    + + + +

    Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool. +You'll need the PNG image with which you'd like to create a NinePatch.

    + +
      +
    1. From a terminal, launch the draw9patch application from your SDK + /tools directory. +
    2. +
    3. Drag your PNG image into the Draw 9-patch window + (or File > Open 9-patch... to locate the file). + Your workspace will now open. +

      The left pane is your drawing area, in which you can edit the lines for the + stretchable patches and content area. The right + pane is the preview area, where you can preview your graphic when stretched.

      +
    4. +
    5. Click within the 1-pixel perimeter to draw the lines that define the stretchable + patches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase + previously drawn lines. +
    6. +
    7. When done, select File > Save 9-patch... +

      Your image will be saved with the .9.png file name.

      +
    8. +
    +

    Note: A normal PNG file (*.png) will be + loaded with an empty one-pixel border added around the image, in which you can draw + the stretchable patches and content area. + A previously saved 9-patch file (*.9.png) will be loaded as-is, + with no drawing area added, because it already exists.

    + + + +

    Optional controls include:

    +
      +
    • Zoom: Adjust the zoom level of the graphic in the drawing area.
    • +
    • Patch scale: Adjust the scale of the images in the preview area.
    • +
    • Show lock: Visualize the non-drawable area of the graphic on mouse-over.
    • +
    • Show patches: Preview the stretchable patches in the drawing area (pink is a + stretchable patch).
    • +
    • Show content: Highlight the content area in the preview images + (purple is the area in which content is allowed).
    • +
    • Show bad patches: Adds a red border around patch areas that may + produce artifacts in the graphic when stretched. Visual coherence of your stretched + image will be maintained if you eliminate all bad patches.
    • +
        diff --git a/docs/html/tools/help/emulator.jd b/docs/html/tools/help/emulator.jd new file mode 100644 index 000000000000..fa101e19638e --- /dev/null +++ b/docs/html/tools/help/emulator.jd @@ -0,0 +1,581 @@ +page.title=Android Emulator +parent.title=Tools +parent.link=index.html +@jd:body + +
        + +
        + + +

        The Android SDK includes a mobile device emulator — a virtual mobile device +that runs on your computer. The emulator lets you develop and test +Android applications without using a physical device.

        + +

        This document is a reference to the available command line options and the keyboard mapping to +device keys. +For a complete guide to using the Android Emulator, see +Using the Android Emulator. + + +

        Keyboard Commands

        + +

        Table 1 summarizes the mappings between the emulator keys and the keys of your keyboard.

        + +

        Table 1. Emulator keyboard mapping

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        Emulated Device Key Keyboard Key
        HomeHOME
        Menu (left softkey)F2 or Page-up button
        Star (right softkey)Shift-F2 or Page Down
        BackESC
        Call/dial button F3
        Hangup/end call buttonF4
        SearchF5
        Power buttonF7
        Audio volume up buttonKEYPAD_PLUS, Ctrl-F5
        Audio volume down buttonKEYPAD_MINUS, Ctrl-F6
        Camera buttonCtrl-KEYPAD_5, Ctrl-F3
        Switch to previous layout orientation (for example, portrait, landscape)KEYPAD_7, Ctrl-F11
        Switch to next layout orientation (for example, portrait, landscape)KEYPAD_9, Ctrl-F12
        Toggle cell networking on/offF8
        Toggle code profilingF9 (only with -trace startup option)
        Toggle fullscreen modeAlt-Enter
        Toggle trackball modeF6
        Enter trackball mode temporarily (while key is pressed)Delete
        DPad left/up/right/downKEYPAD_4/8/6/2
        DPad center clickKEYPAD_5
        Onion alpha increase/decreaseKEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)
        + + +

        Command Line Parameters

        + +

        The emulator supports a variety of options that you can specify +when launching the emulator, to control its appearance or behavior. +Here's the command-line syntax of the options available to the {@code emulator} program:

        + +
        emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>]
        + +

        Table 2. Emulator command line parameters

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + s + + + + + + + + + + + + + + + +
        CategoryOptionDescriptionComments
        AVD-avd <avd_name> or
        + @<avd_name>
        Required. Specifies the AVD to load for this emulator + instance.You must create an AVD configuration before launching the emulator. For + information, see Managing + AVDs with AVD Manager.
        Disk Images-cache <filepath>Use <filepath> as the working cache partition image. An absolute or relative path to the current working directory. + If no cache file is specified, the emulator's default behavior is to use a temporary file instead. +

        For more information on disk images, use -help-disk-images.

        +
        -data <filepath>Use {@code <filepath>} as the working user-data disk image. Optionally, you can specify a path relative to the current working directory. + If -data is not used, the emulator looks for a file named {@code userdata-qemu.img} + in the storage area of the AVD being used (see -avd). +
        -initdata <filepath>When resetting the user-data image (through -wipe-data), copy the contents + of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img.Optionally, you can specify a path relative to the current working directory. See also -wipe-data. +

        For more information on disk images, use -help-disk-images.

        -nocacheStart the emulator without a cache partition.See also -cache <file>.
        -ramdisk <filepath>Use <filepath> as the ramdisk image.Default value is <system>/ramdisk.img. +

        Optionally, you can specify a path relative to the current working directory. + For more information on disk images, use -help-disk-images.

        +
        -sdcard <filepath>Use <file> as the SD card image.Default value is <system>/sdcard.img. +

        Optionally, you can specify a path relative to the current working directory. For more information on disk images, use -help-disk-images.

        +
        -wipe-dataReset the current user-data disk image (that is, the file specified by -datadir and + -data, or the default file). The emulator deletes all data from the user data image file, + then copies the contents of the file at -inidata data to the image file before starting. + See also -initdata. +

        For more information on disk images, use -help-disk-images.

        +
        Debug-debug <tags>Enable/disable debug messages for the specified debug tags.<tags> is a space/comma/column-separated list of debug component names. + Use -help-debug-tags to print a list of debug component names that you can use.
        -debug-<tag>Enable/disable debug messages for the specified debug tag.Use -help-debug-tags to print a list of debug component names that you can use in <tag>.
        -debug-no-<tag>Disable debug messages for the specified debug tag.
        -logcat <logtags>Enable logcat output with given tags.If the environment variable ANDROID_LOG_TAGS is defined and not + empty, its value will be used to enable logcat output by default.
        -shellCreate a root shell console on the current terminal.You can use this command even if the adb daemon in the emulated system is broken. + Pressing Ctrl-c from the shell stops the emulator instead of the shell.
        -shell-serial <device>Enable the root shell (as in -shell and specify the QEMU character + device to use for communication with the shell.<device> must be a QEMU device type. See the documentation for '-serial dev' at + http://wiki.qemu.org/download/qemu-doc.html + for a list of device types. + +

        Here are some examples:

        +
          +
        • -shell-serial stdio is identical to -shell
        • +
        • -shell-serial tcp::4444,server,nowait lets you communicate with the shell over TCP port 4444
        • +
        • -shell-serial fdpair:3:6 lets a parent process communicate with the shell using fds 3 (in) and 6 (out)
        • +
        • -shell-serial fdpair:0:1 uses the normal stdin and stdout fds, except that QEMU won't tty-cook the data.
        • +
        +
        -show-kernel <name>Display kernel messages. 
        -trace <name>Enable code profiling (press F9 to start), written to a specified file. 
        -verboseEnable verbose output.Equivalent to -debug-init. +

        You can define the default verbose output options used by emulator instances in the Android environment variable +ANDROID_VERBOSE. Define the options you want to use in a comma-delimited list, specifying only the stem of each option: +-debug-<tags>.

        +

        Here's an example showing ANDROID_VERBOSE defined with the -debug-init and -debug-modem options: +

        ANDROID_VERBOSE=init,modem

        +

        For more information about debug tags, use <-help-debug-tags>.

        +
        Media-audio <backend>Use the specified audio backend. 
        -audio-in <backend>Use the specified audio-input backend. 
        -audio-out <backend>Use the specified audio-output backend. 
        -noaudioDisable audio support in the current emulator instance. 
        -radio <device>Redirect radio modem interface to a host character device. 
        -useaudioEnable audio support in the current emulator instance.Enabled by default.
        Network-dns-server <servers>Use the specified DNS server(s). The value of <servers> must be a comma-separated list of up to 4 DNS server names or + IP addresses.
        -http-proxy <proxy>Make all TCP connections through a specified HTTP/HTTPS proxyThe value of <proxy> can be one of the following:
        + http://<server>:<port>
        + http://<username>:<password>@<server>:<port> +

        The http:// prefix can be omitted. If the -http-proxy <proxy> command is not supplied, + the emulator looks up the http_proxy environment variable and automatically uses any value matching + the <proxy> format described above.

        -netdelay <delay>Set network latency emulation to <delay>.Default value is none. See the table in + Network Delay Emulation + for supported <delay> values.
        -netfastShortcut for -netspeed full -netdelay none 
        -netspeed <speed>Set network speed emulation to <speed>.Default value is full. See the table in + Network Speed Emulation for + supported <speed> values.
        -port <port>Set the console port number for this emulator instance to <port>.The console port number must be an even integer between 5554 and 5584, inclusive. <port>+1 + must also be free and will be reserved for ADB.
        -report-console <socket>Report the assigned console port for this emulator instance to a remote third party + before starting the emulation. <socket> must use one of these formats: + +

        tcp:<port>[,server][,max=<seconds>]
        +unix:<port>[,server][,max=<seconds>]

        + +

        Use -help-report-console

        to view more information about this topic.
        System-cpu-delay <delay>Slow down emulated CPU speed by <delay> Supported values for <delay> are integers between 0 and 1000. + +

        Note that the <delay> does not correlate to clock speed or other absolute metrics +— it simply represents an abstract, relative delay factor applied non-deterministically +in the emulator. Effective performance does not always +scale in direct relationship with <delay> values.

        +
        -gps <device>Redirect NMEA GPS to character device.Use this command to emulate an NMEA-compatible GPS unit connected to + an external character device or socket. The format of <device> must be QEMU-specific + serial device specification. See the documentation for 'serial -dev' at + http://wiki.qemu.org/download/qemu-doc.html. +
        -nojniDisable JNI checks in the Dalvik runtime. 
        -qemuPass arguments to the qemu emulator software.

        Important: When using this option, make sure it is the + last option specified, since all options after it are interpretted as qemu-specific + options.

        -qemu -enable-kvmEnable KVM acceleration of the emulator virtual machine.This option is only effective when your system is set up to use + KVM-based VM acceleration. + You can optionally specify a memory size ({@code -m <size>}) for the VM, which should match + your emulator's memory size:

        + {@code -qemu -m 512 -enable-kvm}
        + {@code -qemu -m 1024 -enable-kvm} +
        -qemu -hDisplay qemu help.
        -gpu onTurn on graphics acceleration for the emulator.This option is only available for emulators using a system image with API Level 15, revision 3 + and higher. For more information, see + Using the Android + Emulator.
        -radio <device>Redirect radio mode to the specified character device.The format of <device> must be QEMU-specific + serial device specification. See the documentation for 'serial -dev' at +http://wiki.qemu.org/download/qemu-doc.html. +
        -timezone <timezone>Set the timezone for the emulated device to <timezone>, instead of the host's timezone.<timezone> must be specified in zoneinfo format. For example: +

        "America/Los_Angeles"
        +"Europe/Paris"

        +
        -versionDisplay the emulator's version number. 
        UI-dpi-device <dpi>Scale the resolution of the emulator to match the screen size + of a physical device.The default value is 165. See also -scale.
        -no-boot-animDisable the boot animation during emulator startup.Disabling the boot animation can speed the startup time for the emulator.
        -no-windowDisable the emulator's graphical window display. 
        -scale <scale>Scale the emulator window. <scale> is a number between 0.1 and 3 that represents the desired scaling factor. You can + also specify scale as a DPI value if you add the suffix "dpi" to the scale value. A value of "auto" + tells the emulator to select the best window size.
        -raw-keysDisable Unicode keyboard reverse-mapping. 
        -noskinDon't use any emulator skin. 
        -keyset <file>Use the specified keyset file instead of the default.The keyset file defines the list of key bindings between the emulator and the host keyboard. + For more information, use -help-keyset to print information about this topic. +
        -onion <image>Use overlay image over screen.No support for JPEG. Only PNG is supported.
        -onion-alpha <percent>Specify onion skin translucency value (as percent). + Default is 50.
        -onion-rotation <position>Specify onion skin rotation. + <position> must be one of the values 0, 1, 2, 3.
        -skin <skinID>This emulator option is deprecated. Please set skin options using AVDs, rather than by using this emulator +option. Using this option may yield unexpected and in some cases misleading +results, since the density with which to render the skin may not be defined. +AVDs let you associate each skin with a default density and override the default +as needed. For more information, see Managing Virtual Devices +with AVD Manager. +
        -skindir <dir>This emulator option is deprecated. See comments for -skin, above.
        Help-helpPrint a list of all emulator options. 
        -help-allPrint help for all startup options. 
        -help-<option>Print help for a specific startup option. 
        -help-debug-tagsPrint a list of all tags for -debug <tags>. 
        -help-disk-imagesPrint help for using emulator disk images. 
        -help-environmentPrint help for emulator environment variables. 
        -help-keysPrint the current mapping of keys. 
        -help-keyset-filePrint help for defining a custom key mappings file. 
        -help-virtual-devicePrint help for Android Virtual Device usage. 
        diff --git a/docs/html/tools/help/etc1tool.jd b/docs/html/tools/help/etc1tool.jd new file mode 100644 index 000000000000..a7f76f5cadb6 --- /dev/null +++ b/docs/html/tools/help/etc1tool.jd @@ -0,0 +1,68 @@ +page.title=etc1tool +parent.title=Tools +parent.link=index.html +@jd:body + + +

        etc1tool is a command line utility that lets you encode PNG + images to the ETC1 compression standard and decode ETC1 compressed images back to PNG.

        + +

        The usage for etc1tool is:

        +
        etc1tool infile [--help | --encode | --encodeNoHeader | --decode] [--showDifference
        +diff-file] [-o outfile]
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        OptionDescription
        infileThe input file to compress
        --helpPrint usage information
        --encodeCreate an ETC1 file from a PNG file. + This is the default mode for the tool if nothing is specified.
        --encodeNoHeaderCreate a raw ETC1 data file (without a header) from a PNG file.
        --decodeCreate a PNG file from an ETC1 file
        --showDifference diff-fileWrite the difference between the original and encoded image to + diff-file (only valid when encoding).
        -o outfileSpecify the name of the output file. + If outfile is not specified, the output file is constructed + from the input filename with the appropriate suffix (.pkm or .png). +
        \ No newline at end of file diff --git a/docs/html/tools/help/hierarchy-viewer.jd b/docs/html/tools/help/hierarchy-viewer.jd new file mode 100644 index 000000000000..4a346e00fc01 --- /dev/null +++ b/docs/html/tools/help/hierarchy-viewer.jd @@ -0,0 +1,18 @@ +page.title=Hierarchy Viewer +parent.title=Tools +parent.link=index.html +@jd:body + +

        Hierarchy Viewer allows you to debug and optimize your user +interface. It provides a visual representation of the layout's View hierarchy +(the Layout View) and a magnified inspector of the display (the Pixel Perfect View). +

        + +

        To start Hierarchy Viewer, enter the following command from the SDK tools/ directory:

        +
        hierarchyviewer
        + + +

        For more information on how to use Hierarchy Viewer, see +Debugging and Profiling UIs +

        + diff --git a/docs/html/tools/help/hprof-conv.jd b/docs/html/tools/help/hprof-conv.jd new file mode 100644 index 000000000000..f96def205fb1 --- /dev/null +++ b/docs/html/tools/help/hprof-conv.jd @@ -0,0 +1,16 @@ +page.title=HPROF Converter +parent.title=Tools +parent.link=index.html +@jd:body + +

        +The hprof-conv tool converts the HPROF file that is +generated by the Android SDK tools to a standard format so you +can view the file in a profiling tool of your choice.

        + +
         hprof-conv <infile> <outfile>
        + +

        +You can use "-" for <infile> or <outfile> +to specify stdin or stdout. +

        diff --git a/docs/html/tools/help/index.jd b/docs/html/tools/help/index.jd new file mode 100644 index 000000000000..aa95de2992c2 --- /dev/null +++ b/docs/html/tools/help/index.jd @@ -0,0 +1,84 @@ +page.title=Tools +@jd:body + + +

        The Android SDK includes a variety of tools that help you develop mobile +applications for the Android platform. The tools are classified into two groups: SDK tools +and platform tools. SDK tools are platform independent and are required no matter which +Android platform you are developing on. Platform tools are customized to support the features of the +latest Android platform.

        + +

        SDK Tools

        +

        The SDK tools are installed with the SDK starter package and are periodically updated. +The SDK tools are required if you are developing Android applications. The most important SDK tools +include the Android SDK Manager (android sdk), the AVD Manager (android +avd) the emulator (emulator), and the Dalvik Debug Monitor Server +(ddms). A short summary of some frequently-used SDK tools is provided below.

        + +
        +
        android
        +
        Lets you manage AVDs, projects, and the installed components of the SDK.
        +
        Dalvik Debug Monitor +Server (ddms)
        +
        Lets you debug Android applications.
        +
        dmtracedump
        +
        Generates graphical call-stack diagrams from trace log files. The tool uses the +Graphviz Dot utility to create the graphical output, so you need to install Graphviz before +running dmtracedump. For more information on using dmtracedump, see Profiling +with Traceview and dmtracedump
        +
        Draw 9-patch
        +
        Allows you to easily create a {@link android.graphics.NinePatch} graphic using a +WYSIWYG editor. It also previews stretched versions of the image, and highlights the area in which +content is allowed.
        +
        Android Emulator (emulator)
        +
        A QEMU-based device-emulation tool that you can use to design, debug, and test +your applications in an actual Android run-time environment.
        +
        Hierarchy Viewer (hierarchyviewer)
        +
        Lets you debug and optimize an Android application's user interface.
        +
        hprof-conv
        +
        Converts the HPROF file that is generated by the Android SDK tools to a standard format so +you can view the file in a profiling tool of your choice.
        +
        layoutopt
        +
        Lets you quickly analyze your application's layouts in order to optimize them for +efficiency.
        +
        mksdcard
        +
        Helps you create a disk image that you can use with the emulator, to simulate the presence +of an external storage card (such as an SD card).
        +
        Monkey
        +
        Runs on your emulator or device and generates pseudo-random streams of user events such +as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey +to stress-test applications that you are developing, in a random yet repeatable manner.
        +
        monkeyrunner
        +
        Provides an API for writing programs that control an Android device or emulator from +outside of Android code.
        +
        ProGuard
        +
        Shrinks, optimizes, and obfuscates your code by removing unused code and renaming +classes, fields, and methods with semantically obscure names.
        +
        sqlite3
        +
        Lets you access the SQLite data files created and used by Android applications.
        +
        traceview
        +
        Provides a graphical viewer for execution logs saved by your application.
        +
        zipalign
        +
        Optimizes .apk files by ensuring that all uncompressed data starts with a +particular alignment relative to the start of the file. This should always be used to align .apk +files after they have been signed.
        +
        + +

        Platform Tools

        + +

        The platform tools are typically updated every time you install a new SDK platform. Each update +of the platform tools is backward compatible with older platforms. Usually, you directly use only +one of the platform tools—the Android Debug Bridge (adb). +Android Debug Bridge is a versatile tool that lets you manage the state of an emulator instance or +Android-powered device. You can also use it to install an Android application (.apk) file on a +device.

        + +

        The other platform tools, such as aidl, +aapt, dexdump, and dx, are typically called by the Android +build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. +As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.

        + +

        Note: The Android SDK provides additional shell tools that can +be accessed through adb, such as bmgr and +logcat.

        \ No newline at end of file diff --git a/docs/html/tools/help/layoutopt.jd b/docs/html/tools/help/layoutopt.jd new file mode 100644 index 000000000000..1308b1e71a72 --- /dev/null +++ b/docs/html/tools/help/layoutopt.jd @@ -0,0 +1,24 @@ +page.title=layoutopt +parent.title=Tools +parent.link=index.html +@jd:body + +

        layoutopt is a command-line tool that helps you optimize the +layouts and layout hierarchies of your applications.

        + +

        This document is a reference to the available command line options. For more information and sample +output of the tool, see Optimizing layouts with +layoutopt.

        + +

        Usage

        + +

        To run layoutopt against a given list of layout resources:

        + +
        layoutopt <file_or_directory> ...
        + +

        For example:

        + +
        $ layoutopt res/layout-land
        +
        $ layoutopt res/layout/main.xml res/layout-land/main.xml
        + diff --git a/docs/html/tools/help/logcat.jd b/docs/html/tools/help/logcat.jd new file mode 100644 index 000000000000..d504b22c7fde --- /dev/null +++ b/docs/html/tools/help/logcat.jd @@ -0,0 +1,106 @@ +page.title=logcat +parent.title=Tools +parent.link=index.html +@jd:body + +

        The Android logging system provides a mechanism for collecting and viewing system debug + output. Logs from various applications and portions of the system are collected in a series of + circular buffers, which then can be viewed and filtered by the logcat command. You can use + logcat from an ADB shell to view the log messages.

        + +

        This document is a reference to the available command line options. For more information on logcat, see + Reading and Writing Logs. +For more + information on accessing logcat from DDMS, instead of the command line, see the documentation for the + Dalvik Debug Monitor Server. +

        + +

        Syntax

        +
        +[adb] logcat [<option>] ... [<filter-spec>] ...
        +
        + +

        You can run logcat as an adb command or directly in a shell prompt + of your emulator or connected device. To view log output using adb, navigate to your SDK + platform-tools/ directory and execute:

        +
        +$ adb logcat
        +
        + +

        You can create a shell connection to a device and execute:

        +
        +$ adb shell
        +# logcat
        +
        + +

        Options

        +

        The following table describes the command line options of logcat.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        OptionDescription
        -b <buffer>Loads an alternate log buffer for viewing, such as event or + radio. The main buffer is used by default. See Viewing Alternative Log Buffers.
        -cClears (flushes) the entire log and exits.
        -dDumps the log to the screen and exits.
        -f <filename>Writes log message output to <filename>. The default is + stdout.
        -gPrints the size of the specified log buffer and exits.
        -n <count>Sets the maximum number of rotated logs to <count>. The default value + is 4. Requires the -r option.
        -r <kbytes>Rotates the log file every <kbytes> of output. The default value is + 16. Requires the -f option.
        -sSets the default filter spec to silent.
        -v <format>Sets the output format for log messages. The default is brief format. For a + list of supported formats, see Controlling Log Output + Format.
        diff --git a/docs/html/tools/help/mksdcard.jd b/docs/html/tools/help/mksdcard.jd new file mode 100644 index 000000000000..38c435666735 --- /dev/null +++ b/docs/html/tools/help/mksdcard.jd @@ -0,0 +1,55 @@ +page.title=mksdcard +parent.title=Tools +parent.link=index.html +@jd:body + +

        The mksdcard tool lets you quickly create a FAT32 disk image that you can load in the + emulator, to simulate the presence of an SD card in the device. Because you can specify an SD + card while creating an AVD in the AVD Manager, you usually use that feature to create an SD card. + This tool creates an SD card that is not bundled with an AVD, so it is useful for situations + where you need to share a virtual SD card between multiple emulators.

        + +

        Usage

        +
        +mksdcard -l <label> <size> <file>
        +
        + +

        Options

        +

        The following table describes the command-line options of mksdcard

        + + + + + + + + + + + + + + + + + + + + + + + + +
        OptionDescription
        -lA volume label for the disk image to create.
        sizeAn integer that specifies the size (in bytes) of disk image to create. You can also + specify size in kilobytes or megabytes, by appending a "K" or "M" to <size>. For + example, 1048576K, 1024M.
        fileThe path/filename of the disk image to create.
        + +

        Once you have created the disk image file, you can load it in the emulator at startup using + the emulator's -sdcard option. For more information, see Android Emulator.

        + +

        The usage for the -sdcard option is as follows:

        +
        emulator -sdcard <file>
        + +

        Example

        +
        mksdcard -l mySdCard 1024M mySdCardFile.img
        \ No newline at end of file diff --git a/docs/html/tools/help/monkey.jd b/docs/html/tools/help/monkey.jd new file mode 100644 index 000000000000..b6300a70bab4 --- /dev/null +++ b/docs/html/tools/help/monkey.jd @@ -0,0 +1,242 @@ +page.title=UI/Application Exerciser Monkey +parent.title=Tools +parent.link=index.html +@jd:body + +

        The Monkey is a program that runs on your +emulator or device and generates pseudo-random +streams of user events such as clicks, touches, or gestures, as well as a number of system-level +events. You can use the Monkey to stress-test applications that you are developing, in a random +yet repeatable manner.

        + + +

        Overview

        + +

        The Monkey is a command-line tool that that you can run on any emulator +instance or on a device. It sends a pseudo-random stream of +user events into the system, which acts as a stress test on the application software you are +developing.

        + +

        The Monkey includes a number of options, but they break down into four primary +categories:

        + +
          +
        • Basic configuration options, such as setting the number of events to attempt.
        • +
        • Operational constraints, such as restricting the test to a single package.
        • +
        • Event types and frequencies.
        • +
        • Debugging options.
        • +
        + +

        When the Monkey runs, it generates events and sends them to the system. It also watches +the system under test and looks for three conditions, which it treats specially:

        + +
          +
        • If you have constrained the Monkey to run in one or more specific packages, it + watches for attempts to navigate to any other packages, and blocks them.
        • +
        • If your application crashes or receives any sort of unhandled exception, the Monkey + will stop and report the error.
        • +
        • If your application generates an application not responding error, the Monkey + will stop and report the error.
        • +
        + +

        Depending on the verbosity level you have selected, you will also see reports on the progress +of the Monkey and the events being generated.

        + + +

        Basic Use of the Monkey

        + +

        You can launch the Monkey using a command line on your development machine or from a script. +Because the Monkey runs in the emulator/device environment, you must launch it from a shell in +that environment. You can do this by prefacing adb shell to each command, +or by entering the shell and entering Monkey commands directly.

        +

        The basic syntax is:

        + +
        $ adb shell monkey [options] <event-count>
        + +

        With no options specified, the Monkey will launch in a quiet (non-verbose) mode, and will send +events to any (and all) packages installed on your target. Here is a more typical command line, +which will launch your application and send 500 pseudo-random events to it:

        + +
        $ adb shell monkey -p your.package.name -v 500
        + + +

        Command Options Reference

        + +

        The table below lists all options you can include on the Monkey command line.

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        CategoryOptionDescription
        General--helpPrints a simple usage guide.
        -vEach -v on the command line will increment the verbosity level. +Level 0 (the default) provides little information beyond startup notification, test completion, and +final results. +Level 1 provides more details about the test as it runs, such as individual events being sent to +your activities. +Level 2 provides more detailed setup information such as activities selected or not selected for +testing.
        Events-s <seed>Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed +value, it will generate the same sequence of events.
        --throttle <milliseconds>Inserts a fixed delay between events. You can use this option to slow down the Monkey. +If not specified, there is no delay and the events are generated as rapidly as possible.
        --pct-touch <percent>Adjust percentage of touch events. +(Touch events are a down-up event in a single place on the screen.)
        --pct-motion <percent>Adjust percentage of motion events. +(Motion events consist of a down event somewhere on the screen, a series of pseudo-random +movements, and an up event.)
        --pct-trackball <percent>Adjust percentage of trackball events. +(Trackball events consist of one or more random movements, sometimes followed by a click.)
        --pct-nav <percent>Adjust percentage of "basic" navigation events. +(Navigation events consist of up/down/left/right, as input from a directional input device.)
        --pct-majornav <percent>Adjust percentage of "major" navigation events. +(These are navigation events that will typically cause actions within your UI, such as +the center button in a 5-way pad, the back key, or the menu key.)
        --pct-syskeys <percent>Adjust percentage of "system" key events. +(These are keys that are generally reserved for use by the system, such as Home, Back, Start Call, +End Call, or Volume controls.)
        --pct-appswitch <percent>Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a way of maximizing +coverage of all activities within your package.
        --pct-anyevent <percent>Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-used +buttons on the device, and so forth.
        Constraints-p <allowed-package-name>If you specify one or more packages this way, the Monkey will only allow the system +to visit activities within those packages. If your application requires access to activities in +other packages (e.g. to select a contact) you'll need to specify those packages as well. +If you don't specify any packages, the Monkey will allow the system to launch activities +in all packages. To specify multiple packages, use the -p option multiple times — one -p +option per package.
        -c <main-category>If you specify one or more categories this way, the Monkey will only allow the +system to visit activities that are listed with one of the specified categories. +If you don't specify any categories, the Monkey will select activities listed with the category +Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c +option multiple times — one -c option per category.
        Debugging--dbg-no-eventsWhen specified, the Monkey will perform the initial launch into a test activity, but +will not generate any further events. +For best results, combine with -v, one or more package constraints, and a non-zero throttle to keep the Monkey +running for 30 seconds or more. This provides an environment in which you can monitor package +transitions invoked by your application.
        --hprofIf set, this option will generate profiling reports immediately before and after +the Monkey event sequence. +This will generate large (~5Mb) files in data/misc, so use with care. See +Traceview for more information +on trace files.
        --ignore-crashesNormally, the Monkey will stop when the application crashes or experiences any type of +unhandled exception. If you specify this option, the Monkey will continue to send events to +the system, until the count is completed.
        --ignore-timeoutsNormally, the Monkey will stop when the application experiences any type of timeout error such +as a "Application Not Responding" dialog. If you specify this option, the Monkey will continue to +send events to the system, until the count is completed.
        --ignore-security-exceptionsNormally, the Monkey will stop when the application experiences any type of permissions error, +for example if it attempts to launch an activity that requires certain permissions. If you specify +this option, the Monkey will continue to send events to the system, until the count is +completed.
        --kill-process-after-errorNormally, when the Monkey stops due to an error, the application that failed will be left +running. When this option is set, it will signal the system to stop the process in which the error +occurred. +Note, under a normal (successful) completion, the launched process(es) are not stopped, and +the device is simply left in the last state after the final event.
        --monitor-native-crashesWatches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is set, the system will stop.
        --wait-dbgStops the Monkey from executing until a debugger is attached to it.
        + + + + + diff --git a/docs/html/tools/help/monkeyrunner_concepts.jd b/docs/html/tools/help/monkeyrunner_concepts.jd new file mode 100644 index 000000000000..c37e64d64525 --- /dev/null +++ b/docs/html/tools/help/monkeyrunner_concepts.jd @@ -0,0 +1,319 @@ +page.title=monkeyrunner +parent.title=Tools +parent.link=index.html +@jd:body + + +

        + The monkeyrunner tool provides an API for writing programs that control an Android device + or emulator from outside of Android code. With monkeyrunner, you can write a Python program + that installs an Android application or test package, runs it, sends keystrokes to it, + takes screenshots of its user interface, and stores screenshots on the workstation. The + monkeyrunner tool is primarily designed to test applications and devices at the + functional/framework level and for running unit test suites, but you are free to use it for + other purposes. +

        +

        + The monkeyrunner tool is not related to the + UI/Application Exerciser Monkey, + also known as the monkey tool. The monkey tool runs in an + adb shell directly on the + device or emulator and generates pseudo-random streams of user and system events. In comparison, + the monkeyrunner tool controls devices and emulators from a workstation by sending specific + commands and events from an API. +

        +

        + The monkeyrunner tool provides these unique features for Android testing: +

        +
          +
        • + Multiple device control: The monkeyrunner API can apply one or more + test suites across multiple devices or emulators. You can physically attach all the devices + or start up all the emulators (or both) at once, connect to each one in turn + programmatically, and then run one or more tests. You can also start up an emulator + configuration programmatically, run one or more tests, and then shut down the emulator. +
        • +
        • + Functional testing: monkeyrunner can run an automated start-to-finish test of an Android + application. You provide input values with keystrokes or touch events, and view the results + as screenshots. +
        • +
        • + Regression testing - monkeyrunner can test application stability by running an application + and comparing its output screenshots to a set of screenshots that are known to be correct. +
        • +
        • + Extensible automation - Since monkeyrunner is an API toolkit, you can develop an entire + system of Python-based modules and programs for controlling Android devices. Besides using + the monkeyrunner API itself, you can use the standard Python + os and + subprocess + modules to call Android tools such as + Android Debug Bridge. +

          + You can also add your own classes to the monkeyrunner API. This is described + in more detail in the section + Extending monkeyrunner with plugins. +

          +
        • +
        +

        + The monkeyrunner tool uses Jython, a + implementation of Python that uses the Java programming language. Jython allows the + monkeyrunner API to interact easily with the Android framework. With Jython you can + use Python syntax to access the constants, classes, and methods of the API. +

        + +

        A Simple monkeyrunner Program

        +

        + Here is a simple monkeyrunner program that connects to a device, creating a + MonkeyDevice + object. Using the MonkeyDevice object, the program installs an Android application + package, runs one of its activities, and sends key events to the activity. + The program then takes a screenshot of the result, creating a + MonkeyImage object. + From this object, the program writes out a .png file containing the screenshot. +

        +
        +# Imports the monkeyrunner modules used by this program
        +from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
        +
        +# Connects to the current device, returning a MonkeyDevice object
        +device = MonkeyRunner.waitForConnection()
        +
        +# Installs the Android package. Notice that this method returns a boolean, so you can test
        +# to see if the installation worked.
        +device.installPackage('myproject/bin/MyApplication.apk')
        +
        +# sets a variable with the package's internal name
        +package = 'com.example.android.myapplication'
        +
        +# sets a variable with the name of an Activity in the package
        +activity = 'com.example.android.myapplication.MainActivity'
        +
        +# sets the name of the component to start
        +runComponent = package + '/' + activity
        +
        +# Runs the component
        +device.startActivity(component=runComponent)
        +
        +# Presses the Menu button
        +device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
        +
        +# Takes a screenshot
        +result = device.takeSnapshot()
        +
        +# Writes the screenshot to a file
        +result.writeToFile('myproject/shot1.png','png')
        +
        + +

        The monkeyrunner API

        +

        + The monkeyrunner API is contained in three modules in the package + com.android.monkeyrunner: +

        +
          +
        • + MonkeyRunner: + A class of utility methods for monkeyrunner programs. This class provides a method for + connecting monkeyrunner to a device or emulator. It also provides methods for + creating UIs for a monkeyrunner program and for displaying the built-in help. +
        • +
        • + MonkeyDevice: + Represents a device or emulator. This class provides methods for installing and + uninstalling packages, starting an Activity, and sending keyboard or touch events to an + application. You also use this class to run test packages. +
        • +
        • + MonkeyImage: + Represents a screen capture image. This class provides methods for capturing screens, + converting bitmap images to various formats, comparing two MonkeyImage objects, and + writing an image to a file. +
        • +
        +

        + In a Python program, you access each class as a Python module. The monkeyrunner tool + does not import these modules automatically. To import a module, use the + Python from statement: +

        +
        +from com.android.monkeyrunner import <module>
        +
        +

        + where <module> is the class name you want to import. You can import more + than one module in the same from statement by separating the module names with + commas. +

        +

        Running monkeyrunner

        +

        + You can either run monkeyrunner programs from a file, or enter monkeyrunner statements in + an interactive session. You do both by invoking the monkeyrunner command + which is found in the tools/ subdirectory of your SDK directory. + If you provide a filename as an argument, the monkeyrunner command + runs the file's contents as a Python program; otherwise, it starts an interactive session. +

        +

        + The syntax of the monkeyrunner command is +

        +
        +monkeyrunner -plugin <plugin_jar> <program_filename> <program_options>
        +
        +

        +Table 1 explains the flags and arguments. +

        +

        + Table 1. monkeyrunner flags and arguments.

        + + + + + + + + + + + + + + + + + + +
        ArgumentDescription
        + + -plugin <plugin_jar> + + + (Optional) Specifies a .jar file containing a plugin for monkeyrunner. + To learn more about monkeyrunner plugins, see + Extending monkeyrunner with plugins. To specify more than one + file, include the argument multiple times. +
        + + <program_filename> + + + If you provide this argument, the monkeyrunner command runs the contents + of the file as a Python program. If the argument is not provided, the command starts an + interactive session. +
        + <program_options> + + (Optional) Flags and arguments for the program in <program_file>. +
        +

        monkeyrunner Built-in Help

        +

        + You can generate an API reference for monkeyrunner by running: +

        +
        +monkeyrunner help.py <format> <outfile>
        +
        +

        +The arguments are: +

        +
          +
        • + <format> is either text for plain text output + or html for HTML output. +
        • +
        • + <outfile> is a path-qualified name for the output file. +
        • +
        +

        Extending monkeyrunner with Plugins

        +

        + You can extend the monkeyrunner API with classes you write in the Java programming language + and build into one or more .jar files. You can use this feature to extend the + monkeyrunner API with your own classes or to extend the existing classes. You can also use this + feature to initialize the monkeyrunner environment. +

        +

        + To provide a plugin to monkeyrunner, invoke the monkeyrunner command with the + -plugin <plugin_jar> argument described in + table 1. +

        +

        + In your plugin code, you can import and extend the the main monkeyrunner classes + MonkeyDevice, MonkeyImage, and MonkeyRunner in + com.android.monkeyrunner (see The monkeyrunner API). +

        +

        + Note that plugins do not give you access to the Android SDK. You can't import packages + such as com.android.app. This is because monkeyrunner interacts with the + device or emulator below the level of the framework APIs. +

        +

        The plugin startup class

        +

        + The .jar file for a plugin can specify a class that is instantiated before + script processing starts. To specify this class, add the key + MonkeyRunnerStartupRunner to the .jar file's + manifest. The value should be the name of the class to run at startup. The following + snippet shows how you would do this within an ant build script: +

        +
        +<jar jarfile="myplugin" basedir="${build.dir}">
        +<manifest>
        +<attribute name="MonkeyRunnerStartupRunner" value="com.myapp.myplugin"/>
        +</manifest>
        +</jar>
        +
        +
        +
        +

        + To get access to monkeyrunner's runtime environment, the startup class can implement + com.google.common.base.Predicate<PythonInterpreter>. For example, this + class sets up some variables in the default namespace: +

        +
        +package com.android.example;
        +
        +import com.google.common.base.Predicate;
        +import org.python.util.PythonInterpreter;
        +
        +public class Main implements Predicate<PythonInterpreter> {
        +    @Override
        +    public boolean apply(PythonInterpreter anInterpreter) {
        +
        +        /*
        +        * Examples of creating and initializing variables in the monkeyrunner environment's
        +        * namespace. During execution, the monkeyrunner program can refer to the variables "newtest"
        +        * and "use_emulator"
        +        *
        +        */
        +        anInterpreter.set("newtest", "enabled");
        +        anInterpreter.set("use_emulator", 1);
        +
        +        return true;
        +    }
        +}
        +
        diff --git a/docs/html/tools/help/proguard.jd b/docs/html/tools/help/proguard.jd new file mode 100644 index 000000000000..1da94ba60a95 --- /dev/null +++ b/docs/html/tools/help/proguard.jd @@ -0,0 +1,189 @@ +page.title=ProGuard +parent.title=Tools +parent.link=index.html +@jd:body + + + +

        The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and + renaming classes, fields, and methods with semantically obscure names. The result is a smaller + sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your + application harder to reverse engineer, it is important that you use it + when your application utilizes features that are sensitive to security like when you are + Licensing Your Applications.

        + +

        ProGuard is integrated into the Android build system, so you do not have to invoke it + manually. ProGuard runs only when you build your application in release mode, so you do not + have to deal with obfuscated code when you build your application in debug mode. + Having ProGuard run is completely optional, but highly recommended.

        + +

        This document describes how to enable and configure ProGuard as well as use the + retrace tool to decode obfuscated stack traces.

        + +

        Enabling ProGuard

        + +

        When you create an Android project, a proguard.cfg file is automatically + generated in the root directory of the project. This file defines how ProGuard optimizes and + obfuscates your code, so it is very important that you understand how to customize it for your + needs. The default configuration file only covers general cases, so you most likely have to edit + it for your own needs. See the following section about Configuring ProGuard for information on + customizing the ProGuard configuration file.

        + +

        To enable ProGuard so that it runs as part of an Ant or Eclipse build, set the + proguard.config property in the <project_root>/project.properties + file. The path can be an absolute path or a path relative to the project's root.

        +

        If you left the proguard.cfg file in its default location (the project's root directory), +you can specify its location like this:

        +
        +proguard.config=proguard.cfg
        +
        +

        +You can also move the the file to anywhere you want, and specify the absolute path to it: +

        +
        +proguard.config=/path/to/proguard.cfg
        +
        + + +

        When you build your application in release mode, either by running ant release or + by using the Export Wizard in Eclipse, the build system automatically checks to see if + the proguard.config property is set. If it is, ProGuard automatically processes + the application's bytecode before packaging everything into an .apk file. Building in debug mode + does not invoke ProGuard, because it makes debugging more cumbersome.

        + +

        ProGuard outputs the following files after it runs:

        + +
        +
        dump.txt
        +
        Describes the internal structure of all the class files in the .apk file
        + +
        mapping.txt
        +
        Lists the mapping between the original and obfuscated class, method, and field names. + This file is important when you receive a bug report from a release build, because it + translates the obfuscated stack trace back to the original class, method, and member names. + See Decoding Obfuscated Stack Traces for more information.
        + +
        seeds.txt
        +
        Lists the classes and members that are not obfuscated
        + +
        usage.txt
        +
        Lists the code that was stripped from the .apk
        +
      + +

      These files are located in the following directories:

      + +
        +
      • <project_root>/bin/proguard if you are using Ant.
      • + +
      • <project_root>/proguard if you are using Eclipse.
      • +
      + + +

      Caution: Every time you run a build in release mode, these files are + overwritten with the latest files generated by ProGuard. Save a copy of them each time you release your + application in order to de-obfuscate bug reports from your release builds. + For more information on why saving these files is important, see + Debugging considerations for published applications. +

      + +

      Configuring ProGuard

      + +

      For some situations, the default configurations in the proguard.cfg file will + suffice. However, many situations are hard for ProGuard to analyze correctly and it might remove code + that it thinks is not used, but your application actually needs. Some examples include:

      + +
        +
      • a class that is referenced only in the AndroidManifest.xml file
      • + +
      • a method called from JNI
      • + +
      • dynamically referenced fields and methods
      • +
      + +

      The default proguard.cfg file tries to cover general cases, but you might + encounter exceptions such as ClassNotFoundException, which happens when ProGuard + strips away an entire class that your application calls.

      + +

      You can fix errors when ProGuard strips away your code by adding a -keep line in + the proguard.cfg file. For example:

      +
      +-keep public class <MyClass>
      +
      + +

      There are many options and considerations when using the -keep option, so it is + highly recommended that you read the ProGuard + Manual for more information about customizing your configuration file. The Overview of Keep options and + Examples section + are particularly helpful. The Troubleshooting section of the + ProGuard Manual outlines other common problems you might encounter when your code gets stripped + away.

      + +

      Decoding Obfuscated Stack Traces

      + +

      When your obfuscated code outputs a stack trace, the method names are obfuscated, which makes + debugging hard, if not impossible. Fortunately, whenever ProGuard runs, it outputs a + <project_root>/bin/proguard/mapping.txt file, which shows you the original + class, method, and field names mapped to their obfuscated names.

      + +

      The retrace.bat script on Windows or the retrace.sh script on Linux + or Mac OS X can convert an obfuscated stack trace to a readable one. It is located in the + <sdk_root>/tools/proguard/ directory. The syntax for executing the + retrace tool is:

      +
      retrace.bat|retrace.sh [-verbose] mapping.txt [<stacktrace_file>]
      +

      For example:

      + +
      retrace.bat -verbose mapping.txt obfuscated_trace.txt
      + +

      If you do not specify a value for <stacktrace_file>, the retrace tool reads + from standard input.

      + +

      Debugging considerations for published applications

      + +

      Save the mapping.txt file for every release that you publish to your users. + By retaining a copy of the mapping.txt file for each release build, + you ensure that you can debug a problem if a user encounters a bug and submits an obfuscated stack trace. + A project's mapping.txt file is overwritten every time you do a release build, so you must be + careful about saving the versions that you need.

      + +

      For example, say you publish an application and continue developing new features of + the application for a new version. You then do a release build using ProGuard soon after. The + build overwrites the previous mapping.txt file. A user submits a bug report + containing a stack trace from the application that is currently published. You no longer have a way + of debugging the user's stack trace, because the mapping.txt file associated with the version + on the user's device is gone. There are other situations where your mapping.txt file can be overwritten, so + ensure that you save a copy for every release that you anticipate you have to debug.

      + +

      How you save the mapping.txt file is your decision. For example, you can rename them to + include a version or build number, or you can version control them along with your source + code.

      \ No newline at end of file diff --git a/docs/html/tools/help/sqlite3.jd b/docs/html/tools/help/sqlite3.jd new file mode 100644 index 000000000000..9cc7e9831a5b --- /dev/null +++ b/docs/html/tools/help/sqlite3.jd @@ -0,0 +1,59 @@ +page.title=sqlite3 +parent.title=Tools +parent.link=index.html +@jd:body + +

      From a remote shell to your device or from your host machine, you can use the sqlite3 command-line program to manage SQLite databases + created by Android applications. The sqlite3 tool includes many useful commands, + such as .dump to print out the contents of a table and .schema to print + the SQL CREATE statement for an existing table. The tool also gives you the ability to execute + SQLite commands on the fly.

      + +

      To use sqlite3 from a remote shell:

      + +
        +
      1. Enter a remote shell by entering the following command: +
        adb [-d|-e|-s {<serialNumber>}] shell
        +
      2. + +
      3. From a remote shell, start the sqlite3 tool by entering the following command: +
        sqlite3
        + +

        You can also optionally specify a full path to a database that you want to explore. + Emulator/device instances store SQLite3 databases in the directory + /data/data/<package_name>/databases/.

        +
      4. + +
      5. Once you invoke sqlite3, you can issue sqlite3 commands in the + shell. To exit and return to the adb remote shell, enter exit or press + CTRL+D.
      6. +
      + + +

      Here's an example:

      +
      $ adb -s emulator-5554 shell
      +# sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db
      +SQLite version 3.3.12
      +Enter ".help" for instructions
      +.... enter commands, then quit...
      +# sqlite> .exit 
      +
      + +

      To use sqlite3 locally, instead of within a shell, + pull the database file from the device and start {@code sqlite3}:

      + +
        +
      1. Copy a database file from your device to your host machine: +
        +adb pull <database-file-on-device>
        +
        +
      2. + +
      3. Start the sqlite3 tool from the /tools directory, specifying the database + file: +
        +sqlite3 <database-file-on-host>
        +
        +
      4. +
      \ No newline at end of file diff --git a/docs/html/tools/help/traceview.jd b/docs/html/tools/help/traceview.jd new file mode 100644 index 000000000000..6555ac08cc83 --- /dev/null +++ b/docs/html/tools/help/traceview.jd @@ -0,0 +1,16 @@ +page.title=Traceview +parent.title=Tools +parent.link=index.html +@jd:body + +

      Traceview is a graphical viewer for execution logs saved by your application. +Traceview can help you debug your application and profile its performance.

      + +

      To start Traceview, enter the following command from the SDK tools/ directory:

      +
      traceview
      + + +

      For more information on how to use Traceview, see +Profiling with Traceview and dmtracedump +

      + diff --git a/docs/html/tools/help/zipalign.jd b/docs/html/tools/help/zipalign.jd new file mode 100644 index 000000000000..184cdcb6ad22 --- /dev/null +++ b/docs/html/tools/help/zipalign.jd @@ -0,0 +1,67 @@ +page.title=zipalign +parent.title=Tools +parent.link=index.html +@jd:body + +

      zipalign is an archive alignment tool that provides important +optimization to Android application (.apk) files. +The purpose is to ensure that all uncompressed data starts +with a particular alignment relative to the start of the file. Specifically, +it causes all uncompressed data within the .apk, such as images or raw files, +to be aligned on 4-byte boundaries. This +allows all portions to be accessed directly with {@code mmap()} even if they +contain binary data with alignment restrictions. +The benefit is a reduction in the amount of RAM consumed +when running the application.

      + +

      This tool should always be used to align your .apk file before +distributing it to end-users. The Android build tools can handle +this for you. When using Eclipse with the ADT plugin, the Export Wizard +will automatically zipalign your .apk after it signs it with your private key. +The build scripts used +when compiling your application with Ant will also zipalign your .apk, +as long as you have provided the path to your keystore and the key alias in +your project {@code ant.properties} file, so that the build tools +can sign the package first.

      + +

      Caution: zipalign must only be performed +after the .apk file has been signed with your private key. +If you perform zipalign before signing, then the signing procedure will undo +the alignment. Also, do not make alterations to the aligned package. +Alterations to the archive, such as renaming or deleting entries, will +potentially disrupt the alignment of the modified entry and all later +entries. And any files added to an "aligned" archive will not be aligned.

      + +

      The adjustment is made by altering the size of +the "extra" field in the zip Local File Header sections. Existing data +in the "extra" fields may be altered by this process.

      + +

      For more information about how to use zipalign when building your +application, please read Signing +Your Application.

      + + +

      Usage

      + +

      To align {@code infile.apk} and save it as {@code outfile.apk}:

      + +
      zipalign [-f] [-v] <alignment> infile.apk outfile.apk
      + +

      To confirm the alignment of {@code existing.apk}:

      + +
      zipalign -c -v <alignment> existing.apk
      + +

      The {@code <alignment>} is an integer that defines the byte-alignment boundaries. +This must always be 4 (which provides 32-bit alignment) or else it effectively +does nothing.

      + +

      Flags:

      + +
        +
      • {@code -f} : overwrite existing outfile.zip
      • +
      • {@code -v} : verbose output
      • +
      • {@code -c} : confirm the alignment of the given file
      • +
      + + + diff --git a/docs/html/tools/index.jd b/docs/html/tools/index.jd new file mode 100644 index 000000000000..929f849c9392 --- /dev/null +++ b/docs/html/tools/index.jd @@ -0,0 +1,96 @@ +page.title=Developer Tools +@jd:body + + + + +
      +
      +

      The Android Developer Tools (ADT) plugin for Eclipse provides + a professional-grade development environment for building + Android apps. It's a full Java IDE with advanced features to help you build, test, debug, + and package your Android apps.

      +

      Free, open-source, and runs on most major OS platforms.
      To get started, + download the Android SDK.

      +
      +
      + +
      + +
      +

      Full Java IDE

      + +
        +
      • Android-specific refactoring, quick fixes, integrated navigation between Java and Android XML resources.
      • +
      • Enhanced XML editors for Android XML resources
      • +
      • Static analysis tools to catch performance, usability, and correctness problems
      • +
      • Build support for complex projects, command-line support for CI through Ant. Includes ProGuard and app-signing.
      • +
      +
      + +
      +

      Graphical UI Builders

      + +
        +
      • Build rich Android UI with drag and drop. +
      • Vsualize your UI on tablets, phones, and other devices. Switch themes, locales, even plaform versions instantly, without building.
      • +
      • Visual refactoring lets you extracts layout for inclusion, convert layouts, extract styles
      • +
      • Editor support for working with custom UI components
      • +
      +
      + +
      +

      Develop on Hardware Devices

      + +
        +
      • Use any commercial Android hardware device or multiple devices.
      • +
      • Deploy your app to connected devices directy from the IDE
      • +
      • Live, on-device debugging, testing, and profiling
      • +
      +
      + +
      +

      Develop on Virtual Devices

      +
        +
      • Emulate any device. Use custom screen sizes, keyboards, and other hardware components.
      • +
      • Advanced hardware emulation, including camera, sensors, multitouch, telephony.
      • +
      • Develop and test for broadest compatibility at lowest cost.
      • +
      + +
      + +
      + +
      +

      Powerful Debugging

      + +
        +
      • Full Java debugger with on-device debugging and Android-specidic tools
      • +
      • Built-in memory analysis, performance/CPU profiling.
      • +
      • Graphical tools for debugging and optimizing UI, runtime inspecton of UI structure and performance.
      • +
      • Runtime graphical analysis of your app's network bandwidth usage.
      • +
      +
      + +
      + +
      + + +
      +

      Testing

      + +
        +
      • Fully instrumentated, scriptable test environment.
      • +
      • Integrated reports using standard test UI.
      • +
      • Create and run unit tests on hardware devices or emulator.
      • +
      + +

      Native Development

      + +
        +
      • Support for compiling and packaging existing code written in C or C++.
      • +
      • Support for packaging multiple architectures in a single binary, for broad compatibility.
      • +
      +
      + diff --git a/docs/html/tools/other-ide.html b/docs/html/tools/other-ide.html new file mode 100644 index 000000000000..2bfe876570a2 --- /dev/null +++ b/docs/html/tools/other-ide.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

      You should be redirected. Please click here.

      + + \ No newline at end of file diff --git a/docs/html/tools/othertools.html b/docs/html/tools/othertools.html new file mode 100644 index 000000000000..ed45ccdf8103 --- /dev/null +++ b/docs/html/tools/othertools.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

      You should be redirected. Please click here.

      + + \ No newline at end of file diff --git a/docs/html/tools/projects/index.jd b/docs/html/tools/projects/index.jd new file mode 100644 index 000000000000..6a49ac915d22 --- /dev/null +++ b/docs/html/tools/projects/index.jd @@ -0,0 +1,446 @@ +page.title=Managing Projects +@jd:body + + + +

      Projects act as containers for storing things such as code and resource files. The SDK tools + expect your projects to follow a specific structure so it can compile and package your + application correctly, so it is highly recommended that you create them with Eclipse and ADT or + with the android tool on the command line. There are three types of projects, and + they all share the same general structure but differ in function:

      + +
      +
      Android Projects
      + +
      An Android project is the container for your application's source code, resource files, and + files such as the Ant build and Android Manifest file. An application project is the main type + of project and the contents are eventually built into an .apk file that you install on a + device.
      + +
      Test Projects
      + +
      These projects contain code to test your application projects and are built into + applications that run on a device.
      + +
      Library Projects
      + +
      These projects contain shareable Android source code and resources that you can reference + in Android projects. This is useful when you have common code that you want to reuse. + Library projects cannot be installed onto a device, however, they are + pulled into the .apk file at build time.
      +
      + +

      When you use the Android development tools to create a new project, the essential files and + folders will be created for you. There are only a handful of files and folders generated for you, + and some of them depend on whether you use the Eclipse plugin or the {@code android} tool to + generate your project. As your application grows in complexity, you might require new kinds of + resources, directories, and files.

      + +

      Android Projects

      + +

      Android projects are the projects that eventually get built into an .apk file that you install + onto a device. They contain things such as application source code and resource files. + Some are generated for you by default, while others should be created if + required. The following directories and files comprise an Android project:

      + +
      +
      src/
      + +
      Contains your stub Activity file, which is stored at + src/your/package/namespace/ActivityName.java. All other source code + files (such as .java or .aidl files) go here as well.
      + +
      bin
      + +
      Output directory of the build. This is where you can find the final .apk file and other + compiled resources.
      + +
      jni
      + +
      Contains native code sources developed using the Android NDK. For more information, see the + Android NDK documentation.
      + +
      gen/
      + +
      Contains the Java files generated by ADT, such as your R.java file and + interfaces created from AIDL files.
      + +
      assets/
      + +
      This is empty. You can use it to store raw asset files. Files that you save here are + compiled into an .apk file as-is, and the original filename is preserved. You can navigate this + directory in the same way as a typical file system using URIs and read files as a stream of + bytes using the the {@link android.content.res.AssetManager}. For example, this is a good + location for textures and game data.
      + +
      res/
      + +
      + Contains application resources, such as drawable files, layout files, and string values. See + Application Resources for more + information. + +
      +
      anim/
      + +
      For XML files that are compiled into animation objects. See the Animation resource + type.
      + +
      color/
      + +
      For XML files that describe colors. See the Color Values resource + type.
      + +
      drawable/
      + +
      For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML files that describe + Drawable shapes or a Drawable objects that contain multiple states (normal, pressed, or + focused). See the Drawable resource type.
      + +
      layout/
      + +
      XML files that are compiled into screen layouts (or part of a screen). See the Layout resource type.
      + +
      menu/
      + +
      For XML files that define application menus. + See the Menus + resource type.
      + +
      raw/
      + +
      For arbitrary raw asset files. Saving asset files here instead of in the + assets/ directory only differs in the way that you access them. These files + are processed by aapt and must be referenced from the application using a resource + identifier in the {@code R} class. For example, this is a good place for media, such as MP3 + or Ogg files.
      + +
      values/
      + +
      For XML files that are compiled into many kinds of resource. Unlike other resources in + the res/ directory, resources written to XML files in this folder are not + referenced by the file name. Instead, the XML element type controls how the resources is + defined within them are placed into the {@code R} class.
      + +
      xml/
      + +
      For miscellaneous XML files that configure application components. For example, an XML + file that defines a {@link android.preference.PreferenceScreen}, {@link + android.appwidget.AppWidgetProviderInfo}, or Searchability + Metadata. See Application Resources + for more information about configuring these application components.
      +
      +
      + +
      libs/
      + +
      Contains private libraries.
      + +
      AndroidManifest.xml
      + +
      The control file that describes the nature of the application and each of its components. + For instance, it describes: certain qualities about the activities, services, intent receivers, + and content providers; what permissions are requested; what external libraries are needed; what + device features are required, what API Levels are supported or required; and others. See the + AndroidManifest.xml + documentation for more information
      + +
      project.properties
      + +
      This file contains project settings, such as the build target. This file is integral to + the project, so maintain it in a source revision control system. To edit project + properties in Eclipse, right-click the project folder and select + Properties.
      + +
      local.properties
      + +
      Customizable computer-specific properties for the build system. If you use Ant to build + the project, this contains the path to the SDK installation. Because the content of the file + is specific to the local installation of the SDK, the local.properties should not +be maintained in a source revision control system. If you use Eclipse, this file is not +used.
      + +
      ant.properties
      + +
      Customizable properties for the build system. You can edit this file to override default + build settings used by Ant and also provide the location of your keystore and key alias so that + the build tools can sign your application when building in release mode. This file is integral + to the project, so maintain it in a source revision control system. If you use Eclipse, this + file is not used.
      + +
      build.xml
      + +
      The Ant build file for your project. This is only applicable for projects that + you build with Ant.
      + +
      + +

      Library Projects

      + + + +

      An Android library project is a development project that holds shared Android + source code and resources. Other Android application projects can reference the library project + and, at build time, include its compiled sources in their .apk files. Multiple + application projects can reference the same library project and any single application project + can reference multiple library projects.

      + +

      Note: You need SDK Tools r14 or newer to use the new library + project feature that generates each library project into its own JAR file. + You can download the tools and platforms using the + Android SDK Manager, as described in + Exploring the SDK.

      + +

      If you have source code and resources that are common to multiple Android projects, you + can move them to a library project so that it is easier to maintain across applications and + versions. Here are some common scenarios in which you could make use of library projects:

      + +
        +
      • If you are developing multiple related applications that use some of the same components, + you move the redundant components out of their respective application projects and create a + single, reuseable set of the same components in a library project.
      • + +
      • If you are creating an application that exists in both free and paid versions. You move + the part of the application that is common to both versions into a library project. The two + dependent projects, with their different package names, will reference the library project + and provide only the difference between the two application versions.
      • +
      + +

      Structurally, a library project is similar to a standard Android application project. For + example, it includes a manifest file at the project root, as well as src/, + res/ and similar directories. The project can contain the same types of source + code and resources as a standard Android project, stored in the same way. For example, source + code in the library project can access its own resources through its R class.

      + +

      However, a library project differs from an standard Android application project in that you + cannot compile it directly to its own .apk and run it on an Android device. + Similarly, you cannot export the library project to a self-contained JAR file, as you would do + for a true library. Instead, you must compile the library indirectly, by referencing the + library in the dependent application and building that application.

      + +

      When you build an application that depends on a library project, the SDK tools compile the + library into a temporary JAR file and uses it in the main project, then uses the + result to generate the .apk. In cases where a resource ID is defined in both the + application and the library, the tools ensure that the resource declared in the application gets + priority and that the resource in the library project is not compiled into the application + .apk. This gives your application the flexibility to either use or redefine any + resource behaviors or values that are defined in any library.

      + +

      To organize your code further, your application can add references to multiple library + projects, then specify the relative priority of the resources in each library. This lets you + build up the resources actually used in your application in a cumulative manner. When two + libraries referenced from an application define the same resource ID, the tools select the + resource from the library with higher priority and discard the other.

      + +

      Once you have added references to library projects to your Android project, + you can set their relative priority. At build time, the + libraries are merged with the application one at a time, starting from the lowest priority to + the highest.

      + +

      Library projects can reference other library projects and can import an external library + (JAR) in the normal way.

      + +

      Development considerations

      + +

      As you develop your library project and dependent applications, keep the points listed below + in mind:

      + +
        +
      • Resource conflicts

        +

        Since the tools merge the resources of a library project with those of a dependent application + project, a given resource ID might be defined in both projects. In this case, the tools select + the resource from the application, or the library with highest priority, and discard the other + resource. As you develop your applications, be aware that common resource IDs are likely to be + defined in more than one project and will be merged, with the resource from the application or + highest-priority library taking precedence.

        +
      • + +
      • Use prefixes to avoid resource conflicts

        + +

        To avoid resource conflicts for common resource IDs, consider using a prefix or other + consistent naming scheme that is unique to the project (or is unique across all projects).

      • + +
      • You cannot export a library project to a JAR file

        + +

        A library cannot be distributed as a binary file (such as a JAR file). This will +be added in a future + version of the SDK Tools.

      • + +
      • A library project can include a JAR library

        + +

        You can develop a library project that itself includes a JAR library, however you need to + manually edit the dependent application project's build path and add a path to the JAR file.

      • + +
      • A library project can depend on an external JAR library

        + +

        You can develop a library project that depends on an external library (for example, the Maps + external library). In this case, the dependent application must build against a target that + includes the external library (for example, the Google APIs Add-On). Note also that both the + library project and the dependent application must declare the external library in their manifest + files, in a <uses-library> + element.

      • + +
      • Library projects cannot include raw assets

        + +

        The tools do not support the use of raw asset files (saved in the assets/ directory) + in a library project. Any asset resources + used by an application must be stored in the assets/ directory of the application + project itself. However, resource files saved in the + res/ directory are supported.

      • + +
      • Platform version must be lower than or equal to the Android project

        + +

        A library is compiled as part of the dependent application project, so the API used in the + library project must be compatible with the version of the Android library used to compile the + application project. In general, the library project should use an API level that is the same as — or lower + than — that used by the application. If the library project uses an API level that is + higher than that of the application, the application project will not compile. It is + perfectly acceptable to have a library that uses the Android 1.5 API (API level 3) and that is + used in an Android 1.6 (API level 4) or Android 2.1 (API level 7) project, for instance.

      • + +
      • No restriction on library package names

        + +

        There is no requirement for the package name of a library to be the same as that of + applications that use it.

      • + +
      • Each library project creates its own R class

        + +

        When you build the dependent application project, library projects are compiled and + merged with the application project. Each library has its own R class, named according + to the library's package name. The R class generated from main + project and the library project is created in all the packages that are needed including the main + project's package and the libraries' packages.

      • + +
      • Library project storage location

        + +

        There are no specific requirements on where you should store a library project, relative to a + dependent application project, as long as the application project can reference the library + project by a relative link. What is important is that the main + project can reference the library project through a relative link.

      • +
      + +

      Test Projects

      + +

      Test projects contain Android applications that you write using the + Testing and + Instrumentation framework. The framework is an extension of the JUnit test framework and adds + access to Android system objects. The file structure of a test project is the same as an + Android project.

      + +
      +
      src/
      + +
      Includes your test source files. Test projects do not require an Activity .java + file, but can include one.
      + +
      gen/
      + +
      This contains the Java files generated by ADT, such as your R.java file and + interfaces created from AIDL files.
      + +
      assets/
      + +
      This is empty. You can use it to store raw asset files.
      + +
      res/
      + +
      A folder for your application resources, such as drawable files, layout files, string + values, etc. See Application + Resources.
      + +
      AndroidManifest.xml
      + +
      The Android Manifest for your project. See The AndroidManifest.xml File. Test + Projects have a special + <instrumentation> + element that connects the test project with the application project.
      + +
      project.properties
      + +
      This file contains project settings, such as the build target and links to the project being +tested. This file is integral to the project, so maintain it in a source +revision control system. To edit project properties in Eclipse, right-click the project folder +and select Properties.
      + +
      local.properties
      + +
      Customizable computer-specific properties for the build system. If you use Ant to build + the project, this contains the path to the SDK installation. Because the content of the file + is specific to the local installation of the SDK, it should not be maintained in a Source + Revision Control system. If you use Eclipse, this file is not used.
      + +
      ant.properties
      + +
      Customizable properties for the build system. You can edit this file to override default + build settings used by Ant and provide the location to your keystore and key alias, so that the + build tools can sign your application when building in release mode. This file is integral to + the project, so maintain it in a source revision control system. + If you use Eclipse, this file is not used.
      + +
      build.xml
      + +
      The Ant build file for your project. This is only applicable for projects that + you build with Ant.
      +
      + +

      For more information, see the Testing section.

      + + +

      Testing a Library Project

      + +

      There are two recommended ways of setting up testing on code and resources in a library + project:

      + +
        +
      • You can set up a test + project that instruments an application project that depends on the library project. You + can then add tests to the project for library-specific features.
      • + +
      • You can set up a standard application project that depends on the library and put + the instrumentation in that project. This lets you create a self-contained project that + contains both the tests/instrumentations and the code to test.
      • +
      diff --git a/docs/html/tools/projects/projects-cmdline.jd b/docs/html/tools/projects/projects-cmdline.jd new file mode 100644 index 000000000000..29d0e57acac9 --- /dev/null +++ b/docs/html/tools/projects/projects-cmdline.jd @@ -0,0 +1,295 @@ +page.title=Managing Projects from the Command Line +parent.title=Managing Projects +parent.link=index.html +@jd:body + + + +

      The android tool provides you with commands to create all three types of + projects. An Android project contains all of the files and resources that are needed to build a + project into an .apk file for installation. + +

        +
      • An Android project contains all of the files and resources that are needed to build a project into + an .apk file for installation. You need to create an Android project for any application that you + want to eventually install on a device.
      • + +
      • You can also designate an Android project as a library project, which allows it to be shared + with other projects that depend on it. Once an Android project is designated as a library + project, it cannot be installed onto a device.
      • + +
      • Test projects extend JUnit test functionality to include Android specific functionality. For + more information on creating a test project, see Testing from other IDEs.
      • +
      + + +

      Creating an Android Project

      + +

      To create an Android project, you must use the android tool. When you create a + new project with android, it will generate a project directory with some default + application files, stub files, configuration files and a build file.

      + +

      To create a new Android project, open a command-line, navigate to the tools/ + directory of your SDK and run:

      +
      +android create project \
      +--target <target_ID> \
      +--name <your_project_name> \
      +--path path/to/your/project \
      +--activity <your_activity_name> \
      +--package <your_package_namespace>
      +
      + +
        +
      • target is the "build target" for your application. It corresponds to an + Android platform library (including any add-ons, such as Google APIs) that you would like to + build your project against. To see a list of available targets and their corresponding IDs, + execute: android list targets.
      • + +
      • name is the name for your project. This is optional. If provided, this name + will be used for your .apk filename when you build your application.
      • + +
      • path is the location of your project directory. If the directory does not + exist, it will be created for you.
      • + +
      • activity is the name for your default {@link android.app.Activity} class. This + class file will be created for you inside + <path_to_your_project>/src/<your_package_namespace_path>/ + . This will also be used for your .apk filename unless you provide a name.
      • + +
      • package is the package namespace for your project, following the same rules as + for packages in the Java programming language.
      • +
      + +

      Here's an example:

      +
      +android create project \
      +--target 1 \
      +--name MyAndroidApp \
      +--path ./MyAndroidAppProject \
      +--activity MyAndroidAppActivity \
      +--package com.example.myandroid
      +
      + +

      Once you've created your project, you're ready to begin development. You can move your project + folder wherever you want for development, but keep in mind that you must use the Android Debug Bridge (adb) — located in the + SDK platform-tools/ directory — to send your application to the emulator (discussed + later). So you need access between your project solution and the platform-tools/ folder.

      + +

      Tip: Add the platform-tools/ as well as the tools/ directory + to your PATH environment variable.

      + +

      Caution: You should refrain from moving the location of the + SDK directory, because this will break the SDK location property located in local.properties. + If you need to update the SDK location, use the android update project command. + See Updating a Project for more information.

      + +

      Updating a Project

      + +

      If you're upgrading a project from an older version of the Android SDK or want to create a new + project from existing code, use the android update project command to update the + project to the new development environment. You can also use this command to revise the build + target of an existing project (with the --target option) and the project name (with + the --name option). The android tool will generate any files and + folders (listed in the previous section) that are either missing or need to be updated, as needed + for the Android project.

      + +

      To update an existing Android project, open a command-line and navigate to the + tools/ directory of your SDK. Now run:

      +
      +android update project --name <project_name> --target <target_ID>
      +--path <path_to_your_project>
      +
      + +
        +
      • target is the "build target" for your application. It corresponds to an + Android platform library (including any add-ons, such as Google APIs) that you would like to + build your project against. To see a list of available targets and their corresponding IDs, + execute: android list targets.
      • + +
      • path is the location of your project directory.
      • + +
      • name is the name for the project. This is optional—if you're not + changing the project name, you don't need this.
      • +
      + +

      Here's an example:

      +
      +android update project --name MyApp --target 2 --path ./MyAppProject
      +
      + +

      Setting up a Library Project

      + +

      A library project is a standard Android project, so you can create a new one in the same way + as you would a new application project. Specifically, you can use the android tool + to generate a new library project with all of the necessary files and folders.

      + +

      To create a new library project, navigate to the <sdk>/tools/ directory and + use this command:

      +
      +android create lib-project --name <your_project_name> \
      +--target <target_ID> \
      +--path path/to/your/project \
      +--package <your_library_package_namespace>
      +
      + +

      The create lib-project command creates a standard project structure that includes + preset property that indicates to the build system that the project is a library. It does this by + adding this line to the project's project.properties file:

      +
      +android.library=true
      +
      + +

      Once the command completes, the library project is created and you can begin moving source + code and resources into it, as described in the sections below.

      + +

      If you want to convert an existing application project to a library project, so that other + applications can use it, you can do so by adding a the android.library=true property + to the application's project.properties file.

      + +

      Creating the manifest file

      + +

      A library project's manifest file must declare all of the shared components that it includes, + just as would a standard Android application. For more information, see the documentation for + AndroidManifest.xml.

      + +

      For example, the TicTacToeLib example library + project declares the Activity GameActivity:

      +
      +<manifest>
      +  ...
      +  <application>
      +    ...
      +    <activity android:name="GameActivity" />
      +    ...
      +  </application>
      +</manifest>
      +
      + +

      Updating a library project

      + +

      If you want to update the build properties (build target, location) of the library project, + use this command:

      +
      +android update lib-project \
      +--target <target_ID> \
      +--path path/to/your/project
      +
      + +

      Referencing a Library Project

      + +

      If you are developing an application and want to include the shared code or resources from a + library project, you can do so easily by adding a reference to the library project in the + application project's build properties.

      + +

      To add a reference to a library project, navigate to the <sdk>/tools/ + directory and use this command:

      +
      +android update project \
      +--target <target_ID> \
      +--path path/to/your/project
      +--library path/to/library_projectA
      +
      + +

      This command updates the application project's build properties to include a reference to the + library project. Specifically, it adds an android.library.reference.n + property to the project's project.properties file. For example:

      +
      +android.library.reference.1=path/to/library_projectA
      +
      + +

      If you are adding references to multiple libraries, note that you can set their relative + priority (and merge order) by manually editing the project.properties file and + adjusting the each reference's .n index as appropriate. For example, assume + these references:

      +
      +android.library.reference.1=path/to/library_projectA
      +android.library.reference.2=path/to/library_projectB
      +android.library.reference.3=path/to/library_projectC
      +
      + +

      You can reorder the references to give highest priority to library_projectC in + this way:

      +
      +android.library.reference.2=path/to/library_projectA
      +android.library.reference.3=path/to/library_projectB
      +android.library.reference.1=path/to/library_projectC
      +
      + +

      Note that the .n index in the references must begin at "1" and increase + uniformly without "holes". References appearing in the index after a hole are ignored.

      + +

      At build time, the libraries are merged with the application one at a time, starting from the + lowest priority to the highest. Note that a library cannot itself reference another library and + that, at build time, libraries are not merged with each other before being merged with the + application.

      + +

      Declaring library components in the manifest file

      + +

      In the manifest file of the application project, you must add declarations of all components + that the application will use that are imported from a library project. For example, you must + declare any <activity>, <service>, + <receiver>, <provider>, and so on, as well as + <permission>, <uses-library>, and similar elements.

      + +

      Declarations should reference the library components by their fully-qualified package names, + where appropriate.

      + +

      For example, the TicTacToeMain example + application declares the library Activity GameActivity like this:

      +
      +<manifest>
      +  ...
      +  <application>
      +    ...
      +    <activity android:name="com.example.android.tictactoe.library.GameActivity" />
      +    ...
      +  </application>
      +</manifest>
      +
      + +

      For more information about the manifest file, see the documentation for + AndroidManifest.xml.

      + +

      Building a dependent application

      + +

      To build an application project that depends on one or more library projects, you can use the + standard Ant build commands and compile modes, as described in Building and Running. The tools +compile and merge all libraries referenced by the application as part of + compiling the dependent application project. No additional commands or steps are necessary.

      + diff --git a/docs/html/tools/projects/projects-eclipse.jd b/docs/html/tools/projects/projects-eclipse.jd new file mode 100644 index 000000000000..f1972bc19bc3 --- /dev/null +++ b/docs/html/tools/projects/projects-eclipse.jd @@ -0,0 +1,237 @@ +page.title=Managing Projects from Eclipse with ADT +parent.title=Managing Projects +parent.link=index.html +@jd:body + + + +

      Eclipse and the ADT plugin provide GUIs and wizards to create all three types of projects + (Android project, Library project, and Test project): + +

        +
      • An Android project contains all of the files and resources that are needed to build a project into + an .apk file for installation. You need to create an Android project for any application that you + want to eventually install on a device.
      • + +
      • You can also designate an Android project as a library project, which allows it to be shared + with other projects that depend on it. Once an Android project is designated as a library + project, it cannot be installed onto a device.
      • + +
      • Test projects extend JUnit test functionality to include Android specific functionality. For + more information on creating a test project, see Testing from Eclipse with ADT.
      • +
      + +

      Creating an Android Project

      + +

      The ADT plugin provides a New Project Wizard that you can use to quickly create a new Android + project (or a project from existing code). To create a new project:

      + +
        +
      1. Select File > New > Project.
      2. + +
      3. Select Android > Android Project, and click + Next.
      4. + +
      5. Select the contents for the project: + +
          +
        • Enter a Project Name. This will be the name of the folder where your project + is created.
        • + +
        • Under Contents, select Create new project in workspace. Select your + project workspace location.
        • + +
        • Under Target, select an Android target to be used as the project's Build Target. The + Build Target specifies which Android platform you'd like your application built against. + +

          Select the lowest platform with which your application is compatible.

          + +

          Note: You can change your the Build Target for your + project at any time: Right-click the project in the Package Explorer, select + Properties, select Android and then check the desired + Project Target.

          +
        • + +
        • Under Properties, fill in all necessary fields. + +
            +
          • Enter an Application name. This is the human-readable title for your + application — the name that will appear on the Android device.
          • + +
          • Enter a Package name. This is the package namespace (following the same + rules as for packages in the Java programming language) where all your source code will + reside.
          • + +
          • Select Create Activity (optional, of course, but common) and enter a name + for your main Activity class.
          • + +
          • Enter a Min SDK Version. This is an integer that indicates the minimum API + Level required to properly run your application. Entering this here automatically sets + the minSdkVersion attribute in the <uses-sdk> of your + Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level + listed for the Build Target you selected in the Target tab.
          • +
          +
        • +
        +
      6. + +
      7. Click Finish.
      8. +
      + +

      Tip: You can also start the New Project Wizard from the + New icon in the toolbar.

      + +

      Setting up a Library Project

      + +

      A library project is a standard Android project, so you can create a new one in the same way + as you would a new application project.

      + +

      When you are creating the library project, you can select any application name, package, and + set other fields as needed, as shown in figure 1.

      + +

      Next, set the project's properties to indicate that it is a library project:

      + +
        +
      1. In the Package Explorer, right-click the library project and select + Properties.
      2. + +
      3. In the Properties window, select the "Android" properties group at left + and locate the Library properties at right.
      4. + +
      5. Select the "is Library" checkbox and click Apply.
      6. + +
      7. Click OK to close the Properties window.
      8. +
      + +

      The new project is now marked as a library project. You can begin moving source code and + resources into it, as described in the sections below.

      + +

      You can also convert an existing application project into a library. To do so, simply open the + Properties for the project and select the "is Library" checkbox. Other application projects can + now reference the existing project as a library project.

      + + + +

      Figure 1. Marking a project as an + Android library project.

      + +

      Creating the manifest file

      + +

      A library project's manifest file must declare all of the shared components that it includes, + just as would a standard Android application. For more information, see the documentation for + AndroidManifest.xml.

      + +

      For example, the TicTacToeLib example library + project declares the Activity GameActivity:

      +
      +<manifest>
      +  ...
      +  <application>
      +    ...
      +    <activity android:name="GameActivity" />
      +    ...
      +  </application>
      +</manifest>
      +
      + +

      Referencing a library project

      + +

      If you are developing an application and want to include the shared code or resources from a + library project, you can do so easily by adding a reference to the library project in the + application project's Properties.

      + +

      To add a reference to a library project, follow these steps:

      + +
        +
      1. In the Package Explorer, right-click the dependent project and select + Properties.
      2. + +
      3. In the Properties window, select the "Android" properties group at left + and locate the Library properties at right.
      4. + +
      5. Click Add to open the Project Selection dialog.
      6. + +
      7. From the list of available library projects, select a project and click + OK.
      8. + +
      9. When the dialog closes, click Apply in the Properties + window.
      10. + +
      11. Click OK to close the Properties window.
      12. +
      + +

      As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents + of the library project.

      + +

      Figure 2 shows the Properties dialog that lets you add library references and move + them up and down in priority.

      + +

      Figure 2. Adding a reference to a + library project in the properties of an application project.

      + +

      If you are adding references to multiple libraries, note that you can set their relative + priority (and merge order) by selecting a library and using the Up and + Down controls. The tools merge the referenced libraries with your application + starting from lowest priority (bottom of the list) to highest (top of the list). If more than one + library defines the same resource ID, the tools select the resource from the library with higher + priority. The application itself has highest priority and its resources are always used in + preference to identical resource IDs defined in libraries.

      + +

      Declaring library components in the manifest file

      + +

      In the manifest file of the application project, you must add declarations of all components + that the application will use that are imported from a library project. For example, you must + declare any <activity>, <service>, + <receiver>, <provider>, and so on, as well as + <permission>, <uses-library>, and similar elements.

      + +

      Declarations should reference the library components by their fully-qualified package names, + where appropriate.

      + +

      For example, the TicTacToeMain example + application declares the library Activity GameActivity like this:

      +
      +<manifest>
      +  ...
      +  <application>
      +    ...
      +    <activity android:name="com.example.android.tictactoe.library.GameActivity" />
      +    ...
      +  </application>
      +</manifest>
      +
      + +

      For more information about the manifest file, see the documentation for AndroidManifest.xml.

      + + + + + + + diff --git a/docs/html/tools/publishing/app-signing.jd b/docs/html/tools/publishing/app-signing.jd new file mode 100644 index 000000000000..ac45242516b5 --- /dev/null +++ b/docs/html/tools/publishing/app-signing.jd @@ -0,0 +1,618 @@ +page.title=Signing Your Applications +@jd:body + +
      +
      + +

      Quickview

      + +
        +
      • All Android apps must be signed
      • +
      • You can sign with a self-signed key
      • +
      • How you sign your apps is critical — read this document carefully
      • +
      • Determine your signing strategy early in the development process
      • +
      + +

      In this document

      + +
        +
      1. Signing Process
      2. +
      3. Signing Strategies
      4. +
      5. Basic Setup for Signing
      6. +
      7. Signing in Debug Mode
      8. +
      9. Signing Release Mode +
          +
        1. Obtain a suitable private key
        2. +
        3. Compile the application in release mode
        4. +
        5. Sign your application with your private key
        6. +
        7. Align the final APK package
        8. +
        9. Compile and sign with Eclipse ADT
        10. +
        +
      10. +
      11. Securing Your Private Key
      12. + +
      + +

      See also

      + +
        +
      1. Versioning Your Applications
      2. +
      3. Preparing to Publish
      4. +
      + +
      +
      + +

      The Android system requires that all installed applications be digitally signed with a +certificate whose private key is held by the application's developer. The Android system uses the +certificate as a means of identifying the author of an application and establishing trust +relationships between applications. The certificate is not used to control which applications the +user can install. The certificate does not need to be signed by a certificate authority: it is +perfectly allowable, and typical, for Android applications to use self-signed certificates.

      + +

      The important points to understand about signing Android applications are:

      + +
        +
      • All applications must be signed. The system will not install an application +on an emulator or a device if it is not signed.
      • +
      • To test and debug your application, the build tools sign your application with a special debug + key that is created by the Android SDK build tools.
      • +
      • When you are ready to release your application for end-users, you must sign it with a suitable + private key. You cannot publish an application that is signed with the debug key generated + by the SDK tools.
      • +
      • You can use self-signed certificates to sign your applications. No certificate authority is + needed.
      • +
      • The system tests a signer certificate's expiration date only at install time. If an +application's signer certificate expires after the application is installed, the application +will continue to function normally.
      • +
      • You can use standard tools — Keytool and Jarsigner — to generate keys and +sign your application {@code .apk} files.
      • +
      • After you sign your application for release, we recommend that you use the + zipalign tool to optimize the final APK package.
      • +
      + +

      The Android system will not install or run an application that is not signed appropriately. This +applies wherever the Android system is run, whether on an actual device or on the emulator. +For this reason, you must set up signing for your application before you can +run it or debug it on an emulator or device.

      + +

      Signing Process

      + +

      The Android build process signs your application differently depending on which build mode you +use to build your application. There are two build modes: debug mode and release +mode. You use debug mode when you are developing and testing your application. You use +release mode when you want to build a release version of your application that you can +distribute directly to users or publish on an application marketplace such as Google Play.

      + +

      When you build in debug mode the Android SDK build tools use the Keytool utility +(included in the JDK) to create a debug key. Because the SDK build tools created the debug key, +they know the debug key's alias and password. Each time you compile your application in debug mode, +the build tools use the debug key along with the Jarsigner utility (also included in the JDK) to +sign your application's .apk file. Because the alias and password are known to the SDK +build tools, the tools don't need to prompt you for the debug key's alias and password each time +you compile.

      + +

      When you build in release mode you use your own private key to sign your application. If +you don't have a private key, you can use the Keytool utility to create one for you. When you +compile your application in release mode, the build tools use your private key along with the +Jarsigner utility to sign your application's .apk file. Because the certificate and +private key you use are your own, you will have to provide the password for the keystore and key +alias.

      + +

      The debug signing process happens automatically when you run or debug your application using +Eclipse with the ADT plugin. Debug signing also happens automatically when you use the Ant build +script with the debug option. You can automate the release signing process by using the +Eclipse Export Wizard or by modifying the Ant build script and building with the +release option.

      + +

      Signing Strategies

      + +

      Some aspects of application signing may affect how you approach the development +of your application, especially if you are planning to release multiple +applications.

      + +

      In general, the recommended strategy for all developers is to sign +all of your applications with the same certificate, throughout the expected +lifespan of your applications. There are several reasons why you should do so:

      + +
        +
      • Application upgrade – As you release updates to your application, you +will want to continue to sign the updates with the same certificate or set of +certificates, if you want users to upgrade seamlessly to the new version. When +the system is installing an update to an application, it compares the +certificate(s) in the new version with those in the existing version. If the +certificates match exactly, including both the certificate data and order, then +the system allows the update. If you sign the new version without using matching +certificates, you will also need to assign a different package name to the +application — in this case, the user installs the new version as a +completely new application.
      • + +
      • Application modularity – The Android system allows applications that +are signed by the same certificate to run in the same process, if the +applications so requests, so that the system treats them as a single application. +In this way you can deploy your application in modules, and users can update +each of the modules independently if needed.
      • + +
      • Code/data sharing through permissions – The Android system provides +signature-based permissions enforcement, so that an application can expose +functionality to another application that is signed with a specified +certificate. By signing multiple applications with the same certificate and +using signature-based permissions checks, your applications can share code and +data in a secure manner.
      • + +
      + +

      Another important consideration in determining your signing strategy is +how to set the validity period of the key that you will use to sign your +applications.

      + +
        +
      • If you plan to support upgrades for a single application, you should ensure +that your key has a validity period that exceeds the expected lifespan of +that application. A validity period of 25 years or more is recommended. +When your key's validity period expires, users will no longer be +able to seamlessly upgrade to new versions of your application.
      • + +
      • If you will sign multiple distinct applications with the same key, +you should ensure that your key's validity period exceeds the expected +lifespan of all versions of all of the applications, including +dependent applications that may be added to the suite in the future.
      • + +
      • If you plan to publish your application(s) on Google Play, the +key you use to sign the application(s) must have a validity period +ending after 22 October 2033. Google Play enforces this requirement +to ensure that users can seamlessly upgrade applications when +new versions are available.
      • +
      + +

      As you design your application, keep these points in mind and make sure to +use a suitable certificate to sign your applications.

      + +

      Basic Setup for Signing

      + +

      Before you begin, make sure that the Keytool utility and Jarsigner utility are available to +the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell +the SDK build tools how to find these utilities by setting your JAVA_HOME environment +variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and +Jarsigner to your PATH variable.

      + +

      If you are developing on a version of Linux that originally came with GNU Compiler for +Java, make sure that the system is using the JDK version of Keytool, rather than the gcj +version. If Keytool is already in your PATH, it might be pointing to a symlink at +/usr/bin/keytool. In this case, check the symlink target to be sure it points +to the Keytool in the JDK.

      + +

      Signing in Debug Mode

      + +

      The Android build tools provide a debug signing mode that makes it easier for you +to develop and debug your application, while still meeting the Android system +requirement for signing your APK. +When using debug mode to build your app, the SDK tools invoke Keytool to automatically create +a debug keystore and key. This debug key is then used to automatically sign the APK, so +you do not need to sign the package with your own key.

      + +

      The SDK tools create the debug keystore/key with predetermined names/passwords:

      +
        +
      • Keystore name: "debug.keystore"
      • +
      • Keystore password: "android"
      • +
      • Key alias: "androiddebugkey"
      • +
      • Key password: "android"
      • +
      • CN: "CN=Android Debug,O=Android,C=US"
      • +
      + +

      If necessary, you can change the location/name of the debug keystore/key or +supply a custom debug keystore/key to use. However, any custom debug +keystore/key must use the same keystore/key names and passwords as the default +debug key (as described above). (To do so in Eclipse/ADT, go to +Windows > Preferences > +Android > Build.)

      + +

      Caution: You cannot release your application +to the public when signed with the debug certificate.

      + +

      Eclipse Users

      + +

      If you are developing in Eclipse/ADT (and have set up Keytool and Jarsigner as described above in +Basic Setup for Signing), +signing in debug mode is enabled by default. When you run or debug your +application, ADT signs the {@code .apk} file with the debug certificate, runs {@code zipalign} on +the package, then installs it on +the selected emulator or connected device. No specific action on your part is needed, +provided ADT has access to Keytool.

      + +

      Ant Users

      + +

      If you are using Ant to build your {@code .apk} file, debug signing mode +is enabled by using the debug option with the ant command +(assuming that you are using a build.xml file generated by the +android tool). When you run ant debug to +compile your app, the build script generates a keystore/key and signs the APK for you. +The script then also aligns the APK with the zipalign tool. +No other action on your part is needed. Read +Building and Running Apps +on the Command Line for more information.

      + + +

      Expiry of the Debug Certificate

      + +

      The self-signed certificate used to sign your application in debug mode (the default on +Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.

      + +

      When the certificate expires, you will get a build error. On Ant builds, the error +looks like this:

      + +
      debug:
      +[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
      +[exec] Debug Certificate expired on 8/4/08 3:43 PM
      + +

      In Eclipse/ADT, you will see a similar error in the Android console.

      + +

      To fix this problem, simply delete the debug.keystore file. +The default storage location for AVDs is in ~/.android/ on OS X and Linux, +in C:\Documents and Settings\<user>\.android\ on Windows XP, and in +C:\Users\<user>\.android\ on Windows Vista and Windows 7.

      + + +

      The next time you build, the build tools will regenerate a new keystore and debug key.

      + +

      Note that, if your development machine is using a non-Gregorian locale, the build +tools may erroneously generate an already-expired debug certificate, so that you get an +error when trying to compile your application. For workaround information, see the +troubleshooting topic +I can't compile my app because the build tools generated an expired debug +certificate.

      + + +

      Signing in Release Mode

      + +

      When your application is ready for release to other users, you must:

      +
        +
      1. Obtain a suitable private key
      2. +
      3. Compile the application in release mode
      4. +
      5. Sign your application with your private key
      6. +
      7. Align the final APK package
      8. +
      + +

      If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard +to perform the compile, sign, and align procedures. The Export Wizard even allows you to +generate a new keystore and private key in the process. So if you use Eclipse, you can +skip to Compile and sign with Eclipse ADT.

      + + + +

      1. Obtain a suitable private key

      + +

      In preparation for signing your application, you must first ensure that +you have a suitable private key with which to sign. A suitable private +key is one that:

      + +
        +
      • Is in your possession
      • +
      • Represents the personal, corporate, or organizational entity to be identified +with the application
      • +
      • Has a validity period that exceeds the expected lifespan of the application +or application suite. A validity period of more than 25 years is recommended. +

        If you plan to publish your application(s) on Google Play, note that a +validity period ending after 22 October 2033 is a requirement. You can not upload an +application if it is signed with a key whose validity expires before that date. +

      • +
      • Is not the debug key generated by the Android SDK tools.
      • +
      + +

      The key may be self-signed. If you do not have a suitable key, you must +generate one using Keytool. Make sure that you have Keytool available, as described +in Basic Setup.

      + +

      To generate a self-signed key with Keytool, use the keytool +command and pass any of the options listed below (and any others, as +needed).

      + +

      Warning: Keep your private key secure. +Before you run Keytool, make sure to read +Securing Your Private Key for a discussion of how to keep +your key secure and why doing so is critically important to you and to users. In +particular, when you are generating your key, you should select strong passwords +for both the keystore and key.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Keytool OptionDescription
      -genkeyGenerate a key pair (public and private +keys)
      -vEnable verbose output.
      -alias <alias_name>An alias for the key. Only +the first 8 characters of the alias are used.
      -keyalg <alg>The encryption algorithm to use +when generating the key. Both DSA and RSA are supported.
      -keysize <size>The size of each generated key +(bits). If not supplied, Keytool uses a default key size of 1024 bits. In +general, we recommend using a key size of 2048 bits or higher.
      -dname <name>

      A Distinguished Name that describes +who created the key. The value is used as the issuer and subject fields in the +self-signed certificate.

      Note that you do not need to specify this option +in the command line. If not supplied, Jarsigner prompts you to enter each +of the Distinguished Name fields (CN, OU, and so on).

      -keypass <password>

      The password for the +key.

      As a security precaution, do not include this option in your command +line. If not supplied, Keytool prompts you to enter the password. In this way, +your password is not stored in your shell history.

      -validity <valdays>

      The validity period for the +key, in days.

      Note: A value of 10000 or greater is recommended.

      -keystore <keystore-name>.keystoreA name +for the keystore containing the private key.
      -storepass <password>

      A password for the +keystore.

      As a security precaution, do not include this option in your +command line. If not supplied, Keytool prompts you to enter the password. In +this way, your password is not stored in your shell history.

      + +

      Here's an example of a Keytool command that generates a private key:

      + +
      $ keytool -genkey -v -keystore my-release-key.keystore
      +-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
      + +

      Running the example command above, Keytool prompts you to provide +passwords for the keystore and key, and to provide the Distinguished +Name fields for your key. It then generates the keystore as a file called +my-release-key.keystore. The keystore and key are +protected by the passwords you entered. The keystore contains +a single key, valid for 10000 days. The alias is a name that you — +will use later, to refer to this keystore when signing your application.

      + +

      For more information about Keytool, see the documentation at + +http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

      + + + +

      2. Compile the application in release mode

      + +

      In order to release your application to users, you must compile it in release mode. +In release mode, the compiled application is not signed by default and you will need +to sign it with your private key.

      + +

      Caution: +You can not release your application unsigned, or signed with the debug key.

      + +

      With Eclipse

      + +

      To export an unsigned APK from Eclipse, right-click the project in the Package +Explorer and select Android Tools > Export Unsigned Application +Package. Then specify the file location for the unsigned APK. +(Alternatively, open your AndroidManifest.xml file in Eclipse, select +the Manifest tab, and click Export an unsigned APK.)

      + +

      Note that you can combine the compiling and signing steps with the Export Wizard. See +Compiling and signing with Eclipse ADT.

      + +

      With Ant

      + +

      If you are using Ant, you can enable release mode by using the release option +with the ant command. For example, if you are running Ant from the +directory containing your {@code build.xml} file, the command would look like this:

      + +
      $ ant release
      + +

      By default, the build script compiles the application APK without signing it. The output file +in your project {@code bin/} will be <your_project_name>-unsigned.apk. +Because the application APK is still unsigned, you must manually sign it with your private +key and then align it using {@code zipalign}.

      + +

      However, the Ant build script can also perform the signing +and aligning for you, if you have provided the path to your keystore and the name of +your key alias in the project's {@code ant.properties} file. With this information provided, +the build script will prompt you for your keystore and alias password when you perform +ant release, it will sign the package and then align it. The final output +file in {@code bin/} will instead be +<your_project_name>-release.apk. With these steps +automated for you, you're able to skip the manual procedures below (steps 3 and 4). +To learn how to specify your keystore and alias in the {@code ant.properties} file, +see +Building and Running Apps on the Command Line.

      + + + +

      3. Sign your application with your private key

      + +

      When you have an application package that is ready to be signed, you can do sign it +using the Jarsigner tool. Make sure that you have Jarsigner available on your +machine, as described in Basic Setup. Also, make sure that +the keystore containing your private key is available.

      + +

      To sign your application, you run Jarsigner, referencing both the +application's APK and the keystore containing the private key with which to +sign the APK. The table below shows the options you could use.

      + + + + + + + + + + + + + + + + + + + + + + + + +
      Jarsigner OptionDescription
      -keystore <keystore-name>.keystoreThe name of +the keystore containing your private key.
      -verboseEnable verbose output.
      -sigalgThe name of the signature algorithim to use in signing the APK. +Use the value {@code MD5withRSA}.
      -digestalgThe message digest algorithim to use in processing the entries +of an APK. Use the value {@code SHA1}.
      -storepass <password>

      The password for the +keystore.

      As a security precaution, do not include this option +in your command line unless you are working at a secure computer. +If not supplied, Jarsigner prompts you to enter the password. In this +way, your password is not stored in your shell history.

      -keypass <password>

      The password for the private +key.

      As a security precaution, do not include this option +in your command line unless you are working at a secure computer. +If not supplied, Jarsigner prompts you to enter the password. In this +way, your password is not stored in your shell history.

      + +

      Here's how you would use Jarsigner to sign an application package called +my_application.apk, using the example keystore created above. +

      + +
      $ jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore my-release-key.keystore
      +my_application.apk alias_name
      + +

      Running the example command above, Jarsigner prompts you to provide +passwords for the keystore and key. It then modifies the APK +in-place, meaning the APK is now signed. Note that you can sign an +APK multiple times with different keys.

      + +

      Caution: As of JDK 7, the default signing algorithim has +changed, requiring you to specify the signature and digest algorithims ({@code -sigalg} and {@code +-digestalg}) when you sign an APK.

      + +

      To verify that your APK is signed, you can use a command like this:

      + +
      $ jarsigner -verify my_signed.apk
      + +

      If the APK is signed properly, Jarsigner prints "jar verified". +If you want more details, you can try one of these commands:

      + +
      $ jarsigner -verify -verbose my_application.apk
      + +

      or

      + +
      $ jarsigner -verify -verbose -certs my_application.apk
      + +

      The command above, with the -certs option added, will show you the +"CN=" line that describes who created the key.

      + +

      Note: If you see "CN=Android Debug", this means the APK was +signed with the debug key generated by the Android SDK. If you intend to release +your application, you must sign it with your private key instead of the debug +key.

      + +

      For more information about Jarsigner, see the documentation at + +http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jarsigner.html

      + + +

      4. Align the final APK package

      + +

      Once you have signed the APK with your private key, run zipalign on the file. +This tool ensures that all uncompressed data starts with a particular byte alignment, +relative to the start of the file. Ensuring alignment at 4-byte boundaries provides +a performance optimization when installed on a device. When aligned, the Android +system is able to read files with {@code mmap()}, even if +they contain binary data with alignment restrictions, rather than copying all +of the data from the package. The benefit is a reduction in the amount of +RAM consumed by the running application.

      + +

      The zipalign tool is provided with the Android SDK, inside the +tools/ directory. To align your signed APK, execute:

      + +
      $ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
      + +

      The {@code -v} flag turns on verbose output (optional). {@code 4} is the +byte-alignment (don't use anything other than 4). The first file argument is +your signed {@code .apk} file (the input) and the second file is the destination {@code .apk} file +(the output). If you're overriding an existing APK, add the {@code -f} flag.

      + +

      Caution: Your input APK must be signed with your +private key before you optimize the package with {@code zipalign}. +If you sign it after using {@code zipalign}, it will undo the alignment.

      + +

      For more information, read about the +zipalign tool. + + +

      Compile and sign with Eclipse ADT

      + +

      If you are using Eclipse with the ADT plugin, you can use the Export Wizard to +export a signed APK (and even create a new keystore, +if necessary). The Export Wizard performs all the interaction with +the Keytool and Jarsigner for you, which allows you to sign the package using a GUI +instead of performing the manual procedures to compile, sign, +and align, as discussed above. Once the wizard has compiled and signed your package, +it will also perfom package alignment with {@code zipalign}. +Because the Export Wizard uses both Keytool and Jarsigner, you should +ensure that they are accessible on your computer, as described above +in the Basic Setup for Signing.

      + +

      To create a signed and aligned APK in Eclipse:

      + +
        +
      1. Select the project in the Package +Explorer and select File > Export.
      2. +
      3. Open the Android folder, select Export Android Application, + and click Next. +

        The Export Android Application wizard now starts, which will + guide you through the process of signing your application, + including steps for selecting the private key with which to sign the APK + (or creating a new keystore and private key).

        +
      4. Complete the Export Wizard and your application will be compiled, + signed, aligned, and ready for distribution.
      5. +
      + + + +

      Securing Your Private Key

      + +

      Maintaining the security of your private key is of critical importance, both +to you and to the user. If you allow someone to use your key, or if you leave +your keystore and passwords in an unsecured location such that a third-party +could find and use them, your authoring identity and the trust of the user +are compromised.

      + +

      If a third party should manage to take your key without your knowledge or +permission, that person could sign and distribute applications that maliciously +replace your authentic applications or corrupt them. Such a person could also +sign and distribute applications under your identity that attack other +applications or the system itself, or corrupt or steal user data.

      + +

      Your reputation as a developer entity depends on your securing your private +key properly, at all times, until the key is expired. Here are some tips for +keeping your key secure:

      + +
        +
      • Select strong passwords for the keystore and key.
      • +
      • When you generate your key with Keytool, do not supply the +-storepass and -keypass options at the command line. +If you do so, your passwords will be available in your shell history, +which any user on your computer could access.
      • +
      • Similarly, when signing your applications with Jarsigner, +do not supply the -storepass and -keypass +options at the command line.
      • +
      • Do not give or lend anyone your private key, and do not let unauthorized +persons know your keystore and key passwords.
      • +
      + +

      In general, if you follow common-sense precautions when generating, using, +and storing your key, it will remain secure.

      \ No newline at end of file diff --git a/docs/html/tools/publishing/preparing.jd b/docs/html/tools/publishing/preparing.jd new file mode 100644 index 000000000000..3ebf3f788389 --- /dev/null +++ b/docs/html/tools/publishing/preparing.jd @@ -0,0 +1,359 @@ +page.title=Preparing for Release +@jd:body + +
      +
      +

      Quickview

      +
        +
      • Learn which resources you'll need to release your app.
      • +
      • Find out how to configure and build your app for release.
      • +
      • Learn best practices for releasing your app.
      • +
      +

      In this document

      +
        +
      1. Introduction
      2. +
      3. Gathering Materials and Resources
      4. +
      5. Configuring Your Application
      6. +
      7. Building Your Application
      8. +
      9. Preparing External Servers and Resources
      10. +
      11. Testing Your Application for Release
      12. +
      +

      See also

      +
        +
      1. Publishing Overview
      2. +
      3. Signing Your Applications
      4. +
      5. Publishing Checklist for Google Play
      6. +
      +
      +
      + +

      Before you distribute your Android application to users you need to prepare it for release. The +preparation process is a required development +task for all Android applications and is the first step in the publishing process (see figure +1).

      + +

      When you prepare your application for release, you configure, build, and test a release +version of your application. The configuration tasks are straightforward, involving basic code +cleanup and code modification tasks that help optimize your application. The build process is +similar to the debug build process and can be done using JDK and Android SDK tools. The testing +tasks serve as a final check, ensuring that your application performs as expected under real-world +conditions. When you are finished preparing your application for release you have a signed +.apk file, which you can distribute directly to users or distribute through an +application marketplace such as Google Play.

      + +

      This document summarizes the main tasks you need to perform to prepare your application for +release. The tasks that are described in this document apply to all Android applications regardless +how they are released or distributed to users. If you are releasing your application through Google +Play, you should also read Publishing +Checklist for Google Play to be sure your release-ready application satisfies all Google Play +requirements.

      + +

      Note: As a best practice, your application should meet all of your +release criteria for functionality, performance, and stability before you perform the tasks outlined +in this document.

      + +Shows how the preparation process fits into the development process +

      + Figure 1. Preparing for release is a required development +task and is the first step in the publishing process. +

      + +

      Introduction

      + +

      To release your application to users you need to create a release-ready package that users can +install and run on their Android-powered devices. The release-ready package contains the same +components as the debug .apk file — compiled source code, resources, manifest +file, and so on — and it is built using the same build tools. However, unlike the debug +.apk file, the release-ready .apk file is signed with your own certificate +and it is optimized with the zipalign tool.

      + +
      + Shows the five tasks you perform to prepare your app for release +

      + Figure 2. You perform five main tasks to prepare your application for + release. +

      +
      + +

      The signing and optimization tasks are usually seamless if you are building your application with +Eclipse and the ADT plugin or with the Ant build script (included with the Android SDK). For +example, you can use the Eclipse Export Wizard to compile, sign, and optimize your application all +at once. You can also configure the Ant build script to do the same when you build from the command +line.

      + +

      To prepare your application for release you typically perform five main tasks (see figure 2). +Each main task may include one or more smaller tasks depending on how you are releasing your +application. For example, if you are releasing your application through Google Play you may want +to add special filtering rules to your manifest while you are configuring your application for +release. Similarly, to meet Google Play publishing guidelines you may have to prepare screenshots +and create promotional text while you are gathering materials for release.

      + +

      You usually perform the tasks listed in figure 2 after you have throroughly debugged and tested +your application. The Android SDK contains several tools to help you test and debug your Android +applications. For more information, see the Debugging and Testing sections in the Dev Guide.

      + +

      Gathering Materials and Resources

      + +

      To begin preparing your application for release you need to gather several supporting items. At a +minimum this includes cryptographic keys for signing your application and an application icon. You +might also want to include an end-user license agreement.

      + +

      Cryptographic keys

      + +

      The Android system requires that each installed application be digitally signed with a +certificate that is owned by the application's developer (that is, a certificate for which the +developer holds the private key). The Android system uses the certificate as a means of identifying +the author of an application and establishing trust relationships between applications. The +certificate that you use for signing does not need to be signed by a certificate authority; the +Android system allows you to sign your applications with a self-signed certificate. To learn about +certificate requirements, see Obtain a +suitable private key.

      + +

      Important: Your application must be signed with a cryptographic +key whose validity period ends after 22 October 2033.

      + +

      You may also have to obtain other release keys if your application accesses a service or uses a +third-party library that requires you to use a key that is based on your private key. For example, +if your application uses the MapView +class, which is part of the Google Maps external +library, you will need to register your application with the Google Maps service and obtain +a Maps API key. For information about getting a Maps API key, see Obtaining a Maps API +key.

      + +

      Application Icon

      + +

      Be sure you have an application icon and that it meets the recommended icon guidelines. Your +application's icon helps users identify your application on a device's Home +screen and in the Launcher window. It also appears in Manage Applications, My Downloads, and +elsewhere. In addition, publishing services such as Google Play display your icon to users.

      + +

      Note: If you are releasing your application on Google Play, you +need to create a high resolution + version of your icon. See Graphic +Assets for your Application for more information.

      + +

      End-user License Agreement

      + +

      Consider preparing an End User License Agreement (EULA) for your application. A EULA can help +protect your person, organization, and intellectual property, and we recommend that you provide one +with your application.

      + +

      Miscellaneous Materials

      + +

      You might also have to prepare promotional and marketing materials to publicize your application. +For example, if you are releasing your application on Google Play you will need to prepare some +promotional text and you will need to create screenshots of your application. For more +information, see + +Graphic Assets for your Application

      + +

      Configuring Your Application for Release

      + +

      After you gather all of your supporting materials you can start configuring your application +for release. This section provides a summary of the configuration changes we recommend that you make +to your source code, resource files, and application manifest prior to releasing your application. +Although most of the configuration changes listed in this section are optional, they are +considered good coding practices and we encourage you to implement them. In some cases, +you may have already made these configuration changes as part of your development process.

      + +

      Choose a good package name

      + +

      Make sure you choose a package name that is suitable over the life of your application. You +cannot change the package name after you distribute your application to users. You can set the +package name in application's manifest file. For more information, see the package attribute +documentation.

      + +

      Turn off logging and debugging

      + +

      Make sure you deactivate logging and disable the debugging option before you build your +application for release. You can deactivate logging by removing calls to +{@link android.util.Log} methods in your source files. You can disable debugging by removing the +android:debuggable attribute from the <application> tag in your +manifest file, or by setting the android:debuggable attribute to +false in your manifest file. Also, remove any log files or static test files that +were created in your project.

      + +

      Also, you should remove all {@link android.os.Debug} tracing calls that you +added to your code, such as {@link android.os.Debug#startMethodTracing()} and +{@link android.os.Debug#stopMethodTracing()} method calls.

      + +

      Clean up your project directories

      + +

      Clean up your project and make sure it conforms to the directory structure described in Android Projects. +Leaving stray or orphaned files in your project can prevent your application from compiling and +cause your application to behave unpredictably. At a minimum you should do the following cleanup +tasks:

      + +
        +
      • Review the contents of your jni/, lib/, and src/ + directories. The jni/ directory should contain only source files associated with the + Android NDK, such as + .c, .cpp, .h, and .mk files. The + lib/ directory should contain only third-party library files or private library + files, including prebuilt shared and static libraries (for example, .so files). The + src/ directory should contain only the source files for your application + (.java and .aidl files). The src/ directory should not + contain any .jar files.
      • +
      • Check your project for private or proprietary data files that your application does not use + and remove them. For example, look in your project's res/ directory for old + drawable files, layout files, and values files that you are no longer using and delete them.
      • +
      • Check your lib/ directory for test libraries and remove them if they are no + longer being used by your application.
      • +
      • Review the contents of your assets/ directory and your res/raw/ + directory for raw asset files and static files that you need to update or remove prior to + release.
      • +
      + +

      Review and update your manifest settings

      + +

      Verify that the following manifest items are set correctly:

      + +
        +
      • + <uses-permission> element +

        You should specify only those permissions that are relevant and required for your application.

        +
      • +
      • android:icon and android:label attributes +

        You must specify values for these attributes, which are located in the + <application> + element.

        +
      • +
      • android:versionCode and android:versionName attributes. +

        We recommend that you specify values for these attributes, which are located in the + <manifest> + element. For more information see + Versioning your Application.

        +
      • +
      + +

      There are several additional manifest elements that you can set if you are releasing your +application on Google Play. For example, the android:minSdkVersion and +android:targetSdkVersion attributes, which are located in the <uses-sdk> element. For more +information about these and other Google Play settings, see Filters on Google Play.

      + +

      Address compatibility issues

      + +

      Android provides several tools and techniques to make your application compatible with a wide +range of devices. To make your application available to the largest number of users, consider +doing the following:

      + +
        +
      • Add support for multiple screen configurations +

        Make sure you meet the + + best practices for supporting multiple screens. By supporting multiple screen configurations + you can create an application that functions properly and looks good on any of the screen sizes + supported by Android.

        +
      • +
      • Optimize your application for Android tablet devices. +

        If your application is designed for devices older than Android 3.0, make it compatible + with Android 3.0 devices by following the guidelines and best practices described in + Optimizing Apps for Android 3.0 + .

        +
      • +
      • Consider using the Support Library +

        If your application is designed for devices running Android 3.x, make your application + compatible with older versions of Android by adding the + Support Library to your + application project. The Support Library provides static support libraries that you can add to + your Android application, which enables you to use APIs that are either not available on + older platform versions or use utility APIs that are not part of the framework APIs.

        +
      • +
      + +

      Update URLs for servers and services

      + +

      If your application accesses remote servers or services, make sure you are using the production +URL or path for the server or service and not a test URL or path.

      + +

      Implement Licensing (if you are releasing on Google Play)

      + +

      If you are releasing a paid application through Google Play, consider adding support for +Google Play Licensing. Licensing lets you control access to your application based on whether the +current user has purchased it. Using Google Play Licensing is optional even if you are +releasing your app through Google Play.

      + +

      For more information about Google Play Licensing Service and how to use it in your +application, see Application Licensing.

      + +

      Building Your Application for Release

      + +

      After you finish configuring your application you can build it into a release-ready +.apk fle that is signed and optimized. The JDK includes the tools for signing the +.apk file (Keytool and Jarsigner); the Android SDK includes the tools for compiling and +optimizing the .apk file. If you are using Eclipse with the ADT plugin or you are using +the Ant build script from the command line, you can automate the entire build process.

      + +

      Building with Eclipse

      + +

      You can use the Eclipse Export Wizard to build a release-ready .apk file that is +signed with your private key and optimized. To learn how to run the Export Wizard, see +Compile and sign with Eclipse +ADT. The Export Wizard compiles your application for release, signs your application with your +private key, and optimizes your application with the zipalign tool. The Export Wizard should run +successfully if you have run or debugged your application from Eclipse and you have no errors in +your application (see Building +and Running from Eclipse with ADT for more information.

      + +

      The Export Wizard assumes that you have a certificate and private key +suitable for signing your application. If you do not have a suitable certificate and private key, +the Export Wizard will help you generate one (see +Signing Your Applications for more +information about the signing process and signing guidelines.

      + +

      Building with Ant

      + +

      You can use the Ant build script (included in the Android SDK) to build a release-ready +.apk file that is signed with your private key and optimized. To learn how to do this, +see Building in +Release Mode. This build method assumes you have a certificate and +private key suitable for signing your application. If you do not have a suitable certificate and +private key, the Export Wizard will help you generate one (see +Signing Your Applications for more +information about the signing process and signing guidelines.

      + +

      Preparing External Servers and Resources

      + +

      If your application relies on a remote server, make sure the server is secure and that it is +configured for production use. This is particularly important if you are implementing in-app billing in your application and you are +performing the signature verification step on a remote server.

      + +

      Also, if your application fetches content from a remote server or a real-time service (such as a +content feed), be sure the content you are providing is up to date and production-ready.

      + +

      Testing Your Application for Release

      + +

      Testing the release version of your application helps ensure that your application runs properly +under realistic device and network conditions. Ideally, you should test your application on at least +one handset-sized device and one tablet-sized device to verify that your user interface elements are +sized correctly and that your application's performance and battery efficiency are acceptable.

      + +

      As a starting point for testing, see +What to Test. This article provides +a summary of common Android situations that you should consider when you are testing. When you are +done testing and you are satisfied that the release version of your application +behaves correctly, you can release your application to users. For more information, see +Releasing Your +Application to Users. If you are publishing your application on Google Play, see +Publishing Checklist +for Google Play.

      + + diff --git a/docs/html/tools/publishing/publishing_overview.jd b/docs/html/tools/publishing/publishing_overview.jd new file mode 100755 index 000000000000..572766c9d05a --- /dev/null +++ b/docs/html/tools/publishing/publishing_overview.jd @@ -0,0 +1,238 @@ +page.title=Publishing Overview +@jd:body + +
      +
      +

      Quickview

      +
        +
      • Learn how to publish Android apps.
      • +
      • Find out how to prepare apps for release.
      • +
      • Learn how to release apps to users.
      • +
      +

      In this document

      +
        +
      1. Preparing Your Application for Release
      2. +
      3. Releasing Your Application to Users +
      +

      See also

      +
        +
      1. Publishing on Google Play
      2. +
      +
      +
      + +

      Publishing is the general process that makes your Android applications available to users. When you +publish an Android application you perform two main tasks:

      + +
        +
      • You prepare the application for release. +

        During the preparation step you build a release version of your application, which users can + download and install on their Android-powered devices.

        +
      • +
      • You release the application to users. +

        During the release step you publicize, sell, and distribute the release version of your + application to users.

        +
      • +
      + +

      Usually, you release your application through an application marketplace, such as Google Play. +However, you can also release applications by sending them directly to users or by letting users +download them from your own website.

      + +

      Figure 1 shows how the publishing process fits into the overall Android application development process. +The publishing process is typically performed after you finish testing your application in a debug +environment. Also, as a best practice, your application should meet all of your release criteria for +functionality, performance, and stability before you begin the publishing process.

      + +Shows where the publishing
+       process fits into the overall development process +

      + Figure 1. Publishing is the last phase of the Android application development process. +

      + +

      Preparing Your Application for Release

      + +

      Preparing your application for release is a multi-step process that involves the following +tasks:

      + +
        +
      • Configuring your application for release. +

        At a minimum you need to remove {@link android.util.Log} calls and remove the + android:debuggable + attribute from your manifest file. You should also provide values for the + android:versionCode and android:versionName attributes, which are + located in the + <manifest> + element. You may also have to configure several other settings to meet Google Play + requirements or accomodate whatever method you're using to release your application.

        +
      • +
      • Building and signing a release version of your application. +

        The Android Development Tools (ADT) plugin and the Ant build script that are provided + with the Android SDK tools provide everything you need to build and sign a release version of + your application.

        +
      • +
      • Testing the release version of your application. +

        Before you distribute your application, you should thoroughly test the release version on at + least one target handset device and one target tablet device.

        +
      • +
      • Updating application resources for release. +

        You need to be sure that all application resources such as multimedia files and graphics + are updated and included with your application or staged on the proper production servers.

        +
      • +
      • Preparing remote servers and services that your application depends on. +

        If your application depends on external servers or services, you need to be sure they + are secure and production ready.

        +
      • +
      + +

      You may have to perform several other tasks as part of the preparation process. For example, you +will need to get a private key for signing your application, and you may need to get a Maps API +release key if you are using the Google Maps external +library. You will also need to create an icon for your application, and you may want to prepare +an End User License Agreement (EULA) to protect your person, organization, and intellectual +property.

      + +

      When you are finished preparing your application for release you will have a signed +.apk file that you can distribute to users.

      + +

      To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This +topic provides step-by-step instructions for configuring and building a release version of your +application.

      + +

      Releasing Your Application to Users

      + +

      You can release your Android applications several ways. Usually, you release applications +through an application marketplace such as Google Play, but you can also release applications +on your own website or by sending an application directly to a user. + +

      Releasing through an App Marketplace

      + +

      If you want to distribute your apps to the broadest possible audience, releasing through +an app marketplace such as Google Play is ideal.

      + +

      Google Play is the premier marketplace for Android apps and is particularly +useful if you want to distribute your applications to a large global audience. +However, you can distribute your apps through any app marketplace you want or +you can use multiple marketplaces.

      + + +

      Releasing Your Applications on Google Play

      + +

      Google Play is a robust publishing platform that helps you publicize, sell, and distribute +your Android applications to users around the world. When you release your applications through +Google Play you have access to a suite of developer tools that let you analyze your sales, +identify market trends, and control who your applications are being distributed to. You also have +access to several revenue-enhancing features such as in-app billing and application licensing. The rich array of tools +and features, coupled with numerous end-user community features, makes Google Play the premier +marketplace for selling and buying Android applications.

      + +

      Releasing your application on Google Play is a simple process that involves three basic + steps:

      + +
        +
      • Preparing promotional materials. +

        To fully leverage the marketing and publicity capabilities of Google Play, you need to + create promotional materials for your application, such as screenshots, videos, graphics, and + promotional text.

        +
      • +
      • Configuring options and uploading assets. +

        Google Play lets you target your application to a worldwide pool of users and devices. + By configuring various Google Play settings, you can choose the countries you want to + reach, the listing languages you want to use, and the price you want to charge in each + country. You can also configure listing details such as the application type, category, and + content rating. When you are done configuring options you can upload your promotional materials + and your application as a draft (unpublished) application.

        +
      • +
      • Publishing the release version of your application. +

        If you are satisfied that your publishing settings are correctly configured and your + uploaded application is ready to be released to the public, you can simply click + Publish in the developer console and within minutes your application will be + live and available for download around the world.

        +
      • +
      + +

      For information complete information, see Google Play.

      + + +

      Releasing your application through email

      + +
      + Screenshot showing the graphical user interface users see when you send them an app +

      + Figure 1. Users can simply click Install when you send them + an application via email. +

      +
      + +

      The easiest and quickest way to release your application is to send it to a user through +email. To do this, you prepare your application for release and then attach it to an email +and send it to a user. When the user opens your email message on their Android-powered device +the Android system will recognize the APK and display an Install Now +button in the email message (see figure 1). Users can install your application by touching the +button.

      + +

      Note: The Install Now button +shown in Figure 1 appears only if a user has configured their device to allow +installation from unknown sources and has opened your +email with the native Gmail application.

      + +

      Distributing applications through email is convenient if you are sending your application to +only a few trusted users, but it provides few protections from piracy and unauthorized +distribution; that is, anyone you send your application to can simply forward it to someone else.

      + +

      Releasing through a web site

      + +

      If you do not want to release your app on a marketplace like Google Play, you +can make the app available for download on your own website or server, including +on a private or enterprise server. To do this, you must first prepare your +application for release in the normal way. Then all you need to do is host the +release-ready APK file on your website and provide a download link to users. +

      + +

      When users browse to the download link from their Android-powered devices, +the file is downloaded and Android system automatically starts installing it on +the device. However, the installation process will start automatically only if +the user has configured their Settings to allow the installation of apps from +unknown sources.

      + +

      Although it is relatively easy to release your application on your own +website, it can be inefficient. For example, if you want to monetize your +application you will have to process and track all financial transactions +yourself and you will not be able to use Google Play's In-app Billing service +to sell in-app products. In addition, you will not be able to use the Licensing service to +help prevent unauthorized installation and use of your application.

      + + +

      User Opt-In for Apps from Unknown Sources

      + +
      + Screenshot showing the setting for accepting download and install of
+       apps from unknown sources. +

      + Figure 2. Users must enable the Unknown sources + setting before they can install apps not downloaded from Google Play. +

      +
      + +

      Android protects users from inadvertent download and install of apps from +locations other than Google Play (which is trusted). It blocks such installs +until the user opts-in Unknown sources in +Settings > Security, shown in Figure 2. To allow +the installation of applications from other sources, users need to enable the +Unknown sources setting on their devices, and they need to make this +configuration change before they download your application to their +devices.

      + +

      Note that some network providers do not allow users to install +applications from unknown sources.

      diff --git a/docs/html/tools/publishing/versioning.jd b/docs/html/tools/publishing/versioning.jd new file mode 100644 index 000000000000..8f602b4d5a2c --- /dev/null +++ b/docs/html/tools/publishing/versioning.jd @@ -0,0 +1,174 @@ +page.title=Versioning Your Applications +@jd:body + +
      +
      + +

      Quickview

      + +
        +
      • Your application must be versioned
      • +
      • You set the version in the application's manifest file
      • +
      • How you version your applications affects how users upgrade
      • +
      • Determine your versioning strategy early in the development process, including considerations for future releases.
      • +
      + +

      In this document

      + +
        +
      1. Setting Application Version
      2. +
      3. Specifying Your Application's System API Requirements +
      + + +

      See also

      + +
        +
      1. Preparing to Publish Your Application
      2. +
      3. Publishing Checklist for Google Play
      4. +
      5. The AndroidManifest.xml File
      6. +
      + +
      +
      + +

      Versioning is a critical component of your application upgrade and maintenance +strategy. Versioning is important because:

      + +
        +
      • Users need to have specific information about the application version that +is installed on their devices and the upgrade versions available for +installation.
      • +
      • Other applications — including other applications that you publish as +a suite — need to query the system for your application's version, to +determine compatibility and identify dependencies.
      • +
      • Services through which you will publish your application(s) may also need to +query your application for its version, so that they can display the version to +users. A publishing service may also need to check the application version to +determine compatibility and establish upgrade/downgrade relationships.
      • +
      + +

      The Android system does not use app version information to enforce +restrictions on upgrades, downgrades, or compatibility of third-party apps. Instead, you (the +developer) are responsible for enforcing version restrictions within your application or by +informing users of the version restrictions and limitations. The Android system does, however, +enforce system version compatibility as expressed by the minSdkVersion attribute in the +manifest. This attribute allows an application to specify the minimum system API with which it is +compatible. For more information see Specifying Minimum System API +Version.

      + +

      Setting Application Version

      +

      To define the version information for your application, you set attributes in +the application's manifest file. Two attributes are available, and you should +always define values for both of them:

      + +
        +
      • android:versionCode — An integer value that represents +the version of the application code, relative to other versions. + +

        The value is an integer so that other applications can programmatically +evaluate it, for example to check an upgrade or downgrade relationship. You can +set the value to any integer you want, however you should make sure that each +successive release of your application uses a greater value. The system does not +enforce this behavior, but increasing the value with successive releases is +normative.

        + +

        Typically, you would release the first version of your application with +versionCode set to 1, then monotonically increase the value with each release, +regardless whether the release constitutes a major or minor release. This means +that the android:versionCode value does not necessarily have a +strong resemblance to the application release version that is visible to the +user (see android:versionName, below). Applications and publishing +services should not display this version value to users.

        +
      • +
      • android:versionName — A string value that represents the +release version of the application code, as it should be shown to users. +

        The value is a string so that you can describe the application version as a +<major>.<minor>.<point> string, or as any other type of +absolute or relative version identifier.

        + +

        As with android:versionCode, the system does not use this value +for any internal purpose, other than to enable applications to display it to +users. Publishing services may also extract the android:versionName +value for display to users.

        +
      • +
      + +

      You define both of these version attributes in the +<manifest> element of the manifest file.

      + +

      Here's an example manifest that shows the android:versionCode +and android:versionName attributes in the +<manifest> element.

      + +
      +<?xml version="1.0" encoding="utf-8"?>
      +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      +      package="com.example.package.name"
      +      android:versionCode="2"
      +      android:versionName="1.1">
      +    <application android:icon="@drawable/icon" android:label="@string/app_name">
      +        ...
      +    </application>
      +</manifest>
      +
      + +

      In this example, note that android:versionCode value indicates +that the current .apk contains the second release of the application code, which +corresponds to a minor follow-on release, as shown by the +android:versionName string.

      + +

      The Android framework provides an API to let applications query the system +for version information about your application. To obtain version information, +applications use the +{@link android.content.pm.PackageManager#getPackageInfo(java.lang.String, int)} +method of {@link android.content.pm.PackageManager PackageManager}.

      + +

      Specifying Your Application's System API Requirements

      + +

      If your application requires a specific minimum version of the Android +platform, or is designed only to support a certain range of Android platform +versions, you can specify those version requirements as API Level identifiers +in the application's manifest file. Doing so ensures that your +application can only be installed on devices that +are running a compatible version of the Android system.

      + +

      To specify API Level requirements, add a <uses-sdk> +element in the application's manifest, with one or more of these attributes:

      + +
        +
      • android:minSdkVersion — The minimum version +of the Android platform on which the application will run, specified +by the platform's API Level identifier.
      • +
      • android:targetSdkVersion — Specifies the API Level +on which the application is designed to run. In some cases, this allows the +application to use manifest elements or behaviors defined in the target +API Level, rather than being restricted to using only those defined +for the minimum API Level.
      • +
      • android:maxSdkVersion — The maximum version +of the Android platform on which the application is designed to run, +specified by the platform's API Level identifier. Important: Please read the <uses-sdk> +documentation before using this attribute.
      • +
      + +

      When preparing to install your application, the system checks the value of this +attribute and compares it to the system version. If the +android:minSdkVersion value is greater than the system version, the +system aborts the installation of the application. Similarly, the system +installs your application only if its android:maxSdkVersion +is compatible with the platform version.

      + +

      If you do not specify these attributes in your manifest, the system assumes +that your application is compatible with all platform versions, with no +maximum API Level.

      + +

      To specify a minimum platform version for your application, add a +<uses-sdk> element as a child of +<manifest>, then define the +android:minSdkVersion as an attribute.

      + +

      For more information, see the <uses-sdk> +manifest element documentation and the API Levels document.

      diff --git a/docs/html/tools/revisions/index.jd b/docs/html/tools/revisions/index.jd new file mode 100644 index 000000000000..0e7ceef21b6f --- /dev/null +++ b/docs/html/tools/revisions/index.jd @@ -0,0 +1,9 @@ +page.title=Revisions +page.noplus=1 +@jd:body + +

      The Android SDK is composed of individual packages that may undergo +an update at their own schedule, so some have their own set of release notes. You can +find information about some of the packages in this section, including the core SDK Tools and the latest Platforms.

      \ No newline at end of file diff --git a/docs/html/tools/revisions/platforms.jd b/docs/html/tools/revisions/platforms.jd new file mode 100644 index 000000000000..e57c2210e7ed --- /dev/null +++ b/docs/html/tools/revisions/platforms.jd @@ -0,0 +1,831 @@ +page.title=Platforms +@jd:body + + + + + +

      To develop an Android app, you must install at least one Android platform from the SDK Manager +against which you can compile your app. Often, any given version of the Android will be revised +with bug fixes or other changes, as denoted by the "revision" number. Below, you'll find the +release notes for each version of the platform and the subsequent revisions to the platform +version.

      + +

      To determine what revision of an Android platform you +have installed, refer to the "Installed Packages" listing in the Android SDK Manager.

      + + + + + + + + +

      Android 4.0.3

      + + +

      Important: To download the new Android +4.0.x system components from the Android SDK Manager, you must first update the +SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, +the Android 4.0.x system components will not be available for download.

      + +
      + +

      + + Revision 3 (March 2012) +

      + +
      + +

      Maintenance update. The system version is 4.0.4.

      +

      Note: This system image includes support for emulator +hardware graphics acceleration when used with SDK Tools r17 or higher. +(more info)

      +
      +
      Dependencies:
      +
      SDK Tools r17 or higher is required.
      +
      + +
      +
      + +
      + +

      + + Revision 2 (January 2012) +

      + +
      + +

      Maintenance update. The system version is 4.0.3.

      +
      +
      Dependencies:
      +
      SDK Tools r14 or higher is required.
      +
      + +
      +
      + +
      + +

      + + Revision 1 (December 2011) +

      + +
      + +

      Initial release. The system version is 4.0.3.

      +
      +
      Dependencies:
      +
      SDK Tools r14 or higher is required.
      +
      + +
      +
      + +

      Emulator Skins

      + +

      The downloadable platform includes the following emulator skins:

      + +
        +
      • + QVGA (240x320, low density, small screen) +
      • +
      • + WQVGA400 (240x400, low density, normal screen) +
      • +
      • + WQVGA432 (240x432, low density, normal screen) +
      • +
      • + HVGA (320x480, medium density, normal screen) +
      • +
      • + WVGA800 (480x800, high density, normal screen) +
      • +
      • + WVGA854 (480x854 high density, normal screen) +
      • +
      • + WXGA720 (1280x720, extra-high density, normal screen) +
      • +
      • + WSVGA (1024x600, medium density, large screen) +
      • +
      • + WXGA (1280x800, medium density, xlarge screen) +
      • +
      + +

      To test your application on an emulator that represents the latest Android device, you can create +an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator +currently doesn't support the new on-screen navigation bar for devices without hardware navigation +buttons, so when using this skin, you must use keyboard keys Home for the Home button, +ESC for the Back button, and F2 or Page-up for the Menu button.

      + +

      However, due to performance issues in the emulator when running high-resolution screens such as +the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin +(hdpi, normal screen) to test your application.

      + + + + + + + + + + + + + + + +

      Android 4.0

      + + +
      + +

      + + Android 4.0, Revision 2 (December 2011) +

      + +
      +

      Maintenance update. The system version is 4.0.2.

      +
      +
      Dependencies:
      +
      SDK Tools r14 or higher is required.
      +
      +
      +
      + +
      + +

      + + Android 4.0, Revision 1 (October 2011) +

      + +
      +

      Initial release. The system version is 4.0.1.

      +
      +
      Dependencies:
      +
      SDK Tools r14 or higher is required.
      +
      +
      +
      + + +

      Emulator Skins

      + +

      The downloadable platform includes the following emulator skins:

      + +
        +
      • + QVGA (240x320, low density, small screen) +
      • +
      • + WQVGA400 (240x400, low density, normal screen) +
      • +
      • + WQVGA432 (240x432, low density, normal screen) +
      • +
      • + HVGA (320x480, medium density, normal screen) +
      • +
      • + WVGA800 (480x800, high density, normal screen) +
      • +
      • + WVGA854 (480x854 high density, normal screen) +
      • +
      • + WXGA720 (1280x720, extra-high density, normal screen) new +
      • +
      • + WSVGA (1024x600, medium density, large screen) new +
      • +
      • + WXGA (1280x800, medium density, xlarge screen) +
      • +
      + +

      To test your application on an emulator that represents the latest Android device, you can create +an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator +currently doesn't support the new on-screen navigation bar for devices without hardware navigation +buttons, so when using this skin, you must use keyboard keys Home for the Home button, +ESC for the Back button, and F2 or Page-up for the Menu button.

      + +

      However, due to performance issues in the emulator when running high-resolution screens such as +the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin +(hdpi, normal screen) to test your application.

      + + + + + + + + + + + + + +

      Android 3.2

      + + + +
      + +

      + + Android 3.2, Revision 1 (July 2011) +

      + +
      + +
      +
      Initial release. SDK Tools r12 or higher is recommended.
      +
      + +
      +
      + + + + +

      Emulator Skins

      + +

      The downloadable platform includes the following emulator skin:

      + +
        +
      • + WXGA (1280x800, medium density, xlarge screen) +
      • +
      + +

      For more information about how to develop an application that displays +and functions properly on all Android-powered devices, see Supporting Multiple +Screens.

      + + + + + + + + + + + + + + + + + + +

      Android 3.1

      + + +
      + +

      + + Android 3.1, Revision 3 (July 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r12 or +higher.

      +
      +
      Notes:
      +
      +

      Improvements to the platform's rendering library to support the visual layout editor in the ADT +Eclipse plugin. This revision allows for more drawing features in ADT and fixes several +bugs in the previous rendering library. It also unlocks several editor features that were added in +ADT 12.

      +
      +
      + +
      +
      + + +
      + +

      + + Android 3.1, Revision 2 (May 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r11 or +higher.

      +
      +
      Notes:
      +
      +

      Fixes an issue with the visual layout editor rendering library that prevented Android 3.1 from +running in ADT.

      +
      +
      + +
      +
      + + +
      + +

      + + Android 3.1, Revision 1 (May 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r11 or +higher.

      +
      +
      + +
      +
      + + +

      Emulator Skins

      + +

      The downloadable platform includes the following emulator skin:

      + +
        +
      • + WXGA (1280x800, medium density, xlarge screen) +
      • +
      + +

      For more information about how to develop an application that displays +and functions properly on all Android-powered devices, see Supporting Multiple +Screens.

      + + + + + + + + + + + +

      Android 3.0

      + + +
      + +

      + + Android 3.0, Revision 2 (July 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r12 or +higher.

      +
      +
      Notes:
      +
      +

      Improvements to the platform's rendering library to support the visual layout editor in the ADT +Eclipse plugin. This revision allows for more drawing features in ADT and fixes several +bugs in the previous rendering library. It also unlocks several editor features that were added in +ADT 12.

      +
      +
      + +
      +
      + +
      + +

      + + Android 3.0, Revision 1 (February 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r10 or higher.

      +
      +
      + +
      +
      + + + +

      Emulator Skins

      + +

      The downloadable platform includes the following emulator skin:

      + +
        +
      • + WXGA (1280x800, medium density, xlarge screen) +
      • +
      + + + + + + + + + + + + + + + + + + +

      Android 2.3.4

      + + + +

      The sections below provide notes about successive releases of +the Android 2.3.4 platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +2.3.4 platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

      + +
      + +

      + + Android 2.3.4, Revision 1 (May 2011) +

      + +
      +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r11 or higher.

      +
      +
      +
      +
      + + +

      Emulator Skins

      + +

      The downloadable platform includes a set of emulator skins that you can use +for modeling your application in different screen sizes and resolutions. The +emulator skins are:

      + +
        +
      • + QVGA (240x320, low density, small screen) +
      • +
      • + WQVGA400 (240x400, low density, normal screen) +
      • +
      • + WQVGA432 (240x432, low density, normal screen) +
      • +
      • + HVGA (320x480, medium density, normal screen) +
      • +
      • + WVGA800 (480x800, high density, normal screen) +
      • +
      • + WVGA854 (480x854 high density, normal screen) +
      • +
      + + + + + + + + + + + + + +

      Android 2.3.3

      + + +
      + +

      + + Android 2.3.3, Revision 2 (July 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r12 or +higher.

      +
      +
      Notes:
      +
      +

      Improvements to the platform's rendering library to support the visual layout editor in the ADT +Eclipse plugin. This revision allows for more drawing features in ADT and fixes several +bugs in the previous rendering library. It also unlocks several editor features that were added in +ADT 12.

      +
      +
      + +
      +
      + +
      + +

      + + Android 2.3.3, Revision 1 (February 2011) +

      + +
      +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r9 or higher.

      +
      +
      + +
      +
      + + +

      Emulator Skins

      + +

      The downloadable platform includes a set of emulator skins that you can use +for modeling your application in different screen sizes and resolutions. The +emulator skins are:

      + +
        +
      • + QVGA (240x320, low density, small screen) +
      • +
      • + WQVGA400 (240x400, low density, normal screen) +
      • +
      • + WQVGA432 (240x432, low density, normal screen) +
      • +
      • + HVGA (320x480, medium density, normal screen) +
      • +
      • + WVGA800 (480x800, high density, normal screen) +
      • +
      • + WVGA854 (480x854 high density, normal screen) +
      • +
      + + + + + + + + + + + + +

      Android 2.3

      + + + +

      The sections below provide notes about successive releases of +the Android 2.3 platform component for the Android SDK, as denoted by +revision number. To determine what revision(s) of the Android +2.3 platforms are installed in your SDK environment, refer to +the "Installed Packages" listing in the Android SDK and AVD Manager.

      + + +
      + +

      + + Android 2.3, Revision 1 (December 2010) +

      + +
      +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r8 or higher.

      +
      +
      +
      +
      + + +

      Emulator Skins

      + +

      The downloadable platform includes a set of emulator skins that you can use +for modeling your application in different screen sizes and resolutions. The +emulator skins are:

      + +
        +
      • + QVGA (240x320, low density, small screen) +
      • +
      • + WQVGA400 (240x400, low density, normal screen) +
      • +
      • + WQVGA432 (240x432, low density, normal screen) +
      • +
      • + HVGA (320x480, medium density, normal screen) +
      • +
      • + WVGA800 (480x800, high density, normal screen) +
      • +
      • + WVGA854 (480x854 high density, normal screen) +
      • +
      + + + + + + + + + +

      Android 2.2

      + + +
      + +

      + + Android {@sdkPlatformVersion}, Revision 3 (July 2011) +

      + +
      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r12 or +higher.

      +
      +
      Notes:
      +
      +

      Improvements to the platform's rendering library to support the visual layout editor in the ADT +Eclipse plugin. This revision allows for more drawing features in ADT and fixes several +bugs in the previous rendering library. It also unlocks several editor features that were added in +ADT 12.

      +
      +
      + +
      +
      + +
      + +

      + + Android {@sdkPlatformVersion}, Revision 2 (July 2010) +

      + +
      +
      Dependencies:
      +
      +

      Requires SDK Tools r6 or higher.

      +
      + +
      System Image:
      +
      +
        +
      • Adds default Search Widget.
      • +
      • Includes proper provisioning for the platform's Backup Manager. For more information about how +to use the Backup Manager, see Data +Backup.
      • +
      • Updates the Android 2.2 system image to FRF91.
      • +
      +
      + +
    +
    +
    + +
    + +

    + + Android {@sdkPlatformVersion}, Revision 1 (May 2010) +

    + +
    +
    +
    Dependencies:
    +
    +

    Requires SDK Tools r6 or higher.

    +
    + +
    Tools:
    +
    +

    Adds support for building with Android library projects. See SDK +Tools, r6 for information.

    +
    + +
    +
    +
    + + +

    Emulator Skins

    + +

    The downloadable platform includes a set of emulator skins that you can use +for modeling your application in different screen sizes and resolutions. The +emulator skins are:

    + +
      +
    • + QVGA (240x320, low density, small screen) +
    • +
    • + WQVGA (240x400, low density, normal screen) +
    • +
    • + FWQVGA (240x432, low density, normal screen) +
    • +
    • + HVGA (320x480, medium density, normal screen) +
    • +
    • + WVGA800 (480x800, high density, normal screen) +
    • +
    • + WVGA854 (480x854 high density, normal screen) +
    • +
    \ No newline at end of file diff --git a/docs/html/tools/samples/index.jd b/docs/html/tools/samples/index.jd new file mode 100644 index 000000000000..5c0e8db777eb --- /dev/null +++ b/docs/html/tools/samples/index.jd @@ -0,0 +1,31 @@ +page.title=Samples + +@jd:body + +

    To help you understand some fundamental Android APIs and coding practices, a variety of sample +code is available from the Android SDK Manager.

    + +

    To download the samples:

    +
      +
    1. Launch the Android SDK Manager. +
        +
      • On Windows, double-click the SDK Manager.exe file at the root of the Android SDK +directory.
      • +
      • On Mac or Linux, open a terminal to the {@code tools/} directory in the +Android SDK, then execute {@code android sdk}.
      +
    2. +
    3. Expand the list of packages for the latest Android platform.
    4. +
    5. Select and download Samples for SDK.
    6. +
    + +

    When the download is complete, you can find the samples sources at this location:

    + +

    +<sdk>/platforms/<android-version>/samples/ +

    + +

    You can easily create new Android projects with the downloaded samples, modify them +if you'd like, and then run them on an emulator or device.

    + \ No newline at end of file diff --git a/docs/html/tools/sdk/OLD_RELEASENOTES.jd b/docs/html/tools/sdk/OLD_RELEASENOTES.jd new file mode 100644 index 000000000000..6865db235c0b --- /dev/null +++ b/docs/html/tools/sdk/OLD_RELEASENOTES.jd @@ -0,0 +1,527 @@ +page.title=Release Notes for Older SDK Versions +@jd:body + +
    +

    Note: These are the release notes for the "early-look" SDK versions, released + before the full Android 1.0 release in September 2008. + Release notes for the Android 1.0 and later SDK versions are provided in the main + Release Notes document.

    +
    + + + + +

    Android 0.9 SDK Beta (r1)

    + +

    This beta SDK release contains a large number of bug fixes and improvements from the early-look SDKs.  +The sections below describe the highlights of the release. + +

    New Features and Notable Changes

    + +

    Behavior and System Changes

    +
      +
    • New Home screen and many user interface updates +
    • +
    • Minor changes to Activity lifecycle and task management +
    • +
    • New window option to request OpenGL acceleration for certain kinds of View structures +
    • +
    +

    + + Significant API Changes +

    +
      +
    • onFreeze(Bundle) renamed to onSaveInstanceState(Bundle), to better reflect the fact that it does not represent an actual change in application lifecycle +
    • +
    • IntentReceivers are now known as BroadcastReceivers (but still operate on Intents.) +
    • +
    • Various parts of the API cleaned up to use Intents instead of Bundles; Intent itself improved to reduce the need for separate payload Bundles.
    • +
    • ContentProvider Cursors have had significant changes to make them easier to create and remove certain data consistency bugs. +
    • +
    • Changes to menus to make them more flexible; also added context menus (similar to "right mouse button" menus) +
    • +
    • Changes to the Sensor API to make reading sensors more convenient and reduce the need to poll +
    • +
    • Improvements to the Camera API +
    • +
    • Significant changes to the Location API to make it easier to use and better self-documenting +
    • +
    • API cleanup on MapViews +
    • +
    • Performance-related changes to the MediaPlayer, as well as support for new types of ringtones +
    • +
    • Apache HTTPClient installation upgraded to 4.x of that API; 3.x version is removed +
    • +
    • HTTPClient 4.x removes multipart methods, include HttpMime which is an extension of Mime4j (http://james.apache.org/mime4j/index.html) in your project instead +
    • +
    • Improvements to WiFi and related networking +
    • +
    • New Preferences API to easily store small amounts of data +
    • +
    • Improvements to the Telephony API, including ability to obtain source number of incoming phone calls +
    • +
    • Variety of improvements to the View API +
    • +
    • Variety of improvements to component management, such as the ability to keep components private, better control over when processes are started, and ability to "alias" an Activity to more than one entry in AndroidManifest.xml +
    • +
    • Improvements to how the Browser and WebView, such as better control over content downloads +
    • +
    • A number of enhancements to XML layouts, such as the new <merge> tag +
    • +
    • Numerous improvements to the standard widgets +
    • +
    • Network access now requires that applications obtain a permission in their AndroidManifest.xml files. +
    • +
    +

    + + Maps & Location +

    +
      +
    • The MapView will require an API key on final Android 1.0 devices. This key can be obtained at no cost from Google, and will allow access to the full MapView API. In this release, the API key must be provided but can be any dummy value.  In the final 1.0-compatible SDKs, this will need to be a real key. +
    • +
    • The KML-based mock location provider supported in previous releases is no longer supported. In the current SDK, you can use the emulator console to send GPS fix updates to the emulator and applications running on it. Also, the DDMS tool provides an UI that you can use to easily upload GPX and KML files. DDMS handles playback of the KML or GPX tracks automatically.
    • +
    +

    + ADT Plugin for Eclipse

    +

    The ADT Plugin that accompanies this SDK includes a preview of the Graphical Layout Editor. Files located in <project>/res/layout[-qualifiers]/ will be opened with the new layout editor. This is very much a work in progress, and provided here for preview purpose. The editor feature is subject to change. +

    +
      +
    • Dual page editor with a WYSIWYG page (the graphical editor) and an XML page with content assist. +
    • +
    • The interactivity in the editor itself is limited to selection at the moment. Actions on the layout elements can be done from the following standard Eclipse views: Outline (add/remove/up/down), and Properties (editing of all the element properties with a tooltip in the status bar). +
    • +
    • Top part of the editor allows you to display the layout in different configurations (language, orientation, size, etc...), and different themes. + +
        +
      • All referenced resources (strings, bitmaps, etc...) are resolved based on the selected configuration/theme. +
      • +
      • A green check mark next to a resource qualifier indicates that the opened file matches the value of the qualifier. A warning sign indicates that the opened file does not specifies any value for this qualifier. +
      • +
      • If a different version of the opened layout matches the new configuration selection (in a different res/layout-qualifier folder) then the editor automatically switches to that new file. +
      • +
      +
    • +
    • Custom Views are supported, however if they do too much in their constructor/onDraw method, it may not work (the layout library used by the editor only includes a sub-part of the Android framework). Check the android console for errors/exceptions. +
    • +
    + +

    Known issues/limitations for Graphical Layout Editor include:

    + +
      +
    • Font display is very close but not equals to on-device rendering since the font engine in Java slightly differs from the font engine in Android. This should not have any impact on your layouts. +
    • +
    • Creating new views in a relative layout automatically puts each new elements below each other using the layout_below attribute. However, until the layout file is saved, they will appear stacked on top of each other. +
    • +
    • Some XML based drawables don't draw. Fading in the scroll/list view appears as a white rectangle. Generally do not expect every single fancy drawing feature of the android framework to be supported in the layout editor (but we're working on it). +
    • +
    • Themes defined in the project are not added to the theme drop-down. +
    • +
    • No animation support! +
    • +
    • No support for WebView, MapView and SurfaceView. +
    • +
    • No UI support for <merge>, <include>, <ViewStub> elements. You can add these elements to your manifest using the xml editor only. +
    • +
    • If a layout fails to render in a way that prevents the whole editor from opening, you can: + +
        +
      • open that particular file in a different editor: right click the file in the package explorer and choose Open With... > XML editor +
      • +
      • completely disable the layout editor, by setting a system wide environment variable called ANDROID_DISABLE_LAYOUT to any value. +
      • +
      +
    • If a layout fails to render, check the android console (in the standard Eclipse Console view). Errors/Exceptions will be displayed in there. +
    • +
    + + +

    Other ADT features/notes include:

    +
      +
    • There is a new launch option for activity. You can choose to launch the default activity (finds an activity configured to show up in the home screen), or a specific activity, or none.
    • +
    • Normal Java resources (non Java files placed in package folders) are now properly packaged in the final package, and can be accessed through normal java API such as ClassLoader.getResourceAsStream()
    • +
    • Launch configuration now has an option to wipe emulator data on launch. This always asks for confirmation.
    • +
    • Launch configuration now has an option to disable the boot animation. This will let the emulator start faster on older computers.
    • +
    • Installation of application is now more robust and will notify of installation failure. Also installation is blocking, removing issues where ADT tried to launch the activity before the app was installed.
    • + +
    + +

    Ant Build Tools

    + +
      +
    • External jar libraries are now directly supported by build.xml, just drop them in the libs directory.
    • +
    + +

    Emulator

    + +
      +
    • The console port number of a given emulator instance is now displayed in its window's title bar.
    • +
    • You can define the console port number used by a given emulator instance. +To do so, start the instance with the '-port <port>' option and +specify which port the emulator should bind to for the console. <port> must be an *even* integer between 5554 and 5584 inclusive. The corresponding ADB port will be <port>+1.
    • +
    • The -adb-port command is deprecated. Please do not use it, as it will be removed soon and you cannot use both -port and -adb-port at the same time.
    • +
    • Voice/sms are automatically forwarded to other emulator instances running on the same machine, as long as you use their console port number as the destination phone number. For example, if you have two emulators running, the first one will typically use console port 5554, and the second one will use port 5556, dialing 5556 on the first emulator will generate an incoming call on the second emulator. You can also hold/unhold calls. This also works when sending SMS messages from one emulator to the other.
    • +
    • A new -scale <fraction> option allows you to scale the emulator window.
    • +
    • A new -no-boot-anim option tells the emulator to disable the boot animation. On slower systems, this can significantly reduce the time to boot the system in the emulator.
    • + +
    + +

    + Other Development Tools +

    + +

    The SDK includes several new development tools, such as

    +
      +
    • HierarchyViewer is a visual tool for inspecting and debugging your user interfaces and layout.
    • +
    • Draw 9-patch allows you to easily create a NinePatch graphic using a WYSIWYG editor.
    • +
    • The UI/Application Exerciser Monkey generates pseudo-random system and user events, for testing your application.
    • +
    +

    + Application Signing +

    +
      +
    • Starting with this release, Android .apk files must be cryptographically signed, or the system will reject them upon installation.  The purpose of this requirement is to securely and uniquely identify developers, so that the system can -- for example -- safely let multiple .apk files signed by the same developer share resources.  +
    • +
    • There are no requirements on the key used to sign .apk files;  locally-generated and self-signed keys are allowed.  There is no PKI, and developers will not be required to purchase certificates, or similar.   For developers who use the Eclipse/ADT plugin, application signing will be largely automatic.  Developers who do not use Eclipse/ADT can use the standard Java jarsigner tool to sign .apk files. +
    • +
    +

    + Sample Code +

    +
      +
    • LunarLander has been converted to render into a SurfaceView via a background Thread, for better performance. +
    • +
    • New sample: the source code for the now-obsolete Home screen from M5 is included as an example of how to construct a Home screen replacement. +
    • +
    +

    + + Removed Functionality +

    +
      +
    • Due to significant API changes in the upstream open-source project and due to the timeline of getting certain Bluetooth profile implementations certified, a comprehensive Bluetooth API will not be possible or present in Android 1.0. +
    • +
    • Due to the security risks inherent in accepting arbitrary data from "outside" the device, the data messaging facility of the GTalkService will not be present in Android 1.0.  The GTalkService will provide connectivity to Google's servers for Google Talk instant messaging, but the API has been removed from this release while we improve the service.  Note that this will be a Google-specific service and is not part of the core of Android. +
    • +
    • We know that these changes will affect many developers who have worked with the prior early looks at the SDK, and we are very sorry for the resulting inconvenience.  We look forward to the possibilty of restoring some or all of this functionality in a later version of the Android platform. +
    • +
    +

    + + Miscellaneous +

    +
      +
    • Many internal and non-public APIs have been removed from the documentation.  Classes and methods that are not present in the documentation are non-public and should not be used, even though they may appear in tools such as IDEs.  A future version of the SDK will ship with an android.jar file that contains only public classes, to help developers avoid accidentally using non-public APIs. +
    • +
    • A few extraneous APIs (such as unnecessary packages under java.awt) have been removed. +
    • +
    • Several additional tools are included, such as a utility for easily drawing 9-patch images. +
    • +
    • The DDMS utility has been refactored into library form. This is not of direct interest to application developers, but may be of interest to vendors interested in integrating the Android SDK into their products. Watch for more information about the ddmlib library soon. +
    • +
    • For performance and maintainability reasons, some APIs were moved into separate modules that must be explicitly included in the application via a directive in AndroidManifest.xml.  Notable APIs that fall into this category are the MapView, and the java.awt.* classes, which each now reside in separate modules that must be imported.  Developers who overlook this requirement will see ClassNotFoundExceptions that seem spurious. +
    • +
    • Developers who use 'adb push' to install applications must now use 'adb install', since the full package manager is now implemented. 'adb push' will no longer work to install .apk files. +
    • +
    • The emulator supports a variety of new options, and some existing options have been changed.  Please consult the updated emulator documentation for details. +
    • +
    + +

    + Resolved Issues +

    +

    + The list below is not comprehensive, but instead highlights the most interesting fixes since the last SDK release. +

    +
      +
    • More of the standard Android user applications are now included, such as the Music and Messaging applications. +
    • +
    • Many bug fixes to the Media Player +
    • +
    • Emulator performance is improved, especially for startup +
    • +
    • More internal APIs are removed from class documentation.  (However, this work is not quite yet complete.) +
    • +
    • It's now much easier to add media content to the SD card and have the ContentProvider locate and expose it to other applications. +
    • +
    + +

    + Known Issues +

    +
      +
    • The final set of Intent patterns honored by Android 1.0 has not yet been fully documented.  Documentation will be provided in future releases. +
    • +
    • We regret to inform developers that Android 1.0 will not support 3.5" floppy disks. +
    • +
    • Unfortunately, the ability to play audio streams from memory (such as via an InputStream or Reader) will not be possible in Android 1.0.  As a workaround, we recommend that developers save media content to SD card and use MediaPlayer to play from a file URI, or embed a small HTTP server and play from a URI on localhost (such as http://127.0.0.1:4242/something). +
    • +
    • Android now supports modules or libraries that can be optionally linked into applications; a good example is the MapView, which has been moved into such a library. However, Android 1.0 will not support the ability for third-party developers to create such libraries for sharing with other applications. +
    • +
    • We believe that we have eliminated the problem with very long emulator startups on Windows, but had some trouble reproducing the issue.  We are interested in feedback from developers, if this issue persists. +
    • +
    + + + + + +

    Version m5-rc15

    + +

    New Features

    +

    m5-rc15 does not introduce any new features.

    + +

    Resolved Issues

    +
      +
    • 1012640: Incorrect handling of BMP images.
    • +
    + +

    Known Issues

    +

    Unless otherwise noted, Known Issues from m5-rc14 also apply to m5-rc15.

    + + + + + +

    Version m5-rc14

    + +

    New Features

    + +

    In addition to changes in the Android APIs, m5-rc14 also introduces changes to the Android Developer Tools:

    + +

    emulator

    +
      +
    • The Android emulator now support SD card images up to 128 GB in size. The previous limit was 2 GB.
    • +
    + +

    DDMS

    +
      +
    • Support for managing multiple devices has been integrated into DDMS. This should make it easier to debug applications that are run on multiple device scenarios.
    • +
    + +

    ADT

    +
      +
    • ADT now attempts to connect a debugger to any application that shows up + in the wait-for-debugger state, even if this application was not launched + from Eclipse. +

      + The connection is actually established only if there exists a project + in the Eclipse workspace that contains an AndroidManifest.xml + declaring a package matching the name of the process. + To force this connection from your code, use Debug.waitForDebugger(). Activities declaring that they require their own process through the + "process" attribute with a value like ":someProcess" will be + recognized and a debugger will be connected accordingly. + This should make it easier to debug intent receivers, services, + providers, and other activities not launched from the standard app + launcher.

    • +
    • ADT has launch modes for device target selection. Automatic mode will: 1) launch an emulator if no device is present, 2) automatically target the device if only one is connected, and 3) prompt the user if 2 or more are connected. Manual mode will always prompt the user.

    • +
    • ADT also contains the same support for multiple devices that has been introduced into DDMS.
    • +
    + +

    AIDL

    +
      +
    • AIDL files that import and reuse types is now supported by activityCreator.py and ADT.
    • +
    + +

    traceview

    +
      +
    • The traceview tool is now included in the SDK.
    • +
    + +

    Resolved Issues

    + +

    The following Known Issues from m3-rc20 have been resolved:

    +
      +
    • 917572: The activityCreator created incorrect IntelliJ scripts
    • +
    • 917465: Unanswered incoming calls placed from the emulator console will result in an unfinished call UI if you press the call back button
    • +
    • 917247: dmtracedump and traceview tools are not available in the SDK
    • +
    • 912168: Extremely rapid or prolonged scrolling in the Maps application or MapsView will result in application errors
    • +
    • 905852: adb emits warnings about deprecated API use on Mac OS X 10.5
    • +
    • 905242: The Run dialog sometimes failed to show the Android Launcher
    • +
    • 901122: The focus ring in the browser is sometimes incorrect
    • +
    • 896274: On Windows, the emulator sometimes starts off-screen
    • +
    • 778432: Icons for newly installed applications do not display
    • +
    + +

    Known Issues

    + +

    The following are known issues in m5-rc14:

    + +
      +
    • 1017312: The emulator window size has been reduced slightly, to allow it to be fully visible on smaller screens. This causes a slight clipping of the HVGA emulator skin but does not affect its function.
    • +
    • 1021777: Setting a power requirement in a Criteria object passed to {@link android.location.LocationManager#getBestProvider getBestProvider()} will result in a value not being returned.
    • +
    • 1025850: Emulator failing to launch from the Eclipse plugin due to wrong custom command line parameters do not report the error anywhere and silently fails.
    • +
    + +

    Unless otherwise noted, Known Issues from m3-rc20a also apply to m5-rc14.

    + + + + + +

    Version m3-rc37a

    + +

    Version m3-rc37a and ADT 0.3.3 were released on December 14, 2007.

    + +

    New Features

    + +

    Android Debug Bridge (ADB)

    +
      +
    • Now supports multiple emulators on one host computer. Please note that you need to use the -data option when starting secondary emulators, to allow those instances to save their data across sessions. Also, DDMS does not yet support debugging on multiple emulators yet.
    • +
    + +

    ADT Plugin for Eclipse

    +
      +
    • Adds editor capabilities for working with Android manifest files, such as syntax highlighting and autocompletion. The editor capabilities require the Web Tools WST plugin for Eclipse, which is included in most Eclipse packages. Not having WST does not prevent the ADT plugin from working. If necessary, you can download and install WST from the Web Tools Project downloads page. To update directly from an Eclipse installation, you can add a remote update site with this URL: http://download.eclipse.org/webtools/updates . Note that installing WST on Eclipse 3.4 will require installing other packages, as detailed on the WTP downloads page. +
    • +
    • Now retries to launch the app on the emulator if it fails due to timing issues when the emulator is booting.
    • +
    • Adds support for loading custom skins from the <SDK>/lib/images/skins/ directory. The Skin dropdown in the Emulator tab is now built from the content of the skins/ directory in order to support developer-made skins.
    • +
    • Adds an Emulator control panel. This is a UI on top of the emulator console that allows you to change the state of the network and gsm connection, and to initiate incoming voice call. (This is also present in standalone DDMS.)
    • +
    • Adds support for referenced projects. Android projects will add to the apk package any code from referenced projects.
    • +
    • Eclipse console now warns if an .apk that is pushed to the device declares the same package as another already installed package.
    • +
    • Java classes generated by the Eclipse plugin are now marked as derived automatically, so that Team plugins do not consider them as regular source.
    • +
    + +

    Emulator Console

    +
      +
    • Now provides support for emulating inbound SMS messages. The ADT plugin and DDMS provide integrated access to +this capability. For more information about how to emulate inbound SMS from the console, +see SMS Emulation.
    • +
    + +

    Emulator

    +
    • The default emulator skin has been changed to HVGA-P from QVGA-L. For information +about emulator skins and how to load a specific skin when starting the emulator, see +Using Emulator Skins.
    • +
    + +

    Resolved Issues

    + +

    907947

    +

    adb -version now returns a version number.

    + +

    917462

    +

    Audio on Windows is fixed and is no longer 'choppy'.

    + +

    Removed Manifest File Locking on Mac OS X

    + +

    ADT plugin now uses a custom java editor for R.java/Manifest.java, to make those files non-editable. This is to replace the current locking mechanism which causes issues on Mac OS (preventing projects from being deleted). Note that your project must recompile at least once for the lock to be removed from the files.

    + +

    The following known issues noted in m3-rc20 are now fixed:

    +

    +

      +
    • 890937: Emulator does not support non-qwerty keyboards. +
    • 894618: adb shell may fail to connect when used the first time. +
    • 896274: On Windows, the emulator window may start off-screen. +
    • 899949: The emulator may fail to start with -useaudio on some environments. +
    • 912619: Emulator console listens on non-local ports 5554-5584. +
    • 917399: On Windows, running multiple emulator consoles can result in unexpected behavior when simulating incoming telephone calls. +
    +

    + +

    Known Issues

    + +

    Unless otherwise noted, Known Issues from m3-rc22a also apply to m3-rc37a.

    + + + + + +

    Version m3-rc22a

    + +

    Version m3-rc22a and ADT 0.3.1 were released on November 16, 2007.

    + +

    Resolved Issues

    + +

    920067

    +

    The New Android Project wizard provided by ADT 0.3.1 now properly displays error messages when used with Eclipse 3.2 on Windows.

    + +

    920045

    +

    The AndroidManifest.xml files generated by ADT 0.3.1 now include the XML element required for displaying the associated app in the "Applications" menu. If you have applications created with ADT 0.3.0, simply ensure that your AndroidManifest.xml file contains the following highlighted line:

    +
    +...
    +    <intent-filter>
    +        <action android:value="android.intent.action.MAIN" />
    +        <category android:value="android.intent.category.LAUNCHER" />
    +    </intent-filter>
    +...
    +
    + +

    920098

    +

    ADT 0.3.1 is now compatible with Eclipse 3.4.

    + +

    920282

    +

    Fixes a NullPointerException that is thrown in certain situations with the DDMS perspective in Eclipse.

    + +

    918637

    +

    Address a keyboard lock-up issue when using adb on Mac OS X 10.4 and 10.5.

    + +

    Known Issues

    + +

    Unless otherwise noted, known issues from m3-rc20a also apply to m3-rc22a.

    + + + +

    Version m3-rc20a

    +

    Known Issues

    + +

    The following are known issues in m3-rc20a:

    + +

    778432 - Resolved in m5

    +

    In certain circumstances, icons for newly installed applications do not display as expected.

    + +

    890937 - Resolved in m3-rc37a

    +

    The emulator currently does not support non-QWERTY keyboards.

    + +

    894618 - Resolved in m3-rc37a

    +

    The adb shell command may fail to connect when used for the first time.

    + +

    896274 - Resolved in m5

    +

    On Windows, the emulator screen will sometimes show up off-screen when it is started. The workaround for this is to right-click on the emulator taskbar entry, select Move, and move the window using keyboard arrow keys

    + +

    899949 - Resolved in m3-rc37a

    +

    The emulator may fail to start when using the -useaudio in some environments

    + +

    901122 - Resolved in m5

    +

    The focus ring shown in the browser may sometimes not properly wrap links.

    + +

    905242 - Resolved in m5

    +

    On Mac OS X 10.5, the Eclipse plugin's Run Dialog may sometimes fail to show the option to select the Android Launcher.

    + +

    905852 - Resolved in m5

    +

    On Mac OS X 10.5, adb will emit warnings about deprecated API use when first used.

    + +

    912168 - Resolved in m5

    +

    extremely rapid or prolonged scrolling in the Maps application or in a MapView will result in application errors.

    + +

    912619 - Resolved in m3-rc37a

    +

    The emulator console listens for connections on ports 5554-5587. Future versions will only accept connections from localhost. It is recommend that you use a firewall to block external connections to those ports on your development machine.

    + +

    912849

    +

    On Mac OS X 10.4, the emulator may hang if started in the background (i.e. ./emulator &).

    + +

    914692

    +

    On Mac OS X 10.5, the emulator will emit warnings about deprecated API use when started from the command line.

    + +

    917247 - Resolved in m5

    +

    The dmtracedump and traceview tools are not available in the SDK.

    + +

    917399 - Resolved in m3-rc37a

    +

    On Windows, running multiple emulator consoles can result in unexpected behavior when simulating incoming telephone calls.

    + +

    917465 - Resolved in m5

    +

    Unanswered incoming calls placed from the emulator console, will result in an unfinished call UI if you press the call back button.

    + +

    917572 - Resolved in m5

    +

    Using activityCreator with the --ide intellij option creates IntelliJ scripts with incorrect documentation location specified. To correct, change value for the <JAVADOC> element in the generated .ipr file from file://.../docs/framework to file://.../docs/reference.

    + +

    917579

    +

    On Ubuntu 7.10 (Gusty), the Eclipse package installed by the apt-get install eclipse command uses java-gcj by default. This configuration is not compatible with the Android Eclipse plugin (ADT) and will result in "Class not found" errors whenever you access an ADT feature.

    +

    The resolution for this issue is to install a Sun JDK

    +
    sudo update-java-alternatives --jre java-1.5.0-sun
    +

    and then configure Eclipse to use it by exporting the following environment variable:

    +
    export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
    +

    or by adding following to your .eclipse/eclipserc file:

    +
    JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
    + diff --git a/docs/html/tools/sdk/RELEASENOTES.jd b/docs/html/tools/sdk/RELEASENOTES.jd new file mode 100644 index 000000000000..c7ece4230b1b --- /dev/null +++ b/docs/html/tools/sdk/RELEASENOTES.jd @@ -0,0 +1,803 @@ +page.title=SDK Release Notes +@jd:body + +

    This document provides version-specific information about Android SDK +releases.

    + +

    Android SDK

    + +

    The Android SDK has changed! If you've worked with the Android SDK before, +you will notice several important differences:

    + +
      +
    • The SDK downloadable package includes only +the latest version of the Android SDK Tools.
    • +
    • Once you've installed the SDK, you now use the Android SDK and AVD Manager +to download all of the SDK components that you need, such as Android platforms, +SDK add-ons, tools, and documentation.
    • +
    • The new approach is modular — you can install only the components you +need and update any or all components without affecting your development +environment.
    • +
    • In short, once you've installed the new SDK, you will not need to download +an SDK package again. Instead, you will use the Android SDK and AVD Manager to +keep your development environment up-to-date.
    • +
    + +

    Note that if you are currently using the Android 1.6 SDK, you do not +necessarily need to install the new SDK, since your existing SDK already +includes the Android SDK and AVD Manager tool. To develop against Android 2.0.1, +for example, you could just download the Android 2.0.1 platform into your existing +SDK.

    + +

    Release notes for Android platforms and other SDK components are +now available from the "SDK" tab, under "Downloadable SDK Components."

    + + + +

    To get started with the SDK, review the Quick Start summary on the Android SDK download page or read Installing the SDK for detailed +installation instructions.

    + + +

    Android 1.6 SDK, Release 1

    + +

    This SDK provides updates to the development tools and Android system that +you use to create applications for compliant Android-powered devices.

    + +

    Release Overview

    + +

    This SDK release includes several new features for developers. Highlights of the +changes include:

    + +
      +
    • Emulator support for multiple screen sizes/densities, including new +skins.
    • +
    • Android SDK and AVD Manager, a graphical UI to let you manage your +SDK and AVD environments more easily. The tool lets you create and manage +your Android Virtual +Devices and download new SDK packages (such as platform versions and +add-ons) into your environment.
    • +
    • Improved support for test packages in New Project Wizard
    • +
    • The reference documentation now offers a "Filter by API Level" +capability that lets you display only the parts of the API that are actually +available to your application, based on the android:minSdkVersion +value the application declares in its manifest. For more information, see +Android API Levels
    • +
    + +

    For details about the Android platforms included in the SDK — including +bug fixes, features, and API changes — please read the Android 1.6 version notes.

    + +

    Installation and Upgrade Notes

    + +

    If you've been developing an application using an Android 1.1 SDK, you need +to make a few changes to your development environment to migrate to the new SDK. +Tools and documentation are provided to assist you. No changes to the source +code of an existing application should be needed, provided that your application +is not using Android internal structures or APIs.

    + +

    To ensure that your existing application will work properly on a device +running the latest version of the Android platform, you are strongly encouraged +to migrate the application to the new SDK, compile it using the platform +matching the application's original API Level, and run it against the most +current platform.

    + +

    ADT Plugin for Eclipse

    + +

    An updated version of the ADT Plugin for Eclipse is available with the +Android 1.6 SDK. The new version, ADT 0.9.3, provides several new +features, including integrated support for the Android SDK and AVD Manager +and zipalign tool. In addition, the New Project Wizard now +lets you create a test package containing tests for your application. These +features are described in the sections below.

    + +

    If you are developing in Eclipse with ADT and want to get started with the +Android 1.6 SDK, you should download and install a compatible version of the ADT +Plugin (0.9.3 or higher).

    + +

    The new version of ADT is downloadable from the usual remote update site or +is separately downloadable as a .zip archive. For instructions on how to +download the plugin, please see ADT Plugin for Eclipse.

    + +

    Android SDK and AVD Manager

    + +

    The SDK offers a new tool called Android SDK and AVD Manager that lets you +manage your SDK and AVD environments more efficiently.

    + +

    Using the tool, you can quickly check what Android platforms, add-ons, +extras, and documentation packages are available in your SDK environment, what +their versions are, and whether updated versions are available. You can then +download one or more items from remote repositories and install them directly in +your SDK environment. For example, the tool lets you obtain updates to SDK tools +incrementally, as they are made available, without having to wait for the next +SDK release. You can also download Android platform versions into your +environment that were not included in the SDK package.

    + +

    The tool also lets you quickly create new AVDs, manage +their properties, and run a target AVD from a single window.

    + +

    If you are developing in Eclipse with ADT, you can access the Android SDK +and AVD Manager from the Window menu.

    + +

    If you are developing in another IDE, you can access the Android SDK and +AVD Manager through the android command-line tool, located in the +<sdk>/tools directory. You can launch the tool with a graphical UI by +using the android command without specifying any options. You can +also simply double-click the android.bat (Windows) or android (OS X/Linux) file. +You can still use android commands to create and manage AVDs, +including AVDs with custom hardware configurations.

    + +

    Integration with zipalign

    + +

    The Android system offers a performance optimization for installed +application packages whose contained uncompressed files are all aligned on +4-byte boundaries. For these .apks, the system can read the files by mmap'ing +the zip file, rather than by copying all the data out of them. This reduces +the amount of memory used by the application at run time. The SDK includes +a tool called zipalign that you can run against your .apks, to +align them properly and enable them to benefit from this optimization.

    + +

    The ADT Plugin and the Ant build tools both provide integrated support for +aligning your application packages. After you build an .apk, the SDK tools can +sign and then run zipalign against it. The SDK includes the +standalone version of the zipalign tool, so you can run also run it +manually from the command line if you choose.

    + +
      +
    • If you are developing in Eclipse with ADT, support for +zipalign is integrated into the Export Wizard. When you use the +Wizard to export a signed application package, ADT signs and then automatically +runs zipalign against the exported package. If you use the Wizard +to export an unsigned application package, then it will not zipalign the +package because zipalign must be performed only after the APK has been signed. +You must manually sign and zipalign the package after export.
    • +
    • If you are developing using Ant and are compiling in release mode, the +build tools will automatically sign and then zipalign the +application package, provided that you have specified the location of a valid +keystore in the build properties file. If you are compiling in debug mode, the +build tools will sign the package with the debug key and then zipalign +it.
    • +
    • To use zipalign manually, change to the SDK tools directory +and use the command syntax $ zipalign 4 <infile> +<outfile>
    • +
    + +

    In general, note that you must zipalign an application only +after it has been signed, as signing will disrupt the package +alignment.

    + +

    Support for Test Packages in New Project Wizard

    + +

    The New Project Wizard available in the ADT 0.9.3 now lets you add a test +package containing Instrumentation or other classes of tests while you are +creating or importing a new Android application project.

    + +

    New USB Driver for Windows

    + +

    If you are using Windows and want to develop or test your application on an +Android-powered device (such as the T-Mobile G1), you need an appropriate USB +driver. + +

    The Windows version of the Android 1.6 SDK includes a new, WinUSB-based +driver that you can install. The driver is compatible with both 32- and 64-bit +versions of Windows XP and Vista. The driver represents an upgrade from the USB +driver included in previous Android SDKs, although installing the new driver is +not required.

    + +

    If you installed the USB driver from a previous SDK release and it is working +properly, you do not need to upgrade to the new driver. However, we recommend +upgrading if you have had any problems with the older driver or simply want +to upgrade to the latest version.

    + +

    For driver installation or +upgrade instructions, see USB Driver for Windows.

    +

    + +

    Emulator Skins, Android 1.6 Platform

    + +

    The Android 1.6 platform included in the SDK provides a new set of emulator +skins, including:

    + +
      +
    • QVGA — 240 x 320, low density (120 dpi)
    • +
    • HVGA — 320 x 480, medium density (160 dpi)
    • +
    • WVGA800 — 480 x 800, high density (240 dpi)
    • +
    • WVGA854 — 480 x 854, high density (240 dpi)
    • +
    + +

    Besides these defaults, You can also create an AVD that overrides the default +density for each skin, to create any combination of resolution/density (WVGA +with medium density, for instance). To do so, use the android tool +command line to create a new AVD that uses a custom hardware configuration. See +Creating an +AVD for more information.

    + +

    Other Notes and Resolved Issues

    + +
      +
    • This SDK release adds support for Eclipse 3.5 (Galileo) and deprecates +support for Eclipse 3.3 (Europa).
    • +
    • We regret to inform developers that Android 1.6 will not include support +for RFC 2549
    • +
    • The issue preventing adb from recognizing Samsung Galaxy devices (linux SDK +only) has been fixed.
    • +
    + + +

    Android 1.5 SDK, Release 3

    + +

    Provides an updated Android 1.5 system image that includes permissions +fixes, as described below, and a new application — an IME for Japanese +text input. Also provides the same set of developer tools included in the +previous SDK, but with bug fixes and several new features.

    + +

    Permissions Fixes

    + +

    The latest version of the Android platform, deployable to +Android-powered devices, includes fixes to the permissions-checking +in certain areas of the framework. Specifically, the Android system +now properly checks and enforces several existing permissions where it +did not do so in the previous release. Because of these changes in +enforcement, you are strongly encouraged to test your application +against the new Android 1.5 system image included in this SDK, to ensure +that it functions normally.

    + +

    In particular, if your application uses any of the system areas listed below, +you should add the required permissions to the application's manifest and then +test the areas of your code that depend on the permission-protected services. +Even if you believe your application does not use the permissions-protected +services, you should compile and test your application under the latest platform +version to ensure that users will not encounter problems when using your +application.

    + +

    The changes to permissions are as follows:

    + +
      +
    • When an application requests access to device camera (through +android.hardware.camera), the CAMERA permission check is now +properly enforced.
    • +
    • When an application requests access to device audio capture (through +android.media.MediaRecorder), the RECORD_AUDIO permission check is +now properly enforced.
    • +
    + +

    For more information, see the issue described in the oCert advisory +below:

    + +

    http://www.ocert.org/advisories/ocert-2009-011.html

    + +

    Resolved Issues, Changes

    + +
      +
    • The SDK includes a new version of the Google APIs add-on. The add-on +provides an updated com.google.android.maps external library that fixes compile +errors related to certain classes such as GeoPoint. For information about the +Google APIs add-on and the library it provides, see: + +

      http://code.google.com/android/add-ons/google-apis

    • + +
    • The SDK add-on architecture now lets device manufacturers specify a USB +Vendor ID in their add-ons. +
    • The android tool provides a new command that scans SDK add-ons +for their USB Vendor IDs and makes them available to adb (OS X and Linux +versions of the SDK only). The command is android update adb. On +Windows versions of the SDK, a custom USB driver is included that supports the +"Google" and "HTC" Vendor IDs, which allow adb to recognize G1 and HTC +Magic devices. For other devices, contact the device manufacturer +to obtain a USB driver, especially if you have an SDK add-on that defines +a new USB Vendor ID.
    • +
    • The telephony, sensor, and geo fix issues in the emulator are now +fixed.
    • +
    • When you use adb to uninstall an upgraded application, the Android system +now properly restores any permissions that had already been granted to the +previous (downgrade) version of the application
    • +
    + +

    Android 1.5 SDK, Release 2

    + +

    This SDK release provides the same developer tools as the Android 1.5 SDK, +Release 1, but provides an updated Android 1.5 system image that includes a +security patch for the issue described in the oCert advisory below:

    + +

    http://www.ocert.org/advisories/ocert-2009-006.html

    + +

    Android 1.5 SDK, Release 1

    + +

    This SDK provides updates to the development tools and Android system that +you use to create applications for compliant Android-powered devices.

    + +

    Release Overview

    + +

    This SDK release includes many new features for developers. Highlights of the +changes include:

    + +
      +
    • Multiple versions of the Android platform are included (Android 1.1, +Android 1.5). The tools are updated to let you deploy your application +on any platform in the SDK, which helps you ensure forward-compatibility and, +if applicable, backward-compatibility.
    • +
    • Introduces Android +Virtual Devices — (AVD) configurations of options that you +run in the emulator to better model actual devices. Each AVD gets its +own dedicated storage area, making it much easier to work with multiple emulators +that are running concurrently.
    • +
    • Support for SDK add-ons, which extend the +Android SDK to give you access to one or more external Android libraries and/or +a customized (but compliant) system image that can run in the emulator.
    • +
    • The new Eclipse ADT plugin (version 0.9.x) offers new Wizards to let you +create projects targeted for specific Android configurations, generate XML +resources (such as layouts, animations, and menus), generate alternate layouts, +and export and sign your application for publishing.
    • +
    • Improved JUnit support in ADT
    • +
    • Easier profiling of performance
    • +
    • Easier management of localized applications. You can now include or +exclude locale resources when building your APK from a single +Android project.
    • +
    • A new tool called "android" replaces the activitycreator script.
    • +
    + +

    For details about the Android platforms included in the SDK — including +bug fixes, features, and API changes — please read the Android 1.5 version notes.

    + +

    Installation and Upgrade Notes

    + +

    If you've been developing an application using an Android 1.1 SDK, you need +to make a few changes to your development environment to migrate to the new SDK. +Tools and documentation are provided to assist you. No changes to the source +code of an existing application should be needed, provided that your application +is not using Android internal structures or APIs.

    + +

    To ensure that your existing application will work properly on a device +running the latest version of the Android platform, you are strongly encouraged +to migrate the application to the new SDK, compile it using the platform +matching the application's original API Level, and run it against the most +current platform.

    + +

    SDK Add-Ons

    + +

    This version of the SDK introduces support for SDK add-ons, which extend the +Android SDK to give you access to one or more external Android libraries and/or +a customized (but compliant) system image that can run in the emulator. The +purpose of an SDK add-on is to give you a way to develop applications for a +specific actual device (or family of devices) that extends the APIs available to +Android applications through external libraries or system customizations.

    + +

    From the perspective of your Android development environment, an SDK add-on +is similar to any of the Android platform targets included in the SDK — it +includes an external library, a system image, as well as custom emulator skins +and system properties. The add-on differs in that the Android platform it +provides may include customized UI, resources, or behaviors, a different set of +preinstalled applications, or other similar modifications. + +

    The SDK includes a single SDK add-on — the Google APIs add-on. The +Google APIs add-on gives your application access to the com.google.android.maps +external library that is included on many (if not most) Android-powered devices. +The Google APIs add-on also includes a {@link android.location.Geocoder Geocoder} +backend service implementation. For more information, see the "Maps External +Library" section below.

    + +

    Android Virtual Devices (AVDs)

    + +

    The SDK now gives you the capability to compile an application against any +one of several system targets, then run it in the emulator on top of any +compatible system image. There are two types of targets:

    +
      +
    • Targets that represent core Android platform versions.
    • +
    • Targets that are SDK add-ons, which typically provide application access to +one or more external libraries and/or a customized (but compliant) system image +that can run in the emulator. +
    + +

    A new tool called "android" lets you discover what targets and AVDs are +available to use.

    + +

    For more information about AVDs, see Creating and Managing Virtual Devices + +

    Other Notes

    + +

    Maps External Library

    + +

    In previous versions of the SDK, the com.google.android.maps package was +included in the standard Android library and system image. In the Android 1.5 +SDK, that is not the case. The Android 1.5 library and system image do not +include the Maps external library (com.google.android.maps). However, the Maps +external library is available as part of the Google APIs add-on for the Android +SDK, downloadable from this location:

    + +

    http://code.google.com +/android/add-ons/google-apis

    + +

    For your convenience, the Google APIs add-on is included in the SDK.

    + +

    For information about how to register for a Maps API Key, see + +Obtaining a Maps API Key.

    + +

    USB Drivers for Windows

    + +

    If you are using Windows and want to develop or test your application on an +Android-powered device (such as the T-Mobile G1), you need an appropriate USB +driver. For your convenience, the Windows version of the Android SDK includes +these USB drivers that you can install, to let you develop on the device:

    + +
      +
    • USB driver for 32-bit XP and Vista
    • +
    • USB driver for 64-bit Vista only
    • +
    + +

    For driver installation or +upgrade instructions, see USB Driver for Windows.

    +

    + +

    Resolved Issues, Changes

    + +

    Media

    +
      +
    • Updated documentation for {@link android.media.SoundPool +android.media.SoundPool}
    • +
    • {@link android.webkit.WebView} objects no longer automatically save +thumbnails. The {@link android.webkit.WebView#capturePicture() capturePicture()} +method will need to be called manually.
    • +
    + +

    Known Issues

    + +

    Sensor problems in Emulator

    + +
      +
    • If your application uses the Sensor API and you are running it in the +emulator on the Android 1.5 system image, you may experience problems. Your +application may generate ANR messages or crash when using the sensors. The +problem is being investigated.
    • +
    + +

    Other

    + +
      +
    • We regret to inform developers that Android 1.5 will not include support for +the Zilog Z80 processor architecture.
    • +
    + + +

    Android 1.1 SDK, Release 1

    + +

    This SDK provides the development tools and Android system image you need to +create applications for Android-powered devices. Applications developed on this +SDK will be compatible with mobile devices running the Android 1.1 platform. +

    + +

    This release provides an updated system image (Android 1.1), updated +documentation, and the same set of development tools provided in the Android 1.0 +r2 SDK. The updated system image includes bug fixes and some smaller features, +as well as a few minor API changes from the 1.0 version.

    + +

    For details about the Android 1.1 system image included in the SDK — +including bug fixes, features, and API changes — please read the Android 1.1 version notes.

    + +

    App Versioning for Android 1.1

    + +

    If you are using this SDK to build an application that is compatible +only with Android-powered devices running the Android 1.1 platform, +please note that you must set the the +android:minSdkVersion attribute in the application's manifest to +the API Level of Android 1.1 — "2".

    + +

    Specifically, you specify the android:minSdkVersion attribute in +a <uses-sdk> element as a child of +<manifest> in the manifest file. When set, the attribute +looks like this:

    + +
    <manifest>
    +  ...
    +  <uses-sdk android:minSdkVersion="2" />
    +  ...
    +</manifest>
    +
    + +

    By setting android:minSdkVersion in this way, you ensure that +users will only be able to install your application if their devices are running +the Android 1.1 platform. In turn, this ensures that your application will +function properly on their devices, especially if it uses APIs introduced in +Android 1.1.

    + +

    If your application uses APIs introduced in Android 1.1 but does not declare +<uses-sdk android:minSdkVersion="2" />, then it will run properly on +Android 1.1 devices but not on Android 1.0 devices.

    + +

    If your application does not use any new APIs introduced in Android 1.1, you +can indicate Android 1.0 compatibility by removing android:minSdkVersion or +setting the attribute to "1". However, before publishing your application, you +must make sure to compile your application against the Android 1.0 system image +(available in the Android 1.0 SDK), to ensure that it builds and functions +properly for Android 1.0 devices. You should test the application against system +images corresponding to the API Levels that the application is designed to be +compatible with.

    + +

    If you are sure your application is not using Android 1.1 APIs and has no +need to use them, you might find it easier to keep working in the Android 1.0 +SDK, rather than migrating to the Android 1.1 SDK and having to do additional +testing.

    + + +

    ADT Plugin Compatibility

    + +

    For this version of the SDK — Android 1.1 SDK, Release 1 +— the compatible version of the Android Development Tools (ADT) +Plugin for Eclipse is 0.8.0. If you are using a +previous version of ADT, you should update to the latest version for use +with this SDK. For information about how to update your ADT plugin, see +ADT Plugin for Eclipse.

    + +

    Installation and Upgrade Notes

    + +

    If you've been developing an application using an Android 1.0 SDK no +changes to your application are needed. You may want to wipe application +user data (emulator option -wipe-data) when running your +application on the Android 1.1 emulator for the first time.

    + +

    Other Notes

    + +

    MapView API Key

    + +

    com.google.android.maps.MapView is a class that lets you +easily integrate Google Maps into your application. Before you can +access the maps data, you will need to register with the Google Maps +service and receive a Maps API Key, which you then add to your MapView +for authentication to the server.

    + +

    Developers should note that the registration service for MapView is now +active and Google Maps is actively enforcing the Maps API Key requirement. +For information about how to register for a Maps API Key, see + +Obtaining a Maps API Key.

    + +

    USB Drivers for Windows

    + +

    If you using Windows and want to develop or test your application on an +Android-powered device (such as the T-Mobile G1), you need an appropriate USB +driver. For your convenience, the Windows version of the Android SDK includes +these USB drivers that you can install, to let you develop on the device:

    + +
      +
    • USB driver for 32-bit XP and Vista
    • +
    • USB driver for 64-bit Vista only
    • +
    + +

    The USB driver files are located in the +<SDK>/usb_driver directory. For details and +installation instructions, see Connecting Hardware Devices.

    +

    + +

    Resolved Issues, Changes

    + +

    Emulator

    +
      +
    • Emulator now saves the user image in <android>/SDK1.1/
    • +
    + +

    Known Issues

    + +

    JUnit and Eclipse/ADT

    +
      +
    • If you are developing in Eclipse/ADT and want to add JUnit test +classes, you can do so. However, you need to set up a custom JUnit configuration +before your tests will run properly. For detailed information about how to set +up the JUnit configuration, see the troubleshooting topic Running a Junit test class +in Eclipse.
    • +
    + +

    Other

    + +
      +
    • It is not possible to send MMS messages between emulator instances.
    • +
    • In some cases, you may encounter problems when using the browser on an +emulator started with the command-line option -http-proxy.
    • +
    • On the OSX platform, if you manually remove the ~/.android directory +using rm -rf ~/.android, then try to run +the emulator, it crashes. This happens because the emulator fails to create +a new .android directory before attempting to create the child SDK1.0 directory. +To work around this issue, manually create a new .android directory using +mkdir ~/.android, then run the emulator. The emulator +creates the SDK1.0 directory and starts normally.
    • +
    • We regret to inform developers that Android 1.1 will not include support +for ARCNet network interfaces.
    • +
    • The final set of Intent patterns honored by Android 1.0 has not yet been +fully documented. Documentation will be provided in future releases.
    • +
    • In ADT Editor, you can add at most ten new resource values at a time, +in a given res/values/*.xml, using the form in the Android Resources pane. +If you add more than ten, the Android Resources pane will not display the +attributes fields for the additional resource entries. To work around this +problem, you can close the file in the editor and open it again, or you +can edit the resource entries in the XML text mode.
    • +
    • The emulator's battery-control commands (power <option>) +are not working in this release.
    • +
    + + +

    Android 1.0 SDK, Release 2

    + +

    This SDK release includes the Android 1.0 platform and application API. +Applications developed on this SDK will be compatible with mobile devices +running the Android 1.0 platform.

    + +

    This release includes mainly bug fixes, although some smaller features were +added.

    + +

    ADT Plugin Compatibility

    + +

    For this release of the SDK, the compatible version of the Android +Development Tools (ADT) Plugin for Eclipse is 0.8.0. If you are +using a previous version of ADT, you should update to the latest version for use +with this SDK. For information about how to update your ADT plugin, see ADT Plugin for Eclipse.

    + +

    Other Notes

    + +

    T-Mobile G1 Compatibility

    + +

    This version of the SDK has been tested for compatibility with the first +Android-powered mobile device, the T-Mobile +G1.

    + +

    MapView API Key

    + +

    MapView is a class that lets you easily integrate Google Maps into your +application. Before you can access the maps data, you will need to register with +the Google Maps service and receive a Maps API Key, which you then add to your +MapView for authentication to the server.

    + +

    Developers should note that the registration service for MapView is now +active and Google Maps is actively enforcing the Maps API Key requirement. For +information about how to register for a Maps API Key, see http://code.google.com/android/add-ons/google-apis/mapkey.html. +

    + +

    USB Driver for Windows

    +

    If you using Windows and want to develop or test your application on an +Android-powered device (such as the T-Mobile G1), you need an appropriate USB +driver. For your convenience, the Windows version of the Android SDK includes a +USB driver that you can install, to let you develop on the device. The USB +driver files are located in the <SDK>/usb_driver directory. + +

    + +

    Resolved Issues, Changes

    +
      +
    • The android.jar in this SDK release now includes several classes that were +missing from the previous SDK.
    • +
    • The android.R.styleable class and its fields were removed from the public +API, to better ensure forward-compatibility for applications. The constants +declared in android.R.styleable were platform-specific and subject to arbitrary +change across versions, so were not suitable for use by applications. You can +still access the platform's styleable attributes from your resources or code. To +do so, declare a custom resource element using a +<declare-styleable> in your project's res/values/R.attrs +file, then declare the attribute inside. For examples, see +<sdk>/samples/ApiDemos/res/values/attrs.xml. For more information about +custom resources, see Custom +Layout Resources. Note that the android.R.styleable documentation is still +provided in the SDK, but only as a reference of the platform's styleable +attributes for the various elements.
    • +
    • The VM now properly ensures that private classes are not +available to applications through reflection. If you were using reflection +to access private classes in a previous release, you will now get a run-time +error.
    • + +
    • The Settings and Email applications are now included in the SDK and +available in the emulator.
    • +
    • We regret to inform developers that SDK 1.0_r2 does not support MFM, RLL, +or Winchester hard disk drives.
    • +
    • In the emulator, the control key for enabling/disabling trackball mode +is changed from Control-T to F6. You can also enter trackball mode temporarily +using the Delete key. While the key is pressed, you can send trackball events.
    • +
    + +

    Unless otherwise noted, Known Issues from the previous SDK release also apply +to this release.

    + + + + + + +

    Android 1.0 SDK, Release 1

    + +

    This SDK release is the first to include the Android 1.0 platform and application API. Applications developed on this SDK will be compatible with mobile devices running the Android 1.0 platform, when such devices are available.

    + +

    This release includes mainly bug fixes, although some smaller features were added. The Android 1.0 also includes several API changes from the 0.9 version. For those porting from the M5 release, the SDK also includes the legacy changes overview and API Differences Reports. See the current Overview of Changes for more information.

    + +

    ADT Plugin Compatibility

    + +

    For this version of the SDK — Android 1.0 SDK, Release 1 — the compatible version of the Android Development Tools (ADT) Plugin for Eclipse is 0.8.0. If you are using a previous version of ADT, you should update to the latest version for use with this SDK. For information about how to update your ADT plugin, see Upgrading the SDK.

    + +

    Installation and Upgrade Notes

    + +

    If you've been developing an application using a previous SDK version and you want the application to run on Android-powered mobile devices, you must port the application to the Android 1.0 SDK. Please see Upgrading the SDK for detailed instructions on how to make the transition to this release. Be sure to wipe application user data (emulator option -wipe-data) when running your application on the Android 1.0 SDK emulator.

    + +

    Other Notes

    + +

    MapView API Key

    + +

    MapView is a class that lets you easily integrate Google Maps into your application. Before you can access the maps data, you will need to register with the Google Maps service and receive a Maps API Key, which you then add to your MapView for authentication to the server.

    + +

    Currently, the registration service for MapView is not yet active and Google Maps is not yet enforcing the Maps API Key requirement. However, note that the registration service will be activated soon, so that MapViews in any application deployed to a mobile device will require registration and a valid Maps API Key.

    + +

    As soon as the registration service becomes available, we will update the page at http://code.google.com/android/add-ons/google-apis/mapkey.html with details about how and where to register. Please check that page periodically for registration information, if you are using a MapView.

    + + +

    Resolved Issues, Changes

    + +

    Emulator

    +
      +
    • Emulator now saves the user image in <android>/SDK1.0/
    • +
    • Fixed EsounD-related freezes on Linux.
    • +
    • Fixed the documentation in -help-audio. '-audio list' doesn't work, one + needs to call -help-audio-out and -help-audio-in to get the list of valid + audio backends.
    • +
    • Fixed scrollwheel Dpad emulation in rotated mode. before that, using the + scroll-wheel would always generated Dpad Up/Down events, even when in + landscape mode.
    • + +
    • Several Obsolete command options were removed.
    • +
    • Setting the network speed through the console or the -netspeed option will + properly modify the connectivity icon on the device.
    • +
    • Setting the GSM voice registration state to 'roaming' in the console will + properly modify the voice icon on the device
    • +
    + +

    SQLite

    +
      +
    • SQLite is now included in the SDK package on all platforms.
    • +
    + +

    Other

    + +
      +
    • It is not possible to send MMS messages between emulator instances.
    • +
    • In some cases, you may encounter problems when using the browser on an +emulator started with the command-line option -http-proxy.
    • + +
    • We regret to inform developers that Android 1.0 will not include support for +dot-matrix printers.
    • +
    • On the OSX platform, if you manually remove the ~/.android directory +using rm -rf ~/.android, then try to run +the emulator, it crashes. This happens because the emulator fails to create +a new .android directory before attempting to create the child SDK1.0 directory. +To work around this issue, manually create a new .android directory using +mkdir ~/.android, then run the emulator. The emulator +creates the SDK1.0 directory and starts normally.
    • +
    • The final set of Intent patterns honored by Android 1.0 has not yet been +fully documented. Documentation will be provided in future releases.
    • +
    • In ADT Editor, you can add at most ten new resource values at a time, +in a given res/values/*.xml, using the form in the Android Resources pane. +If you add more than ten, the Android Resources pane will not display the +attributes fields for the additional resource entries. To work around this +problem, you can close the file in the editor and open it again, or you +can edit the resource entries in the XML text mode.
    • +
    • The emulator's battery-control commands (power <option>) +are not working in this release.
    • + +
    + diff --git a/docs/html/tools/sdk/addons.jd b/docs/html/tools/sdk/addons.jd new file mode 100644 index 000000000000..8c5e1ed1c745 --- /dev/null +++ b/docs/html/tools/sdk/addons.jd @@ -0,0 +1,9 @@ +page.title=SDK Add-Ons + +@jd:body + + + +

    A page that lists SDK addons and links to release notes. Links to dashboards etc.

    + + diff --git a/docs/html/tools/sdk/adt-notes.jd b/docs/html/tools/sdk/adt-notes.jd new file mode 100644 index 000000000000..291b543f13fb --- /dev/null +++ b/docs/html/tools/sdk/adt-notes.jd @@ -0,0 +1,5 @@ +page.title=ADT Plugin for Eclipse +sdk.redirect=true +sdk.redirect.path=eclipse-adt.html + +@jd:body diff --git a/docs/html/tools/sdk/adt_download.html b/docs/html/tools/sdk/adt_download.html new file mode 100644 index 000000000000..5ba2ef5be745 --- /dev/null +++ b/docs/html/tools/sdk/adt_download.html @@ -0,0 +1,10 @@ + + + +Redirecting... + + +

    You should be redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/tools/sdk/download.jd b/docs/html/tools/sdk/download.jd new file mode 100644 index 000000000000..af256096139c --- /dev/null +++ b/docs/html/tools/sdk/download.jd @@ -0,0 +1,93 @@ +page.title=Download an Archived Android SDK +hide_license_footer=true + +@jd:body + + + +
    +

    Please carefully review the Android SDK License Agreement before downloading the SDK. +The License Agreement constitutes a contract between you and Google with respect to your use of the +SDK.

    +

    Note: You must agree to this license agreement in order to +download one of the archived SDKs, because these SDK packages contain Google software (whereas, the +current SDK packages do not require a +license agreement, because they contain only the open sourced SDK tools).

    + + + +

    + + +

    +

    + +

    +

    + +

    +
    + + + + + + + + + + + + diff --git a/docs/html/tools/sdk/eclipse-adt.jd b/docs/html/tools/sdk/eclipse-adt.jd new file mode 100644 index 000000000000..ac200b69789f --- /dev/null +++ b/docs/html/tools/sdk/eclipse-adt.jd @@ -0,0 +1,1178 @@ +page.title=ADT Plugin + +@jd:body + +
    +
    + +

    See also

    +
      +
    1. Installing the Eclipse +Plugin
    2. +
    + +
    +
    + +

    Android Development Tools (ADT) is a plugin for the Eclipse IDE +that is designed to give you a powerful, integrated environment in which +to build Android applications.

    + +

    ADT extends the capabilities of Eclipse to let you quickly set up new Android +projects, create an application UI, add packages based on the Android +Framework API, debug your applications using the Android SDK tools, and even +export signed (or unsigned) {@code .apk} files in order to distribute your application.

    + +

    Developing in Eclipse with ADT is highly recommended and is the fastest way +to get started. With the guided project setup it provides, as well as tools +integration, custom XML editors, and debug output pane, ADT gives you an +incredible boost in developing Android applications.

    + +

    This document provides step-by-step instructions on how to download the ADT +plugin and install it into your Eclipse development environment. Note that +before you can install or use ADT, you must have compatible versions of both the +Eclipse IDE and the Android SDK installed. For details, make sure to read Installing the ADT Plugin, below.

    + +

    If you are already using ADT, this document also provides instructions on +how to update ADT to the latest version or how to uninstall it, if necessary. +

    + +

    For information about the features provided by the ADT plugin, such as code +editor features, SDK tool integration, and the graphical layout editor (for drag-and-drop layout +editing), see the Android Developer Tools +document.

    + + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the ADT Plugin, as denoted by revision number.

    + +

    For a summary of all known issues in ADT, see http://tools.android.com/knownissues.

    + + + + + + +
    + + +ADT 18.0.0 (April 2012) +
    +
    +
    Dependencies:
    + +
    +
      +
    • Java 1.6 or higher is required for ADT 18.0.0.
    • +
    • Eclipse Helios (Version 3.6.2) or higher is required for ADT 18.0.0.
    • +
    • ADT 18.0.0 is designed for use with SDK Tools + r18. If you haven't already installed SDK Tools r18 into your SDK, use the Android SDK + Manager to do so.
    • +
    +
    + +
    Bug fixes:
    +
    +
      +
    • Fixed problem where exporting release package does not recompile libraries in release + mode. + (Issue 27940)
    • +
    +
    + +
    + +
    +
    + + +
    + + +ADT 17.0.0 (March 2012) +
    +
    +
    Dependencies:
    + +
    +
      +
    • Java 1.6 or higher is required for ADT 17.0.0.
    • +
    • Eclipse Helios (Version 3.6.2) or higher is required for ADT 17.0.0.
    • +
    • ADT 17.0.0 is designed for use with SDK Tools + r17. If you haven't already installed SDK Tools r17 into your SDK, use the Android SDK + Manager to do so.
    • +
    +
    + +
    General improvements:
    +
    +
      +
    • New build features +
        +
      • Added feature to automatically setup JAR dependencies. Any {@code .jar} files in the + {@code /libs} folder are added to the build configuration (similar to how the Ant build + system works). Also, {@code .jar} files needed by library projects are also automatically + added to projects that depend on those library projects. + (more + info)
      • +
      • Added a feature that allows you to run some code only in debug mode. Builds now +generate a class called {@code BuildConfig} containing a {@code DEBUG} constant that is +automatically set according to your build type. You can check the ({@code BuildConfig.DEBUG}) +constant in your code to run debug-only functions.
      • +
      • Added support for custom views with custom attributes in libraries. Layouts using +custom attributes must use the namespace URI {@code http://schemas.android.com/apk/res-auto} instead +of the URI that includes the app package name. This URI is replaced with the app specific one at +build time.
      • +
      +
    • +
    • Improved Lint features. See the SDK Tools r17 +release notes.
    • +
    • Improved the Lint user interface +
        +
      • Added Run Lint toolbar action with a dropdown menu for selecting +specific (or all) projects, clearing results and other actions.
      • +
      • Updated the results window to be organized as a tree rather than a flat list. Each +issue type has a single top level item, which makes it easier to quickly scan through the reported +issues and narrow down to the issues you are most interested in.
      • +
      • Added many new toolbar actions to the results window, including expand/collapse, +ignore in file, ignore in project, ignore everywhere, show options, and configure columns.
      • +
      • Added new column options for the Lint Warnings tab, such as +category, priority, project, file and line. The column selection (as well as the column sizes) are +persisted. You can also click on columns to sort by those values.
      • +
      • Added Enable All and Disable All buttons to the Lint Options dialog, and a search +filter textbox to filter by issue id, summary and severity.
      • +
      +
    • +
    • Added Quick Outline for XML editors (Ctrl-O, Command-O). This feature shows the structure +of the current file including icons and ids, lets you filter and quickly jump to specific ids.
    • +
    • Updated the resource chooser to shows the resolved value for resources. For example, +when selecting {@code @string/hello} the chooser displays a resolved value such as "Hello World"). +The resource chooser also now allows you to edit the chosen value directly.
    • +
    • Updated Layout Editor so that it does not assign default ids to layouts, includes and +merge tags. This behavior tended to pollute the namespace with a lot of unused resources since +layouts are not usually manipulated via code, or referenced from XML. (The RelativeLayout editor +automatically assigns ids to views without ids when pointing to them.)
    • +
    • Added ability to export screenshots from the Layout Editor
    • +
    +
    + +
    Bug fixes:
    +
    +
      +
    • Fixed problem using Layout Editor with {@link android.widget.SlidingDrawer} which could + not be dragged into the layout on some platforms.
    • +
    • Fixed preview rendering for {@link android.widget.SlidingDrawer} and + {@link android.widget.TabHost}. + (Issue 23022).
    • +
    • Fixed issues that could prevent layout rendering due to unresolvable resources. + (Issue 21046, + Issue 21051)
    • +
    • Fixed a bug in resource chooser which made some types of framework resources impossible to +select. (Issue 20589)
    • +
    • Fixed a bug in the formatter where a certain whitespace pattern could result in a + non-space character getting deleted. + (Issue 23940)
    • +
    • Fixed a locale bug affecting Turkish locales in particular. + (Issue 23747)
    • +
    • Fixed issue where dex complains about duplicate classes in cases where a Library + Project depends on the same jar files or Java-only projects.
    • +
    • Fixed issue where test projects had to independently reference the library projects used + by an app project. Now referencing only the app project is enough.
    • +
    +
    + +
    + +
    +
    + +
    + + +ADT 16.0.1 (December 2011) +
    +
    +
    Dependencies:
    + +
    +
      +
    • Eclipse Helios (Version 3.6) or higher is required for ADT 16.0.1.
    • +
    • ADT 16.0.1 is designed for use with SDK Tools + r16. If you haven't already installed SDK Tools r16 into your SDK, use the Android SDK + Manager to do so.
    • +
    +
    + +
    Bug fixes:
    +
    +
      +
    • Fixed build issue where the 9-patch could be packaged as normal bitmap in some cases.
    • +
    • Fixed minor issues in the Lint + tool.
    • +
    • Fixed minor issues in the SDK Manager.
    • +
    +
    +
    + +
    +
    + + +
    + + +ADT 16.0.0 (December 2011) +
    +
    +
    Dependencies:
    + +
    +
      +
    • Eclipse Helios (Version 3.6) or higher is required for ADT +16.0.0.
    • +
    • ADT 16.0.0 is designed for use with SDK Tools r16. If you haven't already installed SDK Tools +r16 into your SDK, use the Android SDK Manager to do so.
    • +
    +
    + +
    General improvements:
    +
    +
      +
    • Added Lint tool to detect common errors in Android projects. (more info)
    • +
    +
    +
    + +
    +
    + + +
    + + +ADT 15.0.1 (November 2011) +
    +
    +
    Dependencies:
    + +
    ADT 15.0.1 is designed for use with SDK Tools r15. + If you haven't already installed SDK Tools r15 into your SDK, use the Android SDK Manager to + do so.
    + +
    Bug fixes:
    +
    +
      +
    • Fixed how source files are attached to library project .jar files.
    • +
    • Fixed how the bin/ folder for library projects are refreshed. This ensures that parent projects pick up changes in library projects.
    • +
    • Fixed how a parent project's library container is updated when a library project is recompiled. This ensures that parent projects are + recompiled when code in a library project changes.
    • +
    • Fixed how res/ folders are checked in library projects. This ensures that all res folders are properly included + even if Eclipse is not aware of them due to refresh issues.
    • +
    • Fixed issue that prevented aapt from running when editing certain XML files.
    • +
    • Fixed minor XML formatting issues.
    • +
    +
    +
    + +
    +
    + + + +
    + + +ADT 15.0.0 (October 2011) +
    +
    + +
    Dependencies:
    + +
    ADT 15.0.0 is designed for use with SDK Tools r15. +If you haven't already installed SDK Tools r15 into your SDK, use the Android SDK Manager to +do so.
    + +
    Bug fixes:
    +
    +
      +
    • Fixed build issue when using Renderscript in projects that target API levels 11-13 + (Issue 21006).
    • +
    • Fixed issue when creating projects from existing source code.
    • +
    • Fixed issues in the SDK Manager + (Issue 20939, + Issue 20607).
    • +
    • Fixed scrolling issue in the new Logcat panel of DDMS.
    • +
    +
    +
    + +
    +
    + +
    + + +ADT 14.0.0 (October 2011) +
    +
    + +
    Dependencies:
    + +
    ADT 14.0.0 is designed for use with SDK Tools r14. +If you haven't already installed SDK Tools r14 into your SDK, use the Android SDK Manager to +do so.
    + +
    Build system:
    +
    +
      +
    • Changed default.properties to project.properties and + build.properties to ant.properties. ADT automatically + renames these files, if necessary, when you open a project in Eclipse.
    • +
    • Changed how library projects are built in Eclipse.
    • +
    • Changed output of javac from bin/ to bin/classes + in Eclipse.
    • +
    • Improved incremental builds so that resource compilation runs less frequently. Builds no + longer run when you edit strings or layouts (unless you add a new id) and no longer + run once for each library project.
    • +
    • Introduced a "PNG crunch cache" that only runs on modified PNG files, instead of + crunching all existing PNG files, all the time.
    • +
    • Modified resource compilation so it no longer happens for normal save operations. It only + happens when running or debugging (the build option that lets you disable the packaging + step, which was introduced in ADT 12, is now on by default.)
    • +
    +

    For a complete overview of the build system changes and what you need to do to support them, +see the Android Tools Project +site.

    +
    + +
    General improvements:
    +
    +
      + + +
    • Added a Welcome Wizard to help with the initial setup of the Android +development environment (more +info).
    • +
    • Integrated the Android Asset Studio, which helps you create icons for things +like the launcher, menus, and tabs. (more +info).
    • +
    • Revamped the Logcat view and added support to display and filter logs by + application names as well as PIDs (more info).
    • +
    • Revamped the SDK Manager UI (more +info).
    • +
    • Revamped the New Project and the New XML File wizards to have +multiple pages. Sample projects are now copied into the workspace such that they can be modified +and deleted without affecting the master copy +(more info).
    • +
    • Removed the dependency on Eclipse GEF.
    • +
    +
    + +
    XML and Java editors:
    +
    +
      +
    • Added a new XML formatter that formats all XML files according to the + standard Android coding style. The formatter can also reorder + attributes to follow a recommended order and processes any changes made in the Layout editor. +(more info).
    • +
    • Added the "Go to Matching" (Ctrl-Shift-P) feature, which lets you jump +between opening and closing tags in XML files.
    • +
    • Added support for the "Select Enclosing Element" feature on Mac.
    • +
    • Added a Quickfix for extracting Strings when the caret is inside a String (see +more).
    • +
    • Improved "smart indent", which allows automatic indentation and un-indentation + when pressing the Return key in XML editors (more info).
    • + +
    +
    + +
    Layout editor:
    +
    +
      +
    • Added tooltip feedback for dragging and resizing operations. For + example, when dragging in a relative layout, the proposed + constraints are shown. When resizing, the new dimensions are + shown (more +info).
    • +
    • Added the ability to suppress rendering fidelity warnings (more info).
    • +
    • Added "Remove Container" visual refactoring that removes the + children of a container up to the top level and transfers + namespace and layout attributes if necessary (more info).
    • +
    • Added pull-right menus to the context menu for accessing + properties of the parents, which is useful when the children fully + cover the parent and make it hard to select on their own.
    • +
    • Improved access to properties in the context menu. The most + frequently set attributes for each view are listed at the top of + the menu. The Properties menu offers access to the most + recently set attributes, attributes organized by their defining + view, and layout attributes only or all attributes alphabetically (more info).
    • +
    +
    + +
    Bug fixes:
    +
    Fixed many bugs and added minor improvements, in +particular some critical bug fixes on +Linux.
    + +
    +
    + + + +
    + + +ADT 12.0.0 (July 2011) +
    +
    + +
    Dependencies:
    + +
    ADT 12.0.0 is designed for use with SDK Tools r12. If you haven't +already installed SDK Tools r12 into your SDK, use +the Android SDK Manager to do so.
    + +
    Visual Layout Editor:
    +
    +
      +
    • New RelativeLayout drop support with guideline suggestions for + attachments and cycle prevention + (more info).
    • +
    • Resize support in most layouts along with + guideline snapping to the sizes dictated by wrap_content and match_parent. + In LinearLayout, sizes are mapped to weights instead of pixel widths. + (more info).
    • +
    • Previews of drawables and colors in the resource chooser dialogs + (more info).
    • +
    • Improved error messages and links for rendering errors including + detection of misspelled class names + (more info).
    • +
    +
    + +
    Build system:
    +
    +
      +
    • A new option lets you disable the packaging step in the automatic + builders. This improves performance when saving files by not + performing a full build, which can take a long time for large projects. + If the option is enabled, the APK is packaged when the + application is deployed to a device or emulator or when the + release APK is exported (more info).
    • +
    +
    + +
    Bug fixes:
    +
    Many bug fixes are part of this release +(more info).
    + +
    +
    + + +
    + + +ADT 11.0.0 (June 2011) +
    + +
    + +
    Dependencies:
    + +
    ADT 11.0.0 is designed for use with SDK Tools r11. If you haven't +already installed SDK Tools r11 into your SDK, use the Android SDK Manager to do +so.
    + +
    Visual Refactoring:
    +
    +
      +
    • "Extract Style" feature pulls out style-related attributes from your layout and extracts +them as a new style defined in {@code styles.xml} (more info).
    • +
    • "Wrap in Container" feature lets you select a group of views then surround them + in a new layout (a new view group, such as a LinearLayout), and transfers namespace and layout + parameters to the new parent (more +info).
    • +
    • "Change Layout" feature changes layouts from one type + to another, and can also flatten a layout hierarchy (more +info).
    • +
    • "Change Widget Type" feature changes the type of the + selected views to a new type. Also, a new selection context menu + in the visual layout editor makes it easy to select siblings as + well as views anywhere in the layout that have the same type (more +info).
    • +
    • "Extract as Include" feature finds identical collections of views + in other layouts and offers to combine them into a single layout that you can then include in + each layout (more info).
    • +
    • Quick Assistant in Eclipse can be invoked + from the XML editor (with Ctrl-1) to apply any of the above + refactorings (and Extract String) to the current selection (more info).
    • +
    +
    + +
    Visual Layout Editor:
    +
    +
      +
    • This is the update to the layout editor you've been waiting for! It includes (almost) all +the goodies demonstrated at Google I/O. Watch +the video on YouTube.
    • +
    • The palette now supports different configurations for supported widgets. That is, a single +view is presented in various different configurations that you can drag into your layout. For +example, there is a Text Fields palette category where you can drag an {@link +android.widget.EditText} widget in as a password field, an e-mail field, a phone field, or other +types of text boxes. Similarly, {@link android.widget.TextView} widgets are preconfigured +with large, normal and small theme sizes, and {@link android.widget.LinearLayout} elements are +preconfigured in horizontal and vertical configurations (more info).
    • +
    • The palette supports custom views. You can pick up any custom + implementations of the View class you've created in your project or from included libraries and +drag them into your layout (more info).
    • +
    • Fragments are available in the palette for placement in your layout. In the tool, you can +choose which layout to show rendered for a given fragment tag. Go to declaration works for fragment +classes (more info).
    • +
    • The layout editor automatically applies a "zoom to fit" for newly + opened files as well as on device size and orientation changes to + ensure that large layouts are always fully visible unless you + manually zoom in.
    • +
    • You can drop in an {@code <include>} element from the palette, which will pop up + a layout chooser. When you select the layout to include, it is added with an {@code +<include>}. Similarly, dropping images or image buttons will pop up image + resource choosers (more info).
    • +
    • The configuration chooser now applies the "Render Target" and + "Locale" settings project wide, making it trivial to check the + layouts for different languages or render targets without having + to configure these individually for each layout.
    • +
    • The layout editor is smarter about picking a default theme to + render a layout with, consulting factors like theme registrations + in the manifest, the SDK version, and other factors.
    • +
    • The layout editor is smarter about picking a default configuration to render a layout +with, defaulting to the currently visible configuration in the previous file. It also considers the +SDK target to determine whether to default to a tablet or phone screen size.
    • +
    • Basic focus support. The first text field dropped in a layout is assigned focus, and there +are Request Focus and Clear Focus context menu items on text +fields to change the focus.
    • +
    +
    + +
    XML editors:
    +
    +
      +
    • Code completion has been significantly improved. It now works + with {@code <style>} elements, completes dimensional units, + sorts resource paths in values based on the attribute name, and more. There are also many fixes to +handle text replacement (more info).
    • +
    • AAPT errors are handled better. They are now underlined for the + relevant range in the editor, and a new quickfix makes it trivial + to create missing resources.
    • +
    • Code completion for drawable, animation and color XML files (more +info).
    • +
    +
    + +
    DDMS:
    +
    +
      +
    • "New Folder" action in the File Explorer.
    • +
    • The screenshot dialog will add timestamps to the filenames and preserve the orientation on +snapshot refresh.
    • +
    +
    + +
    General notes:
    +
    +
      +
    • TraceView supports zooming with the mouse-wheel in the timeline.
    • +
    • The New Android Project wizard now supports Eclipse working sets.
    • +
    +
    +
    +

    More information about tool changes are available on the Android Tools Project Site.

    +
    +
    + + + + + +
    + + +ADT 10.0.1 (March 2011) +
    + +
    + +
    Dependencies:
    + +
    ADT 10.0.1 is designed for use with SDK Tools r10. If you haven't +already installed SDK Tools r10 into your SDK, use the Android SDK Manager to do +so.
    + +
    General notes:
    +
    +
      +
    • Temporary work-around to resolve the rare cases in which the layout editor will +not open.
    • +
    • Fix issue in which ADT 10.0.0 would install on Eclipse 3.4 and lower, even though ADT +requires Eclipse 3.5 or higher (as of 10.0.0).
    • +
    +
    +
    +
    +
    + + + +
    + + +ADT 10.0.0 (February 2011) +
    + +
    + +
    Dependencies:
    + +
    ADT 10.0.0 is designed for use with SDK Tools r10. If you haven't +already installed SDK Tools r10 into your SDK, use the Android SDK Manager to do +so.
    + +
    General notes:
    +
    +
      +
    • The tools now automatically generate Java Programming Language source files (in the gen/ directory) and + bytecode (in the res/raw/ directory) from your .rs files.
    • +
    • A Binary XML editor has been added (details).
    • +
    • Traceview is now integrated into the Eclipse UI (details).
    • +
    • The "Go To Declaration" feature for XML and .java files quickly show all the matches in the project + and allows you jump to specific items such as string translations or onClick handlers + (details).
    • +
    • The Resource Chooser can create items such as dimensions, integers, ids, and booleans + (details).
    • +
    • Improvements to the Visual Layout Editor: +
        +
      • A new Palette with categories and rendering previews + (details).
      • +
      • A Layout Actions bar that provides quick access to common layout operations + (details).
      • +
      • When the Android 3.0 rendering library is selected, layouts render more like they do on devices. + This includes rendering of status and title bars to more accurately reflect the actual + screen space available to applications + (details).
      • +
      • Zoom improvements such as fit to view, persistent scale, and keyboard access. + (details).
      • +
      • Further improvements to <merge> layouts, as well as layouts with gesture overlays + (details).
      • +
      • Improved rendering error diagnostics.
      • +
      +
    • +
    +
    +
    +
    +
    + +
    + + +ADT 9.0.0 (January 2011) +
    + +
    + +
    Dependencies:
    + +
    ADT 9.0.0 is designed for use with SDK Tools r9. If you haven't +already installed SDK Tools r9 into your SDK, use the Android SDK Manager to do +so.
    + +
    General notes:
    +
    +
      +
    • "Go To Declaration" hyperlink support: You can jump directly from code references (such as + R.id.main) to the corresponding XML declaration, or from XML attributes (such as + @string) to the corresponding resource definition, or from manifest XML + registrations to activities and services.
    • +
    • Improvements were made to name refactoring.
    • +
    • AVDs now automatically save their state, so they can restart almost instantly. You can enable this feature when + creating an AVD or by editing an AVD with the AVD Manager.
    • +
    • Improvements to the Visual Layout Editor: +
        +
      • Support for rendering targets: You can now choose an arbitrary Android platform to + render the current page, regardless of the project's minimum platform. This makes it + easy to verify the layout and appearance of your activity on different versions of + the platform. +
      • +
      • Improved support for empty and nested layouts: Dragging items over nested and + invisible layouts automatically enlarges and highlights these layouts, so that they + can receive drops. +
      • +
      • XML formatting improvements: The editor generates cleaner XML and you can now enable + XML auto-formatting in the Preferences menu.
      • +
      • Improved Outline labels: The Outline tab now displays additional information about each + View. Textual Views display a snippet of the actual text. Views with a source + (such as ImageView) displays the resource name. Included Views display the name of the View. +
      • +
      • When you right click a View in the Layout Editor, + the context menu now contains Edit ID... and Edit Text... + items. The Properties... context menus now list all of the properties and + provide a way to edit them + (Details). +
      • +
      • The layout editor now properly handles + <include> + and <merge> + tags (Details).
      • +
      • "Extract as Include" refactoring: The Layout Editor has a new refactoring that allows + you to select one or more views in a layout, and extract it into a separate layout + (Details).
      • +
      • Improved diagnostics for class loading and rendering errors: Class loading and rendering + error messages are more useful and provide better information about the root cause of the + error.
      • +
      • Improved error handling to prevent drag and reordering operations from adding children + into an {@link android.widget.AdapterView}.
      • +
      • Outline reordering: Reordering your views in the Outline tab is much easier + (Details).
      • +
      • Fix for keybinding bug where keyboard shortcuts did not work (Issues + 13231 and + 13134).
      • +
      • Fix for problems with Custom layout attribute menu (Issue + 13134).
      • +
      • Automatic configuration for various view types: Certain views have properties configured + by default. For example, the width of an {@link android.widget.EditText} object is set to + match_parent when added to a vertical {@link android.widget.LinearLayout} + or a default image is added to an {@link android.widget.ImageButton}.
      • +
      • Previews during dragging: Dragging from the palette or dragging within the layout editor + now shows live previews of the dragged item.
      • +
      • Navigation improvements: In the Layout Editor, double-clicking Views jumps to the + corresponding XML element. In the Outline view, double-clicking opens the Properties view.
      • +
      • The editor has Honeycomb style animation preview support.
      • +
      • Improved rendering support for various Views (such as TabHosts and SlidingDrawers) in + Honeycomb (Issues 3162 + and 13092).
      • +
      • Included layouts can be rendered and edited in the context of the layouts that include + them. From a layout using an + <include> tag, double-clicking on the + + <include> element edits the referenced layout in the context of the + current layout. Additionally, when editing a layout that is included by other layouts, + you can quickly change between context layouts, by right clicking in the editor and choosing + Show included in.... This feature is only available in Honeycomb.
      • +
      +
    • +
    • This release fixes many other bugs, but the most important ones are listed below: +
        +
      • Fixed issue that prevented launching debug builds on productions devices when + debuggable=true was not set in the Android manifest.
      • +
      • The LogCat view in DDMS properly handles UTF-8 characters.
      • +
      • The SDK Manager is more reliable on Windows + (Details).
      • +
      • A JUnit initialization bug that prevented you from working with JUnit tests was fixed + (Issue 12411).
      • +
      +
    • +
    +
    +
    +
    +
    + + + + +
    + + +ADT 8.0.1 (December 2010) +
    + +
    + +
    Dependencies:
    + +

    ADT 8.0.1 is designed for use with SDK Tools r8. If you haven't +already installed SDK Tools r8 into your SDK, use the Android SDK Manager to do +so.

    + +
    General notes:
    +
    +
      +
    • This is a quick follow-up to ADT 8.0.0 to fix some bugs.
    • +
    • Fixes an issue in which projects failed to compile, citing a dex error.
    • +
    • Better ProGuard error reporting when exporting applications for release.
    • +
    +

    Also see the recent release notes for 8.0.0, below.

    +
    +
    +
    +
    + + +
    + + +ADT 8.0.0 (December 2010) +
    + +
    + +
    Dependencies:
    + +

    ADT 8.0.0 is designed for use with SDK Tools r8. If you haven't +already installed SDK Tools r8 into your SDK, use the Android SDK Manager to do +so.

    + +
    General notes:
    +
    +
      +
    • New version number scheme that follows the SDK Tools revision number. The major version +number for your ADT plugin should now always match the revision number of your SDK Tools. For +example, ADT 8.x is for SDK Tools r8.
    • +
    • Support for true debug build. You no longer need to change the value of the + debuggable attribute in the Android Manifest. +

      Incremental builds automatically insert debuggable="true", but if you perform + "export signed/unsigned application package", ADT does not insert it. + If you manually set debuggable="true" in the manifest file, then release builds will + actually create a debug build (it does not remove it if you placed it there).

    • +
    • Automatic ProGuard support in + release builds. For it to work, you need to have a proguard.config + property in the default.properties file that points to a ProGuard config file.
    • +
    • Completely rewritten Visual Layout Editor. (This is still a work in progress.) Now includes: +
        +
      • Full drag and drop from palette to layout for all Layout classes.
      • +
      • Move widgets inside a Layout view, from one Layout view to another and from one layout file to another.
      • +
      • Contextual menu with enum/flag type properties.
      • +
      • New zoom controls.
      • +
    • +
    • New HierarchyViewer plug-in integrated in Eclipse.
    • +
    • Android launch configurations don't recompile the whole workspace on launch anymore.
    • +
    • android.jar source and javadoc location can now be configured.
    • +
    +
    +
    +
    +
    + + +
    + + +ADT 0.9.9 (September 2010) +
    + +
    + +
    Dependencies:
    + +

    ADT 0.9.9 replaces ADT 0.9.8 and is designed for use with SDK Tools r7 +and later. ADT 0.9.9 includes the ADT 0.9.8 features as well as an important +bugfix, so we recommend that you upgrade as soon as possible. If you haven't +already installed SDK Tools r7 into your SDK, use the Android SDK Manager to do +so.

    + +
    General notes:
    +
    +
      +
    • Fixes a problem in project import, in which source files were deleted in some cases.
    • +
    • Includes all other ADT 0.9.8 features (see below).
    • +
    +
    +
    +
    +
    + +
    + + +ADT 0.9.8 (September 2010) +
    + + + + + +
    + +
    Dependencies:
    + +

    ADT 0.9.8 is now deprecated. Please use ADT 0.9.9 instead.

    + +
    General notes:
    +
    +
      +
    • Adds a new Action, "Rename Application Package", to the Android Tools +contextual menu. The Action does a full application package refactoring. +
    • Adds support for library projects that don't have a source folder +called src/. There is now support for any number of source folders, +with no name restriction. They can even be in subfolder such as +src/java. If you are already working with library projects created +in ADT 0.9.7, see Migrating +library projects to ADT 0.9.8 for important information about moving +to the new ADT environment.
    • +
    • Adds support for library projects that depend on other library +projects.
    • +
    • Adds support for additional resource qualifiers: +car/desk, night/notnight and +navexposed/navhidden.
    • +
    • Adds more device screen types in the layout editor. All screen +resolution/density combinations listed in the Supporting +Multiple Screens are now available.
    • +
    • Fixes problems with handling of library project names that +contain characters that are incompatible with the Eclipse path variable. +Now properly sets up the link between the main project and the library +project.
    • +
    +
    +
    +
    +
    + + +
    + + +ADT 0.9.7 (May 2010) +
    + +
    +
    Library projects:
    +
    +

    The ADT Plugin now supports the use of library projects during +development, a capability that lets you store shared Android application +code and resources in a separate development project. You can then reference the +library project from other Android projects and, at build time, the tools +compile the shared code and resources as part of the dependent applications. +More information about this feature is available in the Creating and Managing Projects document.

    +

    If you are not developing in Eclipse, SDK Tools r6 provides the equivalent library +project support through the Ant build system.

    +
    +
    +
    +
    + + +
    + + +ADT 0.9.6 (March 2010) +
    + +
    +
    Dependencies:
    + +

    ADT 0.9.6 is designed for use with SDK Tools r5 and later. Before +updating to ADT 0.9.6, we highly recommend that you use the Android SDK Manager to install SDK +Tools r5 into your SDK.

    + +
    General Notes:
    +
    +
      +
    • Editing default.properties outside of Eclipse will now +automatically update the project.
    • +
    • Loads the SDK content only when a project requires it. This will make +Eclipse use less resources when the SDK contains many versions of Android.
    • +
    • Resolves potential deadlock between modal dialogs, when launching ADT the +first time with the SDK Usage panel.
    • +
    • Fixes issues with the New Project Wizard when selecting samples.
    • +
    +
    +
    AVD/SDK Manager:
    +
    +
      +
    • Adds support for platform samples packages.
    • +
    • Improves support for dependency between packages.
    • +
    • AVDs now sorted by API level.
    • +
    • The AVD creation dialog now enforces a minimum SD card size of 9MB.
    • +
    • Prevents deletion of running AVDs.
    • +
    +
    +
    DDMS:
    +
    +
      +
    • DDMS plug-in now contains the Allocation Tracker view.
    • +
    • New action in the Logcat view: "Go to problem" lets you go directly from an +exception trace output to the code.
    • +
    +
    +
    Editors:
    +
    +
      +
    • Explode mode in the Visual Layout Editor adds a margin to all layout objects +so that it's easier to see embedded or empty layouts.
    • +
    • Outline mode in the Visual Layout Editor draws layout outline to make it +easier to see layout objects.
    • +
    • Several fixes in the configuration selector of the Visual Layout +Editor.
    • +
    +
    +
    Application launching:
    +
    +
      +
    • Applications launched from ADT now behave as if they were clicked from the +Home screen.
    • +
    • Fixes issue where add-on with no optional library would not show up as valid +targets for application launches.
    • +
    • Resolves possible crash when launching applications.
    • +
    +
    +
    +
    +
    + +
    + + +ADT 0.9.5 (December 2009) +
    +
    +
    Dependencies:
    + +

    ADT 0.9.5 requires features provided in SDK Tools r4 or higher. If you install +ADT 0.9.5, which is highly recommended, you should use the Android SDK +Manager to download the latest SDK Tools into your SDK. For more information, +see Exploring the SDK.

    +
    + +
    General notes:
    +
    +
      +
    • AVD Launch dialog now shows scale value.
    • +
    • Fixes potential NPE in SDK Manager on AVD launch, for older AVD with no skin name specified.
    • +
    • Fixes XML validation issue in on older Java versions.
    • +
    • .apk packaging now properly ignores vi swap files as well as hidden files.
    • +
    +
    +
    +
    +
    + +
    + + +ADT 0.9.4 (October 2009) +
    +
    +
    Dependencies:
    + +

    ADT 0.9.4 requires features provided in SDK Tools r3 or higher. If you install +ADT 0.9.4, which is highly recommended, you should use the Android SDK +Manager to download the latest SDK Tools into your SDK. For more information, +see Exploring the SDK.

    +
    + +
    Project Creation Wizard:
    +
    +
      +
    • New option to create a project from a sample by choosing it from a list.
    • +
    +
    + +
    Layout Editor:
    +
    +
      +
    • Improved Configuration selector that lets you see how your layout will +render on different devices. Default device descriptions include ADP1 +and Google Ion, while SDK add-ons can also provide new descriptions. +A new UI allows you to create custom descriptions.
    • +
    • Adds a new clipping toggle, to let you see your full layout even if it's +bigger than the screen.
    • +
    +
    + +
    DDMS integration:
    +
    +
      +
    • Includes the improvements from the standlone DDMS, revision 3.
    • +
    • Adds an option to open HPROF files into eclipse instead of writing them on +disk. If a profiler such as MAT (Memory Analyzer +Tool) is installed, it'll open the file.
    • +
    +
    + +
    Android SDK and AVD Manager integration:
    +
    +
      +
    • Includes the improvements from the standalone Android SDK and AVD Manager, +revision 3.
    • +
    +
    +
    +
    +
    diff --git a/docs/html/tools/sdk/images/2.0/camera-modes.png b/docs/html/tools/sdk/images/2.0/camera-modes.png new file mode 100644 index 000000000000..ac4c1da57880 Binary files /dev/null and b/docs/html/tools/sdk/images/2.0/camera-modes.png differ diff --git a/docs/html/tools/sdk/images/2.0/email-inbox.png b/docs/html/tools/sdk/images/2.0/email-inbox.png new file mode 100644 index 000000000000..50d1c19033ac Binary files /dev/null and b/docs/html/tools/sdk/images/2.0/email-inbox.png differ diff --git a/docs/html/tools/sdk/images/2.0/mms-search.png b/docs/html/tools/sdk/images/2.0/mms-search.png new file mode 100644 index 000000000000..22c7dca9db2f Binary files /dev/null and b/docs/html/tools/sdk/images/2.0/mms-search.png differ diff --git a/docs/html/tools/sdk/images/2.0/multiple-accounts.png b/docs/html/tools/sdk/images/2.0/multiple-accounts.png new file mode 100644 index 000000000000..aa4cb157870d Binary files /dev/null and b/docs/html/tools/sdk/images/2.0/multiple-accounts.png differ diff --git a/docs/html/tools/sdk/images/2.0/quick-connect.png b/docs/html/tools/sdk/images/2.0/quick-connect.png new file mode 100644 index 000000000000..0bbf7dd27a65 Binary files /dev/null and b/docs/html/tools/sdk/images/2.0/quick-connect.png differ diff --git a/docs/html/tools/sdk/images/2.2/22browser.png b/docs/html/tools/sdk/images/2.2/22browser.png new file mode 100644 index 000000000000..817439da650c Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/22browser.png differ diff --git a/docs/html/tools/sdk/images/2.2/22exchange.png b/docs/html/tools/sdk/images/2.2/22exchange.png new file mode 100644 index 000000000000..1fa1f590b1b0 Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/22exchange.png differ diff --git a/docs/html/tools/sdk/images/2.2/22gallery.png b/docs/html/tools/sdk/images/2.2/22gallery.png new file mode 100644 index 000000000000..0cb74adcb2e8 Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/22gallery.png differ diff --git a/docs/html/tools/sdk/images/2.2/22home.png b/docs/html/tools/sdk/images/2.2/22home.png new file mode 100644 index 000000000000..a11ea3077457 Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/22home.png differ diff --git a/docs/html/tools/sdk/images/2.2/22hotspot.png b/docs/html/tools/sdk/images/2.2/22hotspot.png new file mode 100644 index 000000000000..0951439451ed Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/22hotspot.png differ diff --git a/docs/html/tools/sdk/images/2.2/22keyboard.png b/docs/html/tools/sdk/images/2.2/22keyboard.png new file mode 100644 index 000000000000..69f95ca8ff3e Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/22keyboard.png differ diff --git a/docs/html/tools/sdk/images/2.2/jit-graph.png b/docs/html/tools/sdk/images/2.2/jit-graph.png new file mode 100644 index 000000000000..52b8d60cf784 Binary files /dev/null and b/docs/html/tools/sdk/images/2.2/jit-graph.png differ diff --git a/docs/html/tools/sdk/images/2.3/ffc.png b/docs/html/tools/sdk/images/2.3/ffc.png new file mode 100644 index 000000000000..136a395fad1b Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/ffc.png differ diff --git a/docs/html/tools/sdk/images/2.3/home-menu.png b/docs/html/tools/sdk/images/2.3/home-menu.png new file mode 100644 index 000000000000..e9c8620bf0b3 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/home-menu.png differ diff --git a/docs/html/tools/sdk/images/2.3/home-plain.png b/docs/html/tools/sdk/images/2.3/home-plain.png new file mode 100644 index 000000000000..a6255f6a4bb1 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/home-plain.png differ diff --git a/docs/html/tools/sdk/images/2.3/nfc.png b/docs/html/tools/sdk/images/2.3/nfc.png new file mode 100644 index 000000000000..a21b6ab90a33 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/nfc.png differ diff --git a/docs/html/tools/sdk/images/2.3/onetouch.png b/docs/html/tools/sdk/images/2.3/onetouch.png new file mode 100644 index 000000000000..2789612f02a6 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/onetouch.png differ diff --git a/docs/html/tools/sdk/images/2.3/power.png b/docs/html/tools/sdk/images/2.3/power.png new file mode 100644 index 000000000000..7b0785d8351e Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/power.png differ diff --git a/docs/html/tools/sdk/images/2.3/running.png b/docs/html/tools/sdk/images/2.3/running.png new file mode 100644 index 000000000000..fe9a1a08f870 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/running.png differ diff --git a/docs/html/tools/sdk/images/2.3/selection.png b/docs/html/tools/sdk/images/2.3/selection.png new file mode 100644 index 000000000000..46ff28c92523 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/selection.png differ diff --git a/docs/html/tools/sdk/images/2.3/sipcall.png b/docs/html/tools/sdk/images/2.3/sipcall.png new file mode 100644 index 000000000000..48a5a1d12919 Binary files /dev/null and b/docs/html/tools/sdk/images/2.3/sipcall.png differ diff --git a/docs/html/tools/sdk/images/3.0/browser.png b/docs/html/tools/sdk/images/3.0/browser.png new file mode 100644 index 000000000000..0f16b2772b40 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/browser.png differ diff --git a/docs/html/tools/sdk/images/3.0/browser_full.png b/docs/html/tools/sdk/images/3.0/browser_full.png new file mode 100644 index 000000000000..08a329d6de5e Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/browser_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/camera.png b/docs/html/tools/sdk/images/3.0/camera.png new file mode 100644 index 000000000000..7dabdfc0516b Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/camera.png differ diff --git a/docs/html/tools/sdk/images/3.0/camera_full.png b/docs/html/tools/sdk/images/3.0/camera_full.png new file mode 100644 index 000000000000..3ee95c993ff8 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/camera_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/contacts.png b/docs/html/tools/sdk/images/3.0/contacts.png new file mode 100644 index 000000000000..9304701e07d2 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/contacts.png differ diff --git a/docs/html/tools/sdk/images/3.0/contacts_full.png b/docs/html/tools/sdk/images/3.0/contacts_full.png new file mode 100644 index 000000000000..b5eaf5b19b2e Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/contacts_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/copy.png b/docs/html/tools/sdk/images/3.0/copy.png new file mode 100644 index 000000000000..d5a4c3ee43d7 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/copy.png differ diff --git a/docs/html/tools/sdk/images/3.0/copy_full.png b/docs/html/tools/sdk/images/3.0/copy_full.png new file mode 100644 index 000000000000..124cf523bd0b Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/copy_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/home_hero1.png b/docs/html/tools/sdk/images/3.0/home_hero1.png new file mode 100644 index 000000000000..c00391f09658 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/home_hero1.png differ diff --git a/docs/html/tools/sdk/images/3.0/home_hero1_full.png b/docs/html/tools/sdk/images/3.0/home_hero1_full.png new file mode 100644 index 000000000000..1910ed21e79d Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/home_hero1_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/homescreen_cust_port.png b/docs/html/tools/sdk/images/3.0/homescreen_cust_port.png new file mode 100644 index 000000000000..b003a30e81a1 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/homescreen_cust_port.png differ diff --git a/docs/html/tools/sdk/images/3.0/homescreen_cust_port_full.png b/docs/html/tools/sdk/images/3.0/homescreen_cust_port_full.png new file mode 100644 index 000000000000..9c64edd6824d Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/homescreen_cust_port_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/mail_drag.png b/docs/html/tools/sdk/images/3.0/mail_drag.png new file mode 100644 index 000000000000..1f09a7a51af7 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/mail_drag.png differ diff --git a/docs/html/tools/sdk/images/3.0/mail_drag_full.png b/docs/html/tools/sdk/images/3.0/mail_drag_full.png new file mode 100644 index 000000000000..be4472f8acd5 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/mail_drag_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/tasks.png b/docs/html/tools/sdk/images/3.0/tasks.png new file mode 100644 index 000000000000..a4ba1bacabad Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/tasks.png differ diff --git a/docs/html/tools/sdk/images/3.0/tasks_full.png b/docs/html/tools/sdk/images/3.0/tasks_full.png new file mode 100644 index 000000000000..d2a224135ed6 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/tasks_full.png differ diff --git a/docs/html/tools/sdk/images/3.0/widgets.png b/docs/html/tools/sdk/images/3.0/widgets.png new file mode 100644 index 000000000000..d84766623dc7 Binary files /dev/null and b/docs/html/tools/sdk/images/3.0/widgets.png differ diff --git a/docs/html/tools/sdk/images/3.1/controls.png b/docs/html/tools/sdk/images/3.1/controls.png new file mode 100644 index 000000000000..e0ca1f81d3af Binary files /dev/null and b/docs/html/tools/sdk/images/3.1/controls.png differ diff --git a/docs/html/tools/sdk/images/3.1/home.png b/docs/html/tools/sdk/images/3.1/home.png new file mode 100644 index 000000000000..ea0a75a589da Binary files /dev/null and b/docs/html/tools/sdk/images/3.1/home.png differ diff --git a/docs/html/tools/sdk/images/3.1/home_full.png b/docs/html/tools/sdk/images/3.1/home_full.png new file mode 100644 index 000000000000..2b8e85e3e600 Binary files /dev/null and b/docs/html/tools/sdk/images/3.1/home_full.png differ diff --git a/docs/html/tools/sdk/images/3.1/resizeable.png b/docs/html/tools/sdk/images/3.1/resizeable.png new file mode 100644 index 000000000000..c9f5e8ea4c8a Binary files /dev/null and b/docs/html/tools/sdk/images/3.1/resizeable.png differ diff --git a/docs/html/tools/sdk/images/3.1/tasks.png b/docs/html/tools/sdk/images/3.1/tasks.png new file mode 100644 index 000000000000..89d69e5d043e Binary files /dev/null and b/docs/html/tools/sdk/images/3.1/tasks.png differ diff --git a/docs/html/tools/sdk/images/4.0/allapps-lg.png b/docs/html/tools/sdk/images/4.0/allapps-lg.png new file mode 100644 index 000000000000..f5eba3c3a7a4 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/allapps-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/allapps.png b/docs/html/tools/sdk/images/4.0/allapps.png new file mode 100644 index 000000000000..317a49ae4707 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/allapps.png differ diff --git a/docs/html/tools/sdk/images/4.0/bbench.png b/docs/html/tools/sdk/images/4.0/bbench.png new file mode 100644 index 000000000000..f1130923590a Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/bbench.png differ diff --git a/docs/html/tools/sdk/images/4.0/beam-lg.png b/docs/html/tools/sdk/images/4.0/beam-lg.png new file mode 100644 index 000000000000..608fc94f5437 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/beam-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/beam-maps-lg.png b/docs/html/tools/sdk/images/4.0/beam-maps-lg.png new file mode 100644 index 000000000000..96ac235e719a Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/beam-maps-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/beam-maps.png b/docs/html/tools/sdk/images/4.0/beam-maps.png new file mode 100644 index 000000000000..63b6756273a1 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/beam-maps.png differ diff --git a/docs/html/tools/sdk/images/4.0/beam.png b/docs/html/tools/sdk/images/4.0/beam.png new file mode 100644 index 000000000000..0eb7d26696c7 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/beam.png differ diff --git a/docs/html/tools/sdk/images/4.0/browser-lg.png b/docs/html/tools/sdk/images/4.0/browser-lg.png new file mode 100644 index 000000000000..fe3fe81465d2 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/browser-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/browser-tabs-lg.png b/docs/html/tools/sdk/images/4.0/browser-tabs-lg.png new file mode 100644 index 000000000000..0ea8f1079182 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/browser-tabs-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/browser-tabs.png b/docs/html/tools/sdk/images/4.0/browser-tabs.png new file mode 100644 index 000000000000..413b0c636b37 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/browser-tabs.png differ diff --git a/docs/html/tools/sdk/images/4.0/browser.png b/docs/html/tools/sdk/images/4.0/browser.png new file mode 100644 index 000000000000..4bc8179f2a82 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/browser.png differ diff --git a/docs/html/tools/sdk/images/4.0/calendar-widget-lg.png b/docs/html/tools/sdk/images/4.0/calendar-widget-lg.png new file mode 100644 index 000000000000..39fc986a558c Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/calendar-widget-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/calendar-widget.png b/docs/html/tools/sdk/images/4.0/calendar-widget.png new file mode 100644 index 000000000000..80a57f71af2e Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/calendar-widget.png differ diff --git a/docs/html/tools/sdk/images/4.0/camera-lg.png b/docs/html/tools/sdk/images/4.0/camera-lg.png new file mode 100644 index 000000000000..7d96a4f6840d Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/camera-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/camera.png b/docs/html/tools/sdk/images/4.0/camera.png new file mode 100644 index 000000000000..74545495ff4c Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/camera.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-call-lg.png b/docs/html/tools/sdk/images/4.0/contact-call-lg.png new file mode 100644 index 000000000000..40b1f404041f Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-call-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-call.png b/docs/html/tools/sdk/images/4.0/contact-call.png new file mode 100644 index 000000000000..5550b575f028 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-call.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-call.xcf b/docs/html/tools/sdk/images/4.0/contact-call.xcf new file mode 100644 index 000000000000..3046e928cd64 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-call.xcf differ diff --git a/docs/html/tools/sdk/images/4.0/contact-connect-lg.png b/docs/html/tools/sdk/images/4.0/contact-connect-lg.png new file mode 100644 index 000000000000..ad0d04c7639d Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-connect-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-connect.png b/docs/html/tools/sdk/images/4.0/contact-connect.png new file mode 100644 index 000000000000..d958206a43a2 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-connect.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-email-lg.png b/docs/html/tools/sdk/images/4.0/contact-email-lg.png new file mode 100644 index 000000000000..db75a467eb88 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-email-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-email.png b/docs/html/tools/sdk/images/4.0/contact-email.png new file mode 100644 index 000000000000..9e5460dcd74c Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-email.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-faves-lg.png b/docs/html/tools/sdk/images/4.0/contact-faves-lg.png new file mode 100644 index 000000000000..1ec3fd02509e Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-faves-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/contact-faves.png b/docs/html/tools/sdk/images/4.0/contact-faves.png new file mode 100644 index 000000000000..57e4ca61e77a Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/contact-faves.png differ diff --git a/docs/html/tools/sdk/images/4.0/face-unlock-lg.png b/docs/html/tools/sdk/images/4.0/face-unlock-lg.png new file mode 100644 index 000000000000..3fd1695a615e Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/face-unlock-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/face-unlock.png b/docs/html/tools/sdk/images/4.0/face-unlock.png new file mode 100644 index 000000000000..00afb83dbd36 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/face-unlock.png differ diff --git a/docs/html/tools/sdk/images/4.0/folders.xcf b/docs/html/tools/sdk/images/4.0/folders.xcf new file mode 100644 index 000000000000..66cc02caade1 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/folders.xcf differ diff --git a/docs/html/tools/sdk/images/4.0/gallery-edit-lg.png b/docs/html/tools/sdk/images/4.0/gallery-edit-lg.png new file mode 100644 index 000000000000..3d6688f45c75 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/gallery-edit-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/gallery-edit.png b/docs/html/tools/sdk/images/4.0/gallery-edit.png new file mode 100644 index 000000000000..69744ec92cf1 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/gallery-edit.png differ diff --git a/docs/html/tools/sdk/images/4.0/gallery-share-lg.png b/docs/html/tools/sdk/images/4.0/gallery-share-lg.png new file mode 100644 index 000000000000..749f51edf30e Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/gallery-share-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/gallery-share.png b/docs/html/tools/sdk/images/4.0/gallery-share.png new file mode 100644 index 000000000000..443a70c94aee Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/gallery-share.png differ diff --git a/docs/html/tools/sdk/images/4.0/gallery-widget.png b/docs/html/tools/sdk/images/4.0/gallery-widget.png new file mode 100644 index 000000000000..e72fd0dc1b75 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/gallery-widget.png differ diff --git a/docs/html/tools/sdk/images/4.0/home-lg.png b/docs/html/tools/sdk/images/4.0/home-lg.png new file mode 100644 index 000000000000..5b9021d6df71 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/home-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/home.png b/docs/html/tools/sdk/images/4.0/home.png new file mode 100644 index 000000000000..cd24732978a8 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/home.png differ diff --git a/docs/html/tools/sdk/images/4.0/live-effects.png b/docs/html/tools/sdk/images/4.0/live-effects.png new file mode 100644 index 000000000000..11a0122d5e40 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/live-effects.png differ diff --git a/docs/html/tools/sdk/images/4.0/lock-camera-lg.png b/docs/html/tools/sdk/images/4.0/lock-camera-lg.png new file mode 100644 index 000000000000..c82cec68450b Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/lock-camera-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/lock-camera.png b/docs/html/tools/sdk/images/4.0/lock-camera.png new file mode 100644 index 000000000000..d3cc1537de1c Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/lock-camera.png differ diff --git a/docs/html/tools/sdk/images/4.0/lock-lg.png b/docs/html/tools/sdk/images/4.0/lock-lg.png new file mode 100644 index 000000000000..b859e117027e Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/lock-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/lock.png b/docs/html/tools/sdk/images/4.0/lock.png new file mode 100644 index 000000000000..d1688265fa04 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/lock.png differ diff --git a/docs/html/tools/sdk/images/4.0/quick-responses-lg.png b/docs/html/tools/sdk/images/4.0/quick-responses-lg.png new file mode 100644 index 000000000000..39cea9ae57c8 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/quick-responses-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/quick-responses.png b/docs/html/tools/sdk/images/4.0/quick-responses.png new file mode 100644 index 000000000000..d43f34835022 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/quick-responses.png differ diff --git a/docs/html/tools/sdk/images/4.0/screenshot-lg.png b/docs/html/tools/sdk/images/4.0/screenshot-lg.png new file mode 100644 index 000000000000..30ac33933f79 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/screenshot-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/screenshot.png b/docs/html/tools/sdk/images/4.0/screenshot.png new file mode 100644 index 000000000000..b23c91347466 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/screenshot.png differ diff --git a/docs/html/tools/sdk/images/4.0/tasks-lg.png b/docs/html/tools/sdk/images/4.0/tasks-lg.png new file mode 100644 index 000000000000..58b5c5d2b79e Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/tasks-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/tasks.png b/docs/html/tools/sdk/images/4.0/tasks.png new file mode 100644 index 000000000000..34a9d4af5cb5 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/tasks.png differ diff --git a/docs/html/tools/sdk/images/4.0/text-replace-lg.png b/docs/html/tools/sdk/images/4.0/text-replace-lg.png new file mode 100644 index 000000000000..047d8025312a Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/text-replace-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/text-replace.png b/docs/html/tools/sdk/images/4.0/text-replace.png new file mode 100644 index 000000000000..d2bda3e6959a Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/text-replace.png differ diff --git a/docs/html/tools/sdk/images/4.0/tts-lg.png b/docs/html/tools/sdk/images/4.0/tts-lg.png new file mode 100644 index 000000000000..2f4905118ceb Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/tts-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/tts.png b/docs/html/tools/sdk/images/4.0/tts.png new file mode 100644 index 000000000000..3eae634b1d22 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/tts.png differ diff --git a/docs/html/tools/sdk/images/4.0/usage-all-lg.png b/docs/html/tools/sdk/images/4.0/usage-all-lg.png new file mode 100644 index 000000000000..fd7eebaf973a Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/usage-all-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/usage-all.png b/docs/html/tools/sdk/images/4.0/usage-all.png new file mode 100644 index 000000000000..048db83309e7 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/usage-all.png differ diff --git a/docs/html/tools/sdk/images/4.0/usage-maps-lg.png b/docs/html/tools/sdk/images/4.0/usage-maps-lg.png new file mode 100644 index 000000000000..b14437069589 Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/usage-maps-lg.png differ diff --git a/docs/html/tools/sdk/images/4.0/usage-maps.png b/docs/html/tools/sdk/images/4.0/usage-maps.png new file mode 100644 index 000000000000..a6dcd219aa4d Binary files /dev/null and b/docs/html/tools/sdk/images/4.0/usage-maps.png differ diff --git a/docs/html/tools/sdk/images/battery.png b/docs/html/tools/sdk/images/battery.png new file mode 100644 index 000000000000..10fd16b16afe Binary files /dev/null and b/docs/html/tools/sdk/images/battery.png differ diff --git a/docs/html/tools/sdk/images/camera.png b/docs/html/tools/sdk/images/camera.png new file mode 100644 index 000000000000..6078388ea232 Binary files /dev/null and b/docs/html/tools/sdk/images/camera.png differ diff --git a/docs/html/tools/sdk/images/donut_small_bg.png b/docs/html/tools/sdk/images/donut_small_bg.png new file mode 100644 index 000000000000..f514b504fd15 Binary files /dev/null and b/docs/html/tools/sdk/images/donut_small_bg.png differ diff --git a/docs/html/tools/sdk/images/market.png b/docs/html/tools/sdk/images/market.png new file mode 100644 index 000000000000..8d11134c1c4a Binary files /dev/null and b/docs/html/tools/sdk/images/market.png differ diff --git a/docs/html/tools/sdk/images/search.png b/docs/html/tools/sdk/images/search.png new file mode 100644 index 000000000000..10ab910bab86 Binary files /dev/null and b/docs/html/tools/sdk/images/search.png differ diff --git a/docs/html/tools/sdk/index.jd b/docs/html/tools/sdk/index.jd new file mode 100644 index 000000000000..fb7106577b10 --- /dev/null +++ b/docs/html/tools/sdk/index.jd @@ -0,0 +1,10 @@ +page.title=Android SDK +header.hide=1 + +@jd:body + +

    This page should not exist.

    + + + + diff --git a/docs/html/tools/sdk/installing.jd b/docs/html/tools/sdk/installing.jd new file mode 100644 index 000000000000..4837ab7ff1e9 --- /dev/null +++ b/docs/html/tools/sdk/installing.jd @@ -0,0 +1,590 @@ +page.title=Installing the SDK + +@jd:body + + + + + + + +

    This page describes how to install the Android SDK +and set up your development environment for the first time.

    + +

    If you encounter any problems during installation, see the +Troubleshooting section at the bottom of +this page.

    + +

    Updating?

    + +

    If you already have an Android SDK, use the Android SDK Manager tool to install +updated tools and new Android platforms into your existing environment. For information about how to +do that, see Exploring the SDK.

    + + +

    Step 1. Preparing Your Development Computer

    + +

    Before getting started with the Android SDK, take a moment to confirm that +your development computer meets the System +Requirements. In particular, you might need to install the JDK, if you don't have it already.

    + +

    If you will be developing in Eclipse with the Android Development +Tools (ADT) Plugin—the recommended path if you are new to +Android—make sure that you have a suitable version of Eclipse +installed on your computer as described in the +System Requirements document. +If you need to install Eclipse, you can download it from this location:

    + +

    http://www.eclipse.org/downloads/

    + +

    The "Eclipse Classic" version is recommended. Otherwise, a Java or +RCP version of Eclipse is recommended.

    + + +

    Step 2. Downloading the SDK Starter Package

    + +

    The SDK starter package is not a full +development environment—it includes only the core SDK Tools, which you can +use to download the rest of the SDK packages (such as the latest Android platform).

    + +

    If you haven't already, get the latest version of the SDK starter package from the SDK download page.

    + +

    If you downloaded a {@code .zip} or {@code .tgz} package (instead of the SDK installer), unpack +it to a safe location on your machine. By default, the SDK files are unpacked +into a directory named android-sdk-<machine-platform>.

    + +

    If you downloaded the Windows installer ({@code .exe} file), run it now and it will check +whether the proper Java SE Development Kit (JDK) is installed (installing it, if necessary), then +install the SDK Tools into a default location (which you can modify).

    + +

    Make a note of the name and location of the SDK directory on your system—you will need to +refer to the SDK directory later, when setting up the ADT plugin and when using +the SDK tools from the command line.

    + + +

    Step 3. Installing the ADT Plugin for Eclipse

    + +

    Android offers a custom plugin for the Eclipse IDE, called Android +Development Tools (ADT), that is designed to give you a powerful, integrated +environment in which to build Android applications. It extends the capabilites +of Eclipse to let you quickly set up new Android projects, create an application +UI, debug your applications +using the Android SDK tools, and even export signed (or unsigned) APKs in order +to distribute your application. In general, developing in Eclipse with ADT is a +highly recommended approach and is the fastest way to get started with Android. +

    + +

    If you'd like to use ADT for developing Android applications, install it now. +Read Installing the ADT Plugin for +step-by-step installation instructions, then return here to continue the +last step in setting up your Android SDK.

    + +

    If you prefer to work in a different IDE, you do not need to +install Eclipse or ADT. Instead, you can directly use the SDK tools to build and +debug your application. The Introduction +to Android application development outlines the major steps that you need to complete when +developing in Eclipse or other IDEs.

    + + + +

    Step 4. Adding Platforms and Other Packages

    + +

    The last step in setting up your SDK is using the Android SDK Manager (a +tool included in the SDK starter package) to download essential SDK packages into your development +environment.

    + +

    The SDK uses a modular structure that separates the major parts of the SDK—Android platform +versions, add-ons, tools, samples, and documentation—into a set of separately installable +packages. The SDK starter package, which you've already downloaded, includes only a single +package: the latest version of the SDK Tools. To develop an Android application, you also need to +download at least one Android platform and the associated platform tools. You can add other +packages and platforms as well, which is highly recommended.

    + +

    If you used the Windows installer, when you complete the installation wizard, it will launch the +Android SDK Manager with a default set of platforms and other packages selected +for you to install. Simply click Install to accept the recommended set of +packages and install them. You can then skip to Step 5, but we +recommend you first read the section about the Available Packages to +better understand the packages available from the Android SDK Manager.

    + +

    You can launch the Android SDK Manager in one of the following ways:

    +
      +
    • From within Eclipse, select Window > Android SDK Manager.
    • +
    • On Windows, double-click the SDK Manager.exe file at the root of the Android +SDK directory.
    • +
    • On Mac or Linux, open a terminal and navigate to the tools/ directory in the +Android SDK, then execute:
      android
    • +
    + +

    To download packages, use the graphical UI of the Android SDK +Manager to browse the SDK repository and select new or updated +packages (see figure 1). The Android SDK Manager installs the selected packages in +your SDK environment. For information about which packages you should download, see Recommended Packages.

    + + +

    Figure 1. The Android SDK Manager's +Available Packages panel, which shows the SDK packages that are +available for you to download into your environment.

    + + +

    Available Packages

    + +

    By default, there are two repositories of packages for your SDK: Android +Repository and Third party Add-ons.

    + +

    The Android Repository offers these types of packages:

    + +
      +
    • SDK Tools — Contains tools for debugging and testing your application +and other utility tools. These tools are installed with the Android SDK starter package and receive +periodic updates. You can access these tools in the <sdk>/tools/ directory of +your SDK. To learn more about +them, see SDK Tools in the +developer guide.
    • + +
    • SDK Platform-tools — Contains platform-dependent tools for developing +and debugging your application. These tools support the latest features of the Android platform and +are typically updated only when a new platform becomes available. You can access these tools in the +<sdk>/platform-tools/ directory. To learn more about them, see Platform Tools in the +developer guide.
    • + +
    • Android platforms — An SDK platform is +available for every production Android platform deployable to Android-powered devices. Each +SDK platform package includes a fully compliant Android library, system image, sample code, +and emulator skins. To learn more about a specific platform, see the list of platforms that appears +under the section "Downloadable SDK Packages" on the left part of this page.
    • + +
    • USB Driver for Windows (Windows only) — Contains driver files +that you can install on your Windows computer, so that you can run and debug +your applications on an actual device. You do not need the USB driver unless +you plan to debug your application on an actual Android-powered device. If you +develop on Mac OS X or Linux, you do not need a special driver to debug +your application on an Android-powered device. See Using Hardware Devices for more information +about developing on a real device.
    • + +
    • Samples — Contains the sample code and apps available +for each Android development platform. If you are just getting started with +Android development, make sure to download the samples to your SDK.
    • + +
    • Documentation — Contains a local copy of the latest +multiversion documentation for the Android framework API.
    • +
    + +

    The Third party Add-ons provide packages that allow you to create a development +environment using a specific Android external library (such as the Google Maps library) or a +customized (but fully compliant) Android system image. You can add additional Add-on repositories by +clicking Add Add-on Site.

    + + +

    Recommended Packages

    + +

    The SDK repository contains a range of packages that you can download. +Use the table below to determine which packages you need, based on whether you +want to set up a basic, recommended, or full development environment: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    EnvironmentSDK PackageComments
    BasicSDK ToolsIf you've just installed +the SDK starter package, then you already have the latest version of this package. The +SDK Tools package is required to develop an Android application. Make sure you keep this up to +date.
    SDK Platform-toolsThis includes more tools that are required +for application development. These tools are platform-dependent and typically update only when +a new SDK platform is made available, in order to support new features in the platform. These +tools are always backward compatible with older platforms, but you must be sure that you have +the latest version of these tools when you install a new SDK platform.
    SDK platformYou need to download at least one platform into your environment, so that +you will be able to compile your application and set up an Android Virtual +Device (AVD) to run it on (in the emulator). To start with, just download the +latest version of the platform. Later, if you plan to publish your application, +you will want to download other platforms as well, so that you can test your +application on the full range of Android platform versions that your application supports.
    +
    Recommended
    (plus Basic)
    DocumentationThe Documentation package is useful because it lets you work offline and +also look up API reference information from inside Eclipse.
    SamplesThe Samples packages give you source code that you can use to learn about +Android, load as a project and run, or reuse in your own app. Note that multiple +samples packages are available — one for each Android platform version. When +you are choosing a samples package to download, select the one whose API Level +matches the API Level of the Android platform that you plan to use.
    Usb DriverThe Usb Driver package is needed only if you are developing on Windows and +have an Android-powered device on which you want to install your application for +debugging and testing. For Mac OS X and Linux platforms, no +special driver is needed.
    +
    Full
    (plus Recommended)
    Google APIsThe Google APIs add-on gives your application access to the Maps external +library, which makes it easy to display and manipulate Maps data in your +application.
    Additional SDK PlatformsIf you plan to publish your application, you will want to download +additional platforms corresponding to the Android platform versions on which you +want the application to run. The recommended approach is to compile your +application against the lowest version you want to support, but test it against +higher versions that you intend the application to run on. You can test your +applications on different platforms by running in an Android Virtual Device +(AVD) on the Android emulator.
    + +

    Once you've installed at least the basic configuration of SDK packages, you're ready to start +developing Android apps. The next section describes the contents of the Android SDK to familiarize +you with the packages you've just installed.

    + +

    For more information about using the Android SDK Manager, see the Exploring the SDK document.

    + + +

    Step 5. Exploring the SDK (Optional)

    + +

    Once you've installed the SDK and downloaded the platforms, documentation, +and add-ons that you need, we suggest that you open the SDK directory and take a look at what's +inside.

    + +

    The table below describes the full SDK directory contents, with packages +installed.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameDescription
    add-ons/Contains add-ons to the Android SDK development +environment, which let you develop against external libraries that are available on some +devices.
    docs/A full set of documentation in HTML format, including the Developer's Guide, +API Reference, and other information. To read the documentation, load the +file offline.html in a web browser.
    platform-tools/Contains platform-dependent development tools that may be updated with each platform release. +The platform tools include the Android Debug Bridge ({@code adb}) as well as other tools that you +don't typically use directly. These tools are separate from the development tools in the {@code +tools/} directory because these tools may be updated in order to support new +features in the latest Android platform.
    platforms/Contains a set of Android platform versions that you can develop +applications against, each in a separate directory.
    <platform>/Platform version directory, for example "android-11". All platform version directories contain +a similar set of files and subdirectory structure. Each platform directory also includes the +Android library (android.jar) that is used to compile applications against the +platform version.
    samples/Sample code and apps that are specific to platform version.
    tools/Contains the set of development and profiling tools that are platform-independent, such +as the emulator, the Android SDK Manager, the AVD Manager, ddms, +hierarchyviewer +and more. The tools in this directory may be updated at any time using the Android SDK +Manager and are independent of platform releases.
    SDK Readme.txtA file that explains how to perform the initial setup of your SDK, +including how to launch the Android SDK Manager tool on all +platforms.
    SDK Manager.exeWindows SDK only. A shortcut that launches the Android SDK +Manager tool, which you use to add packages to your SDK.
    + + +

    Optionally, you might want to add the location of the SDK's tools/ and +platform-tools to your PATH environment variable, to provide easy +access to the tools.

    + + +
    + + + How to update your PATH +
    + +

    Adding both tools/ and platform-tools/ to your PATH lets you run +command line tools without needing to +supply the full path to the tool directories. Depending on your operating system, you can +include these directories in your PATH in the following way:

    + +
      + +
    • On Windows, right-click on My Computer, and select Properties. + Under the Advanced tab, hit the Environment Variables button, and in the + dialog that comes up, double-click on Path (under System Variables). Add the full path to the + tools/ and platform-tools/ directories to the path.
    • + +
    • On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look + for a line that sets the PATH environment variable and add the + full path to the tools/ and platform-tools/ directories to it. If you + don't see a line setting the path, you can add one: +
      export PATH=${PATH}:<sdk>/tools:<sdk>/platform-tools
      +
    • + +
    • On a Mac OS X, look in your home directory for .bash_profile and + proceed as for Linux. You can create the .bash_profile if + you don't already have one.
    • +
    + +
    +
    + + +

    Next Steps

    +

    Once you have completed installation, you are ready to +begin developing applications. Here are a few ways you can get started:

    + +

    Set up the Hello World application

    +
      +
    • If you have just installed the SDK for the first time, go to the Hello + World tutorial. The tutorial takes you step-by-step through the process + of setting up your first Android project, including setting up an Android + Virtual Device (AVD) on which to run the application. +
    • +
    + +

    Following the Hello World tutorial is an essential +first step in getting started with Android development.

    + +

    Learn about Android

    +
      +
    • Take a look at the Dev + Guide and the types of information it provides.
    • +
    • Read an introduction to Android as a platform in What is + Android?
    • +
    • Learn about the Android framework and how applications run on it in + Application + Fundamentals.
    • +
    • Take a look at the Android framework API specification in the Reference tab.
    • +
    + +

    Explore the development tools

    + + +

    Follow the Notepad tutorial

    + +
      +
    • The + Notepad Tutorial shows you how to build a full Android application + and provides helpful commentary on the Android system and API. The + Notepad tutorial helps you bring together the important design + and architectural concepts in a moderately complex application. +
    • +
    +

    Following the Notepad tutorial is an excellent +second step in getting started with Android development.

    + +

    Explore some code

    + +
      +
    • The Android SDK includes sample code and applications for each platform +version. You can browse the samples in the Resources tab or download them +into your SDK using the Android SDK Manager. Once you've downloaded the +samples, you'll find them in +<sdk>/samples/<platform>/.
    • +
    + +

    Visit the Android developer groups

    +
      +
    • Take a look at the Community pages to see a list of + Android developers groups. In particular, you might want to look at the + Android + Developers group to get a sense for what the Android developer + community is like.
    • +
    + +

    Troubleshooting

    + +

    Ubuntu Linux Notes

    + +
      +
    • If you need help installing and configuring Java on your + development machine, you might find these resources helpful: + +
    • +
    • Here are the steps to install Java and Eclipse, prior to installing + the Android SDK and ADT Plugin. +
        +
      1. If you are running a 64-bit distribution on your development + machine, you need to install the ia32-libs package using + apt-get:: +
        apt-get install ia32-libs
        +
      2. +
      3. Next, install Java:
        apt-get install sun-java6-jdk
      4. +
      5. The Ubuntu package manager does not currently offer an Eclipse 3.3 + version for download, so we recommend that you download Eclipse from + eclipse.org (http://www.eclipse.org/ + downloads/). A Java or RCP version of Eclipse is recommended.
      6. +
      7. Follow the steps given in previous sections to install the SDK + and the ADT plugin.
      8. +
      +
    • +
    + +

    Other Linux Notes

    + +
      +
    • If JDK is already installed on your development computer, please + take a moment to make sure that it meets the version requirements listed + in the System Requirements. + In particular, note that some Linux distributions may include JDK 1.4 or Gnu + Compiler for Java, both of which are not supported for Android development.
    • +
    diff --git a/docs/html/tools/sdk/libraries.jd b/docs/html/tools/sdk/libraries.jd new file mode 100644 index 000000000000..9e47c4af58bc --- /dev/null +++ b/docs/html/tools/sdk/libraries.jd @@ -0,0 +1,9 @@ +page.title=Libraries + +@jd:body + + + +

    A page that lists libraries and links to release notes. Links to dashboards etc.

    + + diff --git a/docs/html/tools/sdk/ndk/1.5_r1/index.jd b/docs/html/tools/sdk/ndk/1.5_r1/index.jd new file mode 100644 index 000000000000..4c70a8a6f91e --- /dev/null +++ b/docs/html/tools/sdk/ndk/1.5_r1/index.jd @@ -0,0 +1,6 @@ +page.title=Android 1.5 NDK, Release 1 +sdk.redirect=true +sdk.redirect.path=ndk/index.html + +@jd:body + diff --git a/docs/html/tools/sdk/ndk/1.6_r1/index.jd b/docs/html/tools/sdk/ndk/1.6_r1/index.jd new file mode 100644 index 000000000000..090dcdc37867 --- /dev/null +++ b/docs/html/tools/sdk/ndk/1.6_r1/index.jd @@ -0,0 +1,5 @@ +page.title=Android 1.6 NDK, Release 1 +sdk.redirect=true +sdk.redirect.path=ndk/index.html + +@jd:body diff --git a/docs/html/tools/sdk/ndk/index.jd b/docs/html/tools/sdk/ndk/index.jd new file mode 100644 index 000000000000..956d939c1d6f --- /dev/null +++ b/docs/html/tools/sdk/ndk/index.jd @@ -0,0 +1,1128 @@ +ndk=true + +ndk.win_download=android-ndk-r8-windows.zip +ndk.win_bytes=109928336 +ndk.win_checksum=37b1a2576f28752fcc09e1b9c07e3f14 + +ndk.mac_download=android-ndk-r8-darwin-x86.tar.bz2 +ndk.mac_bytes=96650992 +ndk.mac_checksum=81ce5de731f945692123b377afe0bad9 + +ndk.linux_download=android-ndk-r8-linux-x86.tar.bz2 +ndk.linux_bytes=88310791 +ndk.linux_checksum=5c9afc9695ad67c61f82fbf896803c05 + +page.title=Android NDK + +@jd:body + +

    Revisions

    + +

    The sections below provide information and notes about successive releases of +the NDK, as denoted by revision number.

    + + + + + +
    + + Android NDK, Revision 8 (May 2012) + +
    +

    This release of the NDK includes support for MIPS ABI and a few additional fixes.

    + + +
    New features:
    + +
    +
      +
    • Added support for the MIPS ABI, which allows you to generate machine code that runs on + compatible MIPS-based Android devices. Major features for MIPS include MIPS-specific + toolchains, system headers, libraries and debugging support. For more details regarding + MIPS support, see {@code docs/CPU-MIPS.html} in the NDK package. + +

      By default, code is generated for ARM-based devices. You can add {@code mips} to + your {@code APP_ABI} definition in your {@code Application.mk} file to build + for MIPS platforms. For example, the following line instructs {@code ndk-build} + to build your code for three distinct ABIs:

      + +
      APP_ABI := armeabi armeabi-v7a mips
      + +

      Unless you rely on architecture-specific assembly sources, such as ARM assembly + code, you should not need to touch your {@code Android.mk} files to build MIPS + machine code.

      +
    • + +
    • You can build a standalone MIPS toolchain using the {@code --arch=mips} + option when calling make-standalone-toolchain.sh. See + {@code docs/STANDALONE-TOOLCHAIN.html} for more details. +
    • +
    + +

    Note: To ensure that your applications are available +to users only if their devices are capable of running them, Google Play filters applications based +on the instruction set information included in your application — no action is needed on your part +to enable the filtering. Additionally, the Android system itself also checks your application at +install time and allows the installation to continue only if the application provides a library that +is compiled for the device's CPU architecture.

    +
    + +
    Important bug fixes:
    + +
    +
      +
    • Fixed a typo in GAbi++ implementation where the result of {@code + dynamic_cast<D>(b)} of base class object {@code b} to derived class {@code D} is + incorrectly adjusted in the opposite direction from the base class. + (Issue 28721) +
    • +
    • Fixed an issue in which {@code make-standalone-toolchain.sh} fails to copy + {@code libsupc++.*}.
    • +
    +
    + +
    Other bug fixes:
    + +
    +
      +
    • Fixed {@code ndk-build.cmd} to ensure that {@code ndk-build.cmd} works correctly even + if the user has redefined the {@code SHELL} environment variable, which may be changed + when installing a variety of development tools in Windows environments. +
    • +
    +
    + +
    +
    + +
    + + Android NDK, Revision 7c (April 2012) + +
    +

    This release of the NDK includes an important fix for Tegra2-based devices, and a few +additional fixes and improvements:

    + +
    +
    Important bug fixes:
    + +
    +
      +
    • Fixed GNU STL armeabi-v7a binaries to not crash on non-NEON + devices. The files provided with NDK r7b were not configured properly, + resulting in crashes on Tegra2-based devices and others when trying to use + certain floating-point functions (e.g., {@code cosf}, {@code sinf}, {@code expf}).
    • +
    +
    + +
    Important changes:
    + +
    +
      +
    • Added support for custom output directories through the {@code NDK_OUT} + environment variable. When defined, this variable is used to store all + intermediate generated files, instead of {@code $PROJECT_PATH/obj}. The variable is + also recognized by {@code ndk-gdb}.
    • +
    • Added support for building modules with hundreds or even thousands of source + files by defining {@code LOCAL_SHORT_COMMANDS} to {@code true} in your {@code Android.mk}. +

      This change forces the NDK build system to put most linker or archiver options + into list files, as a work-around for command-line length limitations. + See {@code docs/ANDROID-MK.html} for details.

      +
    • +
    +
    + +
    Other bug fixes:
    + +
    +
      +
    • Fixed {@code android_getCpuCount()} implementation in the {@code cpufeatures} +helper library. On certain devices, where cores are enabled dynamically by the system, the previous +implementation would report the total number of active cores the first time the function +was called, rather than the total number of physically available cores.
    • +
    +
    +
    +
    +
    + + +
    + + Android NDK, Revision 7b (February 2012) + +
    +

    This release of the NDK includes fixes for native Windows builds, Cygwin and many other + improvements:

    + +
    +
    Important bug fixes:
    + +
    +
      +
    • Updated {@code sys/atomics.h} to avoid correctness issues + on some multi-core ARM-based devices. Rebuild your unmodified sources with this + version of the NDK and this problem should be completely eliminated. + For more details, read {@code docs/ANDROID-ATOMICS.html}.
    • +
    • Reverted to {@code binutils} 2.19 to fix debugging issues that + appeared in NDK r7 (which switched to {@code binutils} 2.20.1).
    • +
    • Fixed {@code ndk-build} on 32-bit Linux. A packaging error put a 64-bit version + of the {@code awk} executable under {@code prebuilt/linux-x86/bin} in NDK r7.
    • +
    • Fixed native Windows build ({@code ndk-build.cmd}). Other build modes were not + affected. The fixes include: +
        +
      • Removed an infinite loop / stack overflow bug that happened when trying + to call {@code ndk-build.cmd} from a directory that was not the top of + your project path (e.g., in any sub-directory of it).
      • +
      • Fixed a problem where the auto-generated dependency files were ignored. This + meant that updating a header didn't trigger recompilation of sources that included + it.
      • +
      • Fixed a problem where special characters in files or paths, other than spaces and + quotes, were not correctly handled.
      • +
      +
    • +
    • Fixed the standalone toolchain to generate proper binaries when using + {@code -lstdc++} (i.e., linking against the GNU {@code libstdc++} C++ runtime). You + should use {@code -lgnustl_shared} if you want to link against the shared library + version or {@code -lstdc++} for the static version. + +

      See {@code docs/STANDALONE-TOOLCHAIN.html} for more details about this fix.

      +
    • +
    • Fixed {@code gnustl_shared} on Cygwin. The linker complained that it couldn't find + {@code libsupc++.a} even though the file was at the right location.
    • +
    • Fixed Cygwin C++ link when not using any specific C++ runtime through + {@code APP_STL}.
    • +
    +
    +
    + +
    +
    Other changes:
    + +
    +
      +
    • When your application uses the GNU {@code libstdc++} runtime, the compiler will + no longer forcibly enable exceptions and RTTI. This change results in smaller code. +

      If you need these features, you must do one of the following:

      +
        +
      • Enable exceptions and/or RTTI explicitly in your modules or + {@code Application.mk}. (recommended)
      • +
      • Define {@code APP_GNUSTL_FORCE_CPP_FEATURES} to {@code 'exceptions'}, + {@code 'rtti'} or both in your {@code Application.mk}. See + {@code docs/APPLICATION-MK.html} for more details.
      • +
      +
    • +
    • {@code ndk-gdb} now works properly when your application has private services + running in independent processes. It debugs the main application process, instead of the + first process listed by {@code ps}, which is usually a service process.
    • +
    • Fixed a rare bug where NDK r7 would fail to honor the {@code LOCAL_ARM_MODE} value + and always compile certain source files (but not all) to 32-bit instructions.
    • +
    • {@code stlport}: Refresh the sources to match the Android platform version. This + update fixes a few minor bugs: +
        +
      • Fixed instantiation of an incomplete type
      • +
      • Fixed minor "==" versus "=" typo
      • +
      • Used {@code memmove} instead of {@code memcpy} in {@code string::assign}
      • +
      • Added better handling of {@code IsNANorINF}, {@code IsINF}, {@code IsNegNAN}, + etc.
      • +
      +

      For complete details, see the commit log.

      +
    • +
    • {@code stlport}: Removed 5 unnecessary static initializers from the library.
    • +
    • The GNU libstdc++ libraries for armeabi-v7a were mistakenly compiled for + armeabi instead. This change had no impact on correctness, but using the right + ABI should provide slightly better performance.
    • +
    • The {@code cpu-features} helper library was updated to report three optional + x86 CPU features ({@code SSSE3}, {@code MOVBE} and {@code POPCNT}). See + {@code docs/CPU-FEATURES.html} for more details.
    • +
    • {@code docs/NDK-BUILD.html} was updated to mention {@code NDK_APPLICATION_MK} instead + of {@code NDK_APP_APPLICATION_MK} to select a custom {@code Application.mk} file.
    • +
    • Cygwin: {@code ndk-build} no longer creates an empty "NUL" file in the current + directory when invoked.
    • +
    • Cygwin: Added better automatic dependency detection. In the previous version, it + didn't work properly in the following cases: +
        +
      • When the Cygwin drive prefix was not {@code /cygdrive}.
      • +
      • When using drive-less mounts, for example, when Cygwin would translate + {@code /home} to {@code \\server\subdir} instead of {@code C:\Some\Dir}.
      • +
      +
    • +
    • Cygwin: {@code ndk-build} does not try to use the native Windows tools under + {@code $NDK/prebuilt/windows/bin} with certain versions of Cygwin and/or GNU Make.
    • +
    +
    +
    +
    +
    + + +
    + + Android NDK, Revision 7 (November 2011) + +
    +

    This release of the NDK includes new features to support the Android 4.0 platform as well + as many other additions and improvements:

    + +
    +
    New features
    + +
    +
      +
    • Added official NDK APIs for Android 4.0 (API level 14), which adds the following + native features to the platform: + +
        +
      • Added native multimedia API based on the Khronos Group OpenMAX AL™ 1.0.1 + standard. The new <OMXAL/OpenMAXAL.h> and + <OMXAL/OpenMAXAL_Android.h> headers allow applications targeting + API level 14 to perform multimedia output directly from native code by using a new + Android-specific buffer queue interface. For more details, see + docs/openmaxal/index.html and http://www.khronos.org/openmax/.
      • + +
      • Updated the native audio API based on the Khronos Group OpenSL ES 1.0.1™ + standard. With API Level 14, you can now decode compressed audio (e.g. MP3, AAC, + Vorbis) to PCM. For more details, see docs/opensles/index.html and + http://www.khronos.org/opensles/.
      • +
      +
    • + +
    • Added CCache support. To speed up large rebuilds, define the + NDK_CCACHE environment variable to ccache (or the path to + your ccache binary). When declared, the NDK build system automatically + uses CCache when compiling any source file. For example: +
      +export NDK_CCACHE=ccache
      +
      +

      Note: CCache is not included in the NDK release + so you must have it installed prior to using it. For more information about CCache, see + http://ccache.samba.org.

      +
    • + +
    • Added support for setting APP_ABI to all to indicate that + you want to build your NDK modules for all the ABIs supported by your given NDK + release. This means that either one of the following two lines in your + Application.mk are equivalent with this release: +
      +APP_ABI := all
      +APP_ABI := armeabi armeabi-v7a x86
      +
      + +

      This also works if you define APP_ABI when calling + ndk-build from the command-line, which is a quick way to check that your + project builds for all supported ABIs without changing the project's + Application.mk file. For example:

      +
      +ndk-build APP_ABI=all
      +
      +
    • + +
    • Added a LOCAL_CPP_FEATURES variable in Android.mk that + allows you to declare which C++ features (RTTI or Exceptions) your module uses. This + ensures that the final linking works correctly if you have prebuilt modules that depend + on these features. See docs/ANDROID-MK.html and + docs/CPLUSPLUS-SUPPORT.html for more details.
    • + +
    • Shortened paths to source and object files that are used in build commands. When + invoking $NDK/ndk-build from your project path, the paths to the source, + object, and binary files that are passed to the build commands are significantly + shorter now, because they are passed relative to the current directory. This is useful + when building projects with a lot of source files, to avoid limits on the maximum + command line length supported by your host operating system. The behavior is unchanged + if you invoke ndk-build from a sub-directory of your project tree, or if + you define NDK_PROJECT_PATH to point to a specific directory.
    • +
    +
    + +
    Experimental features
    + +
    + You can now build your NDK source files on Windows without Cygwin by calling the + ndk-build.cmd script from the command line from your project path. The + script takes exactly the same arguments as the original ndk-build script. + The Windows NDK package comes with its own prebuilt binaries for GNU Make, Awk and other + tools required by the build. You should not need to install anything else to get a + working build system. + +

    Important: ndk-gdb does not work on + Windows, so you still need Cygwin to debug.

    + +

    This feature is still experimental, so feel free to try it and report issues on the + public bug database or public forum. All samples and unit tests + shipped with the NDK succesfully compile with this feature.

    +
    + +
    Important bug fixes
    + +
    +
      +
    • Imported shared libraries are now installed by default to the target installation + location (libs/<abi>) if APP_MODULES is not defined in + your Application.mk. For example, if a top-level module foo + imports a module bar, then both libfoo.so and + libbar.so are copied to the install location. Previously, only + libfoo.so was copied, unless you listed bar in your + APP_MODULES too. If you define APP_MODULES explicitly, the + behavior is unchanged.
    • + +
    • ndk-gdb now works correctly for activities with multiple categories in + their MAIN intent filters.
    • + +
    • Static library imports are now properly transitive. For example, if a top-level + module foo imports static library bar that imports static + library zoo, the libfoo.so will now be linked against both + libbar.a and libzoo.a.
    • +
    +
    + +
    Other changes
    + +
    +
      +
    • docs/NATIVE-ACTIVITY.HTML: Fixed typo. The minimum API level should be + 9, not 8 for native activities.
    • + +
    • docs/STABLE-APIS.html: Added missing documentation listing EGL as a + supported stable API, starting from API level 9.
    • + +
    • download-toolchain-sources.sh: Updated to download the toolchain + sources from android.googlesource.com, + which is the new location for the AOSP servers.
    • + +
    • Added a new C++ support runtime named gabi++. More details about it + are available in the updated docs/CPLUSPLUS-SUPPORT.html.
    • + +
    • Added a new C++ support runtime named gnustl_shared that corresponds + to the shared library version of GNU libstdc++ v3 (GPLv3 license). See more info at + docs/CPLUSPLUS-SUPPORT.html
    • + +
    • Added support for RTTI in the STLport C++ runtimes (no support for + exceptions).
    • + +
    • Added support for multiple file extensions in LOCAL_CPP_EXTENSION. For + example, to compile both foo.cpp and bar.cxx as C++ sources, + declare the following: +
      +LOCAL_CPP_EXTENSION := .cpp .cxx
      +
      +
    • + +
    • Removed many unwanted exported symbols from the link-time shared system libraries + provided by the NDK. This ensures that code generated with the standalone toolchain + doesn't risk to accidentally depend on a non-stable ABI symbol (e.g. any libgcc.a + symbol that changes each time the toolchain used to build the platform is changed)
    • + +
    • Refreshed the EGL and OpenGLES Khronos headers to support more extensions. Note + that this does not change the NDK ABIs for the corresponding libraries, + because each extension must be probed at runtime by the client application. + +

      The extensions that are available depend on your actual device and GPU drivers, + not the platform version the device runs on. The header changes simply add new + constants and types to make it easier to use the extensions when they have been + probed with eglGetProcAddress() or glGetProcAddress(). The + following list describes the newly supported extensions:

      + +
      +
      GLES 1.x
      + +
      +
        +
      • GL_OES_vertex_array_object
      • + +
      • GL_OES_EGL_image_external
      • + +
      • GL_APPLE_texture_2D_limited_npot
      • + +
      • GL_EXT_blend_minmax
      • + +
      • GL_EXT_discard_framebuffer
      • + +
      • GL_EXT_multi_draw_arrays
      • + +
      • GL_EXT_read_format_bgra
      • + +
      • GL_EXT_texture_filter_anisotropic
      • + +
      • GL_EXT_texture_format_BGRA8888
      • + +
      • GL_EXT_texture_lod_bias
      • + +
      • GL_IMG_read_format
      • + +
      • GL_IMG_texture_compression_pvrtc
      • + +
      • GL_IMG_texture_env_enhanced_fixed_function
      • + +
      • GL_IMG_user_clip_plane
      • + +
      • GL_IMG_multisampled_render_to_texture
      • + +
      • GL_NV_fence
      • + +
      • GL_QCOM_driver_control
      • + +
      • GL_QCOM_extended_get
      • + +
      • GL_QCOM_extended_get2
      • + +
      • GL_QCOM_perfmon_global_mode
      • + +
      • GL_QCOM_writeonly_rendering
      • + +
      • GL_QCOM_tiled_rendering
      • +
      +
      + +
      GLES 2.0
      + +
      +
        +
      • GL_OES_element_index_uint
      • + +
      • GL_OES_get_program_binary
      • + +
      • GL_OES_mapbuffer
      • + +
      • GL_OES_packed_depth_stencil
      • + +
      • GL_OES_texture_3D
      • + +
      • GL_OES_texture_float
      • + +
      • GL_OES_texture_float_linear
      • + +
      • GL_OES_texture_half_float_linear
      • + +
      • GL_OES_texture_npot
      • + +
      • GL_OES_vertex_array_object
      • + +
      • GL_OES_EGL_image_external
      • + +
      • GL_AMD_program_binary_Z400
      • + +
      • GL_EXT_blend_minmax
      • + +
      • GL_EXT_discard_framebuffer
      • + +
      • GL_EXT_multi_draw_arrays
      • + +
      • GL_EXT_read_format_bgra
      • + +
      • GL_EXT_texture_format_BGRA8888
      • + +
      • GL_EXT_texture_compression_dxt1
      • + +
      • GL_IMG_program_binary
      • + +
      • GL_IMG_read_format
      • + +
      • GL_IMG_shader_binary
      • + +
      • GL_IMG_texture_compression_pvrtc
      • + +
      • GL_IMG_multisampled_render_to_texture
      • + +
      • GL_NV_coverage_sample
      • + +
      • GL_NV_depth_nonlinear
      • + +
      • GL_QCOM_extended_get
      • + +
      • GL_QCOM_extended_get2
      • + +
      • GL_QCOM_writeonly_rendering
      • + +
      • GL_QCOM_tiled_rendering
      • +
      +
      + +
      EGL
      + +
      +
        +
      • EGL_ANDROID_recordable
      • + +
      • EGL_NV_system_time
      • +
      +
      +
      +
    • +
    +
    +
    +
    +
    + + + +
    + + Android NDK, Revision 6b (August 2011) + +
    +

    This release of the NDK does not include any new features compared to r6. The r6b release + addresses the following issues in the r6 release:

    +
    +
    Important bug fixes
    +
    +
      +
    • Fixed the build when APP_ABI="armeabi x86" is used for + multi-architecture builds.
    • +
    • Fixed the location of prebuilt STLport binaries in the NDK release package. + A bug in the packaging script placed them in the wrong location.
    • +
    • Fixed atexit() usage in shared libraries with the x86standalone + toolchain.
    • +
    • Fixed make-standalone-toolchain.sh --arch=x86. It used to fail + to copy the proper GNU libstdc++ binaries to the right location.
    • +
    • Fixed the standalone toolchain linker warnings about missing the definition and + size for the __dso_handle symbol (ARM only).
    • +
    • Fixed the inclusion order of $(SYSROOT)/usr/include for x86 builds. + See the bug for + more information.
    • +
    • Fixed the definitions of ptrdiff_t and size_t in + x86-specific systems when they are used with the x86 standalone toolchain.
    • +
    +
    +
    +
    +
    + +
    + + Android NDK, Revision 6 (July 2011) + +
    +

    This release of the NDK includes support for the x86 ABI and other minor changes. + For detailed information describing the changes in this release, read the + CHANGES.HTML document included in the NDK package. +

    +
    +
    General notes:
    +
    +
      +
    • Adds support for the x86 ABI, which allows you to generate machine code + that runs on compatible x86-based Android devices. Major features for x86 + include x86-specific toolchains, system headers, libraries and + debugging support. For all of the details regarding x86 support, + see docs/CPU-X86.html in the NDK package. + +

      By default, code is generated for ARM-based devices, but you can add x86 to your + APP_ABI definition in your Application.mk file to build + for x86 platforms. For example, the following line instructs ndk-build + to build your code for three distinct ABIs:

      + +
      APP_ABI := armeabi armeabi-v7a x86
      + +

      Unless you rely on ARM-based assembly sources, you shouldn't need to touch + your Android.mk files to build x86 machine code.

      + +
    • + +
    • You can build a standalone x86 toolchain using the --toolchain=x86-4.4.3 + option when calling make-standalone-toolchain.sh. See + docs/STANDALONE-TOOLCHAIN.html for more details. +
    • +
    • The new ndk-stack tool lets you translate stack traces in + logcat that are generated by native code. The tool translates + instruction addresses into a readable format that contains things such + as the function, source file, and line number corresponding to each stack frame. + For more information and a usage example, see docs/NDK-STACK.html. +
    • +
    +
    +
    Other changes:
    +
    arm-eabi-4.4.0, which had been deprecated since NDK r5, has been + removed from the NDK distribution.
    + +
    +
    +
    + +
    + + Android NDK, Revision 5c (June 2011) + +
    +

    This release of the NDK does not include any new features compared to r5b. The r5c release + addresses the following problems in the r5b release:

    +
    +
    Important bug fixes:
    +
    +
      +
    • ndk-build: Fixed a rare bug that appeared when trying to perform parallel + builds of debuggable projects.
    • + +
    • Fixed a typo that prevented LOCAL_WHOLE_STATIC_LIBRARIES to work + correctly with the new toolchain and added documentation for this in + docs/ANDROID-MK.html.
    • + +
    • Fixed a bug where code linked against gnustl_static crashed when run on + platform releases older than API level 8 (Android 2.2).
    • + +
    • ndk-gdb: Fixed a bug that caused a segmentation fault when debugging Android 3.0 + or newer devices.
    • + +
    • <android/input.h>: Two functions that were introduced in API level + 9 (Android 2.3) were incorrect and are fixed. While this breaks the source API, the + binary interface to the system is unchanged. The incorrect functions were missing a + history_index parameter, and the correct definitions are shown below: +
      +float AMotionEvent_getHistoricalRawX(const AInputEvent* motion_event,
      +                                           size_t pointer_index,
      +                                           size_t history_index);
      +
      +float AMotionEvent_getHistoricalRawY(const AInputEvent* motion_event,
      +                                           size_t pointer_index,
      +                                           size_t history_index);
      +
      +
    • + +
    • Updated the C library ARM binary for API level 9 (Android 2.3) to correctly expose at + link time new functions that were added in that API level (for example, + pthread_rwlock_init).
    • + +
    +
    + +
    Minor improvements and fixes:
    +
    +
      +
    • Object files are now always linked in the order they appear in + LOCAL_SRC_FILES. This was not the case previously because the files were + grouped by source extensions instead.
    • + +
    • When import-module fails, it now prints the list of directories that + were searched. This is useful to check that the NDK_MODULE_PATH definition + used by the build system is correct.
    • + +
    • When import-module succeeds, it now prints the directory where the + module was found to the log (visible with NDK_LOG=1).
    • + +
    • Increased the build speed of debuggable applications when there is a very large number + of include directories in the project.
    • + +
    • ndk-gdb: Better detection of adb shell failures and improved + error messages.
    • + +
    • <pthread.h>: Fixed the definition of + PTHREAD_RWLOCK_INITIALIZER for API level 9 (Android 2.3) and higher.
    • + +
    • Fixed an issue where a module could import itself, resulting in an infinite loop in + GNU Make.
    • + +
    • Fixed a bug that caused the build to fail if LOCAL_ARM_NEON was set to + true (typo in build/core/build-binary.mk).
    • + +
    • Fixed a bug that prevented the compilation of .s assembly files + (.S files were okay).
    • +
    +
    +
    +
    + +
    + Android NDK, Revision 5b (January 2011) + +
    +

    This release of the NDK does not include any new features compared to r5. The r5b release addresses the + following problems in the r5 release: +

    +
      +
    • The r5 binaries required glibc 2.11, but the r5b binaries are generated with a special + toolchain that targets glibc 2.7 or higher instead. The Linux toolchain binaries now run on Ubuntu 8.04 or higher.
    • +
    • Fixes a compiler bug in the arm-linux-androideabi-4.4.3 toolchain. + The previous binary generated invalid thumb instruction sequences when + dealing with signed chars.
    • +
    • Adds missing documentation for the + "gnustl_static" value for APP_STL, that allows you to link against + a static library version of GNU libstdc++.
    • +
    • The following ndk-build issues are fixed: +
        +
      • A bug that created inconsistent dependency files when a + compilation error occured on Windows. This prevented a proper build after + the error was fixed in the source code.
      • +
      • A Cygwin-specific bug where using very short paths for + the Android NDK installation or the project path led to the + generation of invalid dependency files. This made incremental builds + impossible.
      • +
      • A typo that prevented the cpufeatures library from working correctly + with the new NDK toolchain.
      • +
      • Builds in Cygwin are faster by avoiding calls to cygpath -m + from GNU Make for every source or object file, which caused problems + with very large source trees. In case this doesn't work properly, define NDK_USE_CYGPATH=1 in your + environment to use cygpath -m again.
      • +
      • The Cygwin installation now notifies the user of invalid installation paths that contain spaces. Previously, an invalid path + would output an error that complained about an incorrect version of GNU Make, even if the right one was installed. +
      +
    • +
    • Fixed a typo that prevented the NDK_MODULE_PATH environment variable from working properly when + it contained multiple directories separated with a colon.
    • +
    • The prebuilt-common.sh script contains fixes to check the compiler for 64-bit + generated machine code, instead of relying on the host tag, which + allows the 32-bit toolchain to rebuild properly on Snow Leopard. The toolchain rebuild scripts now also support + using a 32-bit host toolchain.
    • +
    • A missing declaration for INET_ADDRSTRLEN was added to <netinet/in.h>.
    • +
    • Missing declarations for IN6_IS_ADDR_MC_NODELOCAL and IN6_IS_ADDR_MC_GLOBAL were added to <netinet/in6.h>.
    • +
    • 'asm' was replaced with '__asm__' in <asm/byteorder.h> to allow compilation with -std=c99.
    • +
    +
    +
    + +
    + Android NDK, Revision 5 (December 2010) + +
    +

    This release of the NDK includes many new APIs, most of which are introduced to + support the development of games and similar applications that make extensive use + of native code. Using the APIs, developers have direct native access to events, audio, + graphics and window management, assets, and storage. Developers can also implement the + Android application lifecycle in native code with help from the new + {@link android.app.NativeActivity} class. For detailed information describing the changes in this + release, read the CHANGES.HTML document included in the downloaded NDK package. +

    +
    +
    General notes:
    +
    +
      +
    • Adds support for native activities, which allows you to implement the + Android application lifecycle in native code.
    • + +
    • Adds native support for the following: + +
        + +
      • Input subsystem (such as the keyboard and touch screen)
      • + +
      • Access to sensor data (accelerometer, compass, gyroscope, etc).
      • + +
      • Event loop APIs to wait for things such as input and sensor events.
      • + +
      • Window and surface subsystem
      • + +
      • Audio APIs based on the OpenSL ES standard that support playback and recording + as well as control over platform audio effects
      • + +
      • Access to assets packaged in an .apk file.
      • + +
      +
    • + +
    • Includes a new toolchain (based on GCC 4.4.3), which generates better code, and can also now + be used as a standalone cross-compiler, for people who want to build their stuff with + ./configure && make. See + docs/STANDALONE-TOOLCHAIN.html for the details. The binaries for GCC 4.4.0 are still provided, + but the 4.2.1 binaries were removed.
    • + +
    • Adds support for prebuilt static and shared libraries (docs/PREBUILTS.html) and module + exports and imports to make sharing and reuse of third-party modules much easier + (docs/IMPORT-MODULE.html explains why).
    • + +
    • Provides a default C++ STL implementation (based on STLport) as a helper module. It can be used either + as a static or shared library (details and usage examples are in sources/android/stlport/README). Prebuilt + binaries for STLport (static or shared) and GNU libstdc++ (static only) are also provided if you choose to + compile against those libraries instead of the default C++ STL implementation. + C++ Exceptions and RTTI are not supported in the default STL implementation. For more information, see + docs/CPLUSPLUS-SUPPORT.HTML.
    • + +
    • Includes improvements to the cpufeatures helper library that improves reporting + of the CPU type (some devices previously reported ARMv7 CPU when the device really was an ARMv6). We + recommend developers that use this library to rebuild their applications then + upload to Google Play to benefit from the improvements.
    • + +
    • Adds an EGL library that lets you create and manage OpenGL ES textures and + services.
    • + +
    • Adds new sample applications, native-plasma and native-activity, + to demonstrate how to write a native activity.
    • + +
    • Includes many bugfixes and other small improvements; see docs/CHANGES.html for a more + detailed list of changes.
    • +
    +
    +
    +
    +
    + +
    + Android NDK, Revision 4b (June 2010) + +
    +
    +
    NDK r4b notes:
    + +
    +

    Includes fixes for several issues in the NDK build and debugging scripts — if + you are using NDK r4, we recommend downloading the NDK r4b build. For detailed + information describing the changes in this release, read the CHANGES.TXT document + included in the downloaded NDK package.

    +
    +
    + +
    +
    General notes:
    + +
    +
      +
    • Provides a simplified build system through the new ndk-build build + command.
    • + +
    • Adds support for easy native debugging of generated machine code on production + devices through the new ndk-gdb command.
    • + +
    • Adds a new Android-specific ABI for ARM-based CPU architectures, + armeabi-v7a. The new ABI extends the existing armeabi ABI to + include these CPU instruction set extensions: + +
        +
      • Thumb-2 instructions
      • + +
      • VFP hardware FPU instructions (VFPv3-D16)
      • + +
      • Optional support for ARM Advanced SIMD (NEON) GCC intrinsics and VFPv3-D32. + Supported by devices such as Verizon Droid by Motorola, Google Nexus One, and + others.
      • +
      +
    • + +
    • Adds a new cpufeatures static library (with sources) that lets your + app detect the host device's CPU features at runtime. Specifically, applications can + check for ARMv7-A support, as well as VFPv3-D32 and NEON support, then provide separate + code paths as needed.
    • + +
    • Adds a sample application, hello-neon, that illustrates how to use the + cpufeatures library to check CPU features and then provide an optimized + code path using NEON instrinsics, if supported by the CPU.
    • + +
    • Lets you generate machine code for either or both of the instruction sets supported + by the NDK. For example, you can build for both ARMv5 and ARMv7-A architectures at the + same time and have everything stored to your application's final + .apk.
    • + +
    • To ensure that your applications are available to users only if their devices are + capable of running them, Google Play now filters applications based on the + instruction set information included in your application — no action is needed on + your part to enable the filtering. Additionally, the Android system itself also checks + your application at install time and allows the installation to continue only if the + application provides a library that is compiled for the device's CPU architecture.
    • + +
    • Adds support for Android 2.2, including a new stable API for accessing the pixel + buffers of {@link android.graphics.Bitmap} objects from native code.
    • +
    +
    +
    +
    +
    + +
    + Android NDK, Revision 3 (March 2010) + +
    +
    +
    General notes:
    + +
    +
      +
    • Adds OpenGL ES 2.0 native library support.
    • + +
    • Adds a sample application,hello-gl2, that illustrates the use of + OpenGL ES 2.0 vertex and fragment shaders.
    • + +
    • The toolchain binaries have been refreshed for this release with GCC 4.4.0, which + should generate slightly more compact and efficient machine code than the previous one + (4.2.1). The NDK also still provides the 4.2.1 binaries, which you can optionally use + to build your machine code.
    • +
    +
    +
    +
    +
    + +
    + Android NDK, Revision 2 (September 2009) + +
    +

    Originally released as "Android 1.6 NDK, Release 1".

    + +
    +
    General notes:
    + +
    +
      +
    • Adds OpenGL ES 1.1 native library support.
    • + +
    • Adds a sample application, san-angeles, that renders 3D graphics + through the native OpenGL ES APIs, while managing activity lifecycle with a {@link + android.opengl.GLSurfaceView} object.
    • +
    +
    +
    +
    +
    + +
    + Android NDK, Revision 1 (June 2009) + +
    +

    Originally released as "Android 1.5 NDK, Release 1".

    + +
    +
    General notes:
    + +
    +
      +
    • Includes compiler support (GCC) for ARMv5TE instructions, including Thumb-1 + instructions.
    • + +
    • Includes system headers for stable native APIs, documentation, and sample + applications.
    • +
    +
    +
    +
    +
    + +

    Installing the NDK

    +

    Installing the NDK on your development computer is straightforward and involves extracting the + NDK from its download package.

    + +

    Before you get started make sure that you have downloaded the latest Android SDK and upgraded your applications and environment as + needed. The NDK is compatible with older platform versions but not older versions of the SDK tools. + Also, take a moment to review the System and +Software Requirements + for the NDK, if you haven't already.

    + +

    To install the NDK, follow these steps:

    + +
      +
    1. From the table at the top of this page, select the NDK package that is appropriate for your + development computer and download the package.
    2. + +
    3. Uncompress the NDK download package using tools available on your computer. When + uncompressed, the NDK files are contained in a directory called + android-ndk-<version>. You can rename the NDK directory if necessary and you + can move it to any location on your computer. This documentation refers to the NDK directory as + <ndk>.
    4. +
    + +

    You are now ready to start working with the NDK.

    + +

    Getting Started with the NDK

    + +

    Once you've installed the NDK successfully, take a few minutes to read the documentation + included in the NDK. You can find the documentation in the <ndk>/docs/ + directory. In particular, please read the OVERVIEW.HTML document completely, so that you + understand the intent of the NDK and how to use it.

    + +

    If you used a previous version of the NDK, take a moment to review the list of NDK changes in + the CHANGES.HTML document.

    + +

    Here's the general outline of how you work with the NDK tools:

    + +
      +
    1. Place your native sources under <project>/jni/...
    2. + +
    3. Create <project>/jni/Android.mk to describe your native sources to the + NDK build system
    4. + +
    5. Optional: Create <project>/jni/Application.mk.
    6. + +
    7. Build your native code by running the 'ndk-build' script from your project's directory. It + is located in the top-level NDK directory: +
      cd <project>
      +<ndk>/ndk-build
      +
      + +

      The build tools copy the stripped, shared libraries needed by your application to the + proper location in the application's project directory.

      +
    8. + +
    9. Finally, compile your application using the SDK tools in the usual way. The SDK build tools + will package the shared libraries in the application's deployable .apk file.
    10. +
    + +

    For complete information on all of the steps listed above, please see the documentation + included with the NDK package.

    + +

    Sample Applications

    + +

    The NDK includes sample Android applications that illustrate how to use native code in your + Android applications. For more information, see Sample Applications.

    + +

    Discussion Forum and Mailing List

    + +

    If you have questions about the NDK or would like to read or contribute to discussions about + it, please visit the android-ndk group + and mailing list.

    diff --git a/docs/html/tools/sdk/ndk/overview.jd b/docs/html/tools/sdk/ndk/overview.jd new file mode 100644 index 000000000000..98ef1fcc7a77 --- /dev/null +++ b/docs/html/tools/sdk/ndk/overview.jd @@ -0,0 +1,588 @@ +page.title=What is the NDK? +@jd:body + + + +

    The Android NDK is a toolset that lets you embed components that make use of native code in + your Android applications.

    + +

    Android applications run in the Dalvik virtual machine. The NDK allows you to implement parts + of your applications using native-code languages such as C and C++. This can provide benefits to + certain classes of applications, in the form of reuse of existing code and in some cases + increased speed.

    + +

    The NDK provides:

    + +
      +
    • A set of tools and build files used to generate native code libraries from C and C++ + sources
    • + +
    • A way to embed the corresponding native libraries into an application package file + (.apk) that can be deployed on Android devices
    • + +
    • A set of native system headers and libraries that will be supported in all future versions + of the Android platform, starting from Android 1.5. Applications that use native activities + must be run on Android 2.3 or later.
    • + +
    • Documentation, samples, and tutorials
    • +
    + +

    The latest release of the NDK supports the following instruction sets:

    + +
      +
    • ARMv5TE, including Thumb-1 instructions (see {@code docs/CPU-ARCH-ABIS.html} for more +information)
    • + +
    • ARMv7-A, including Thumb-2 and VFPv3-D16 instructions, with optional support for + NEON/VFPv3-D32 instructions (see {@code docs/CPU-ARM-NEON.html} for more information)
    • + +
    • x86 instructions (see {@code docs/CPU-X86.html} for more information)
    • + +
    • MIPS instructions (see {@code docs/CPU-MIPS.html} for more information)
    • +
    + +

    ARMv5TE machine code will run on all ARM-based Android devices. ARMv7-A will run only on + devices such as the Verizon Droid or Google Nexus One that have a compatible CPU. The main + difference between the two instruction sets is that ARMv7-A supports hardware FPU, Thumb-2, and + NEON instructions. You can target either or both of the instruction sets — ARMv5TE is the + default, but switching to ARMv7-A is as easy as adding a single line to the application's + Application.mk file, without needing to change anything else in the file. You can also build for + both architectures at the same time and have everything stored in the final .apk. + Complete information is provided in the CPU-ARCH-ABIS.HTML in the NDK package.

    + +

    The NDK provides stable headers for libc (the C library), libm (the Math library), OpenGL ES + (3D graphics library), the JNI interface, and other libraries, as listed in the Development Tools section.

    + +

    When to Develop in Native Code

    + +

    The NDK will not benefit most applications. As a developer, you need to balance its benefits + against its drawbacks; notably, using native code does not result in an automatic performance + increase, but always increases application complexity. In general, you should only use native + code if it is essential to your application, not just because you prefer to program in C/C++.

    + +

    Typical good candidates for the NDK are self-contained, CPU-intensive operations that don't + allocate much memory, such as signal processing, physics simulation, and so on. Simply re-coding + a method to run in C usually does not result in a large performance increase. When examining + whether or not you should develop in native code, think about your requirements and see if the + Android framework APIs provide the functionality that you need. The NDK can, however, can be an + effective way to reuse a large corpus of existing C/C++ code.

    + +

    The Android framework provides two ways to use native code:

    + +
      +
    • Write your application using the Android framework and use JNI to access the APIs provided + by the Android NDK. This technique allows you to take advantage of the convenience of the + Android framework, but still allows you to write native code when necessary. If you use this + approach, your application must target specific, minimum Android platform levels, see Android platform compatibility for more information.
    • + +
    • +

      Write a native activity, which allows you to implement the lifecycle callbacks in native + code. The Android SDK provides the {@link android.app.NativeActivity} class, which is a + convenience class that notifies your + native code of any activity lifecycle callbacks (onCreate(), onPause(), + onResume(), etc). You can implement the callbacks in your native code to handle + these events when they occur. Applications that use native activities must be run on Android + 2.3 (API Level 9) or later.

      + +

      You cannot access features such as Services and Content Providers natively, so if you want + to use them or any other framework API, you can still write JNI code to do so.

      +
    • +
    + +

    Contents of the NDK

    The NDK contains the APIs, documentation, and sample + applications that help you write your native code. + +

    Development tools

    + +

    The NDK includes a set of cross-toolchains (compilers, linkers, etc..) that can generate + native ARM binaries on Linux, OS X, and Windows (with Cygwin) platforms.

    + +

    It provides a set of system headers for stable native APIs that are guaranteed to be supported + in all later releases of the platform:

    + +
      +
    • libc (C library) headers
    • + +
    • libm (math library) headers
    • + +
    • JNI interface headers
    • + +
    • libz (Zlib compression) headers
    • + +
    • liblog (Android logging) header
    • + +
    • OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headers
    • + +
    • libjnigraphics (Pixel buffer access) header (for Android 2.2 and above).
    • + +
    • A Minimal set of headers for C++ support
    • + +
    • OpenSL ES native audio libraries
    • + +
    • Android native application APIS
    • +
    + +

    The NDK also provides a build system that lets you work efficiently with your sources, without + having to handle the toolchain/platform/CPU/ABI details. You create very short build files to + describe which sources to compile and which Android application will use them — the build + system compiles the sources and places the shared libraries directly in your application + project.

    + +

    Important: With the exception of the libraries listed above, + native system libraries in the Android platform are not stable and may change in future + platform versions. Your applications should only make use of the stable native system + libraries provided in this NDK.

    + +

    Documentation

    + +

    The NDK package includes a set of documentation that describes the capabilities of the NDK and + how to use it to create shared libraries for your Android applications. In this release, the + documentation is provided only in the downloadable NDK package. You can find the documentation in + the <ndk>/docs/ directory. Included are these files (partial listing):

    + +
      +
    • + INSTALL.HTML — describes how to install the NDK and configure it for your host + system
    • + +
    • OVERVIEW.HTML — provides an overview of the NDK capabilities and usage
    • + +
    • ANDROID-MK.HTML — describes the use of the Android.mk file, which defines the native + sources you want to compile
    • + +
    • APPLICATION-MK.HTML — describes the use of the Application.mk file, which describes + the native sources required by your Android application
    • +
    • CPLUSPLUS-SUPPORT.HTML — describes the C++ support provided in the Android NDK
    • +
    • CPU-ARCH-ABIS.HTML — a description of supported CPU architectures and how to target + them.
    • + +
    • CPU-FEATURES.HTML — a description of the cpufeatures static library that + lets your application code detect the target device's CPU family and the optional features at + runtime.
    • + +
    • CHANGES.HTML — a complete list of changes to the NDK across all releases.
    • + +
    • DEVELOPMENT.HTML — describes how to modify the NDK and generate release packages for it
    • + +
    • HOWTO.HTML — information about common tasks associated with NDK development
    • + +
    • IMPORT-MODULE.HTML — describes how to share and reuse modules
    • + +
    • LICENSES.HTML — information about the various open source licenses that govern the Android NDK
    • + +
    • NATIVE-ACTIVITY.HTML — describes how to implement native activities
    • + +
    • NDK-BUILD.HTML — describes the usage of the ndk-build script
    • + +
    • NDK-GDB.HTML — describes how to use the native code debugger
    • + +
    • PREBUILTS.HTML — information about how shared and static prebuilt libraries work
    • + +
    • STANDALONE-TOOLCHAIN.HTML — describes how to use Android NDK toolchain as a standalone + compiler (still in beta).
    • + +
    • SYSTEM-ISSUES.HTML — known issues in the Android system images that you should be + aware of, if you are developing using the NDK.
    • + +
    • STABLE-APIS.HTML — a complete list of the stable APIs exposed by headers in the + NDK.
    • + +
    + +

    Additionally, the package includes detailed information about the "bionic" C library provided + with the Android platform that you should be aware of, if you are developing using the NDK. You + can find the documentation in the <ndk>/docs/system/libc/ directory:

    + +
      +
    • OVERVIEW.HTML — provides an overview of the "bionic" C library and the features it + offers.
    • +
    + +

    Sample applications

    + +

    The NDK includes sample applications that illustrate how to use native code in your Android + applications:

    + +
      +
    • hello-jni — a simple application that loads a string from a native + method implemented in a shared library and then displays it in the application UI.
    • + +
    • two-libs — a simple application that loads a shared library dynamically + and calls a native method provided by the library. In this case, the method is implemented in a + static library imported by the shared library.
    • + +
    • san-angeles — a simple application that renders 3D graphics through the + native OpenGL ES APIs, while managing activity lifecycle with a {@link + android.opengl.GLSurfaceView} object.
    • + +
    • hello-gl2 — a simple application that renders a triangle using OpenGL ES + 2.0 vertex and fragment shaders.
    • + +
    • hello-neon — a simple application that shows how to use the + cpufeatures library to check CPU capabilities at runtime, then use NEON intrinsics + if supported by the CPU. Specifically, the application implements two versions of a tiny + benchmark for a FIR filter loop, a C version and a NEON-optimized version for devices that + support it.
    • + +
    • bitmap-plasma — a simple application that demonstrates how to access the + pixel buffers of Android {@link android.graphics.Bitmap} objects from native code, and uses + this to generate an old-school "plasma" effect.
    • + +
    • native-activity — a simple application that demonstrates how to use the + native-app-glue static library to create a native activity
    • + +
    • native-plasma — a version of bitmap-plasma implemented with a native + activity.
    • +
    + +

    For each sample, the NDK includes the corresponding C source code and the necessary Android.mk + and Application.mk files. There are located under <ndk>/samples/<name>/ + and their source code can be found under <ndk>/samples/<name>/jni/.

    + +

    You can build the shared libraries for the sample apps by going into + <ndk>/samples/<name>/ then calling the ndk-build command. + The generated shared libraries will be located under + <ndk>/samples/<name>/libs/armeabi/ for (ARMv5TE machine code) and/or + <ndk>/samples/<name>/libs/armeabi-v7a/ for (ARMv7 machine code).

    + +

    Next, build the sample Android applications that use the shared libraries:

    + +
      +
    • If you are developing in Eclipse with ADT, use the New Project Wizard to create a new + Android project for each sample, using the "Import from Existing Source" option and importing + the source from <ndk>/samples/<name>/. Then, set up an AVD, + if necessary, and build/run the application in the emulator.
    • + +
    • If you are developing with Ant, use the android tool to create the build file + for each of the sample projects at <ndk>/samples/<name>/. + Then set up an AVD, if necessary, build your project in the usual way, and run it in the + emulator.
    • + +
    + +

    For more information about developing with the Android SDK tools and what + you need to do to create, build, and run your applications, see + the Overview + section for developing on Android.

    + +

    Exploring the hello-jni Sample

    + +

    The hello-jni sample is a simple demonstration on how to use JNI from an Android application. + The HelloJni activity receives a string from a simple C function and displays it in a + TextView.

    + +

    The main components of the sample include:

    + +
      +
    • The familiar basic structure of an Android application (an AndroidManifest.xml + file, a src/ and res directories, and a main activity)
    • + +
    • A jni/ directory that includes the implemented source file for the native code + as well as the Android.mk file
    • + +
    • A tests/ directory that contains unit test code.
    • +
    + +
      +
    1. Create a new project in Eclipse from the existing sample source or use the + android tool to update the project so it generates a build.xml file that you can + use to build the sample. + +
        +
      • In Eclipse: + +
          +
        1. Click File > New Android Project...
        2. + +
        3. Select the Create project from existing source radio button.
        4. + +
        5. Select any API level above Android 1.5.
        6. + +
        7. In the Location field, click Browse... and select + the <ndk-root>/samples/hello-jni directory.
        8. + +
        9. Click Finish.
        10. +
        +
      • + +
      • On the command line: + +
          +
        1. Change to the <ndk-root>/samples/hello-jni directory.
        2. + +
        3. Run the following command to generate a build.xml file: +
          android update project -p . -s
          +
        4. +
        +
      • +
      +
    2. + +
    3. Compile the native code using the ndk-build command. +
      +cd <ndk-root>/samples/hello-jni
      +<ndk_root>/ndk-build
      +
      +
    4. + +
    5. Build and install the application as you would a normal Android application. If you are + using Eclipse, run the application to build and install it on a device. If you are using Ant, + run the following commands from the project directory: +
      +ant debug
      +adb install bin/HelloJni-debug.apk
      +
      +
    6. +
    + +

    When you run the application on the device, the string Hello JNI should appear on + your device. You can explore the rest of the samples that are located in the + <ndk-root>/samples directory for more examples on how to use the JNI.

    + +

    Exploring the native-activity Sample Application

    + +

    The native-activity sample provided with the Android NDK demonstrates how to use the + android_native_app_glue static library. This static library makes creating a native activity + easier by providing you with an implementation that handles your callbacks in another thread, so + you do not have to worry about them blocking your main UI thread. The main parts of the sample + are described below:

    + +
      +
    • The familiar basic structure of an Android application (an AndroidManifest.xml + file, a src/ and res directories). The AndroidManifest.xml declares + that the application is native and specifies the .so file of the native activity. See {@link + android.app.NativeActivity} for the source or see the + <ndk_root>/platforms/samples/native-activity/AndroidManifest.xml file.
    • + +
    • A jni/ directory contains the native activity, main.c, which uses the + android_native_app_glue.h interface to implement the activity. The Android.mk that + describes the native module to the build system also exists here.
    • +
    + +

    To build this sample application:

    + +
      +
    1. Create a new project in Eclipse from the existing sample source or use the + android tool to update the project so it generates a build.xml file that you can + use to build the sample. + +
        +
      • In Eclipse: + +
          +
        1. Click File > New Android Project...
        2. + +
        3. Select the Create project from existing source radio button.
        4. + +
        5. Select any API level above Android 2.3.
        6. + +
        7. In the Location field, click Browse... and select + the <ndk-root>/samples/native-activity directory.
        8. + +
        9. Click Finish.
        10. +
        +
      • + +
      • On the command line: + +
          +
        1. Change to the <ndk-root>/samples/native-activity directory.
        2. + +
        3. Run the following command to generate a build.xml file: +
          +android update project -p . -s
          +
          +
        4. +
        +
      • +
      +
    2. + +
    3. Compile the native code using the ndk-build command. +
      +cd <ndk-root>/platforms/samples/android-9/samples/native-activity
      +<ndk_root>/ndk-build
      +
      +
    4. + +
    5. Build and install the application as you would a normal Android application. If you are + using Eclipse, run the application to build and install it on a device. If you are using Ant, + run the following commands in the project directory, then run the application on the device: +
      +ant debug
      +adb install bin/NativeActivity-debug.apk
      +
      +
    6. +
    + + +

    System and Software Requirements

    + +

    The sections below describe the system and software requirements for using the Android NDK, as + well as platform compatibility considerations that affect appplications using libraries produced + with the NDK.

    + +

    The Android SDK

    + +
      +
    • A complete Android SDK installation (including all dependencies) is required.
    • + +
    • Android 1.5 SDK or later version is required.
    • +
    + +

    Supported operating systems

    + +
      +
    • Windows XP (32-bit) or Vista (32- or 64-bit)
    • + +
    • Mac OS X 10.4.8 or later (x86 only)
    • + +
    • Linux (32 or 64-bit; Ubuntu 8.04, or other Linux distributions using GLibc 2.7 or +later)
    • +
    + +

    Required development tools

    + +
      +
    • For all development platforms, GNU Make 3.81 or later is required. Earlier versions of GNU + Make might work but have not been tested.
    • + +
    • A recent version of awk (either GNU Awk or Nawk) is also required.
    • + +
    • For Windows, Cygwin 1.7 or higher is required. The NDK + will not work with Cygwin 1.5 installations.
    • +
    + +

    Android platform compatibility

    + +
      +
    • The native libraries created by the Android NDK can only be used on devices running + specific minimum Android platform versions. The minimum required platform version depends on + the CPU architecture of the devices you are targeting. The following table details which + Android platform versions are compatible with native code developed for specific CPU + architectures. + + + + + + + + + + + + + + + + + + + + + +
      Native Code CPU Architecture UsedCompatible Android Platform(s)
      ARM, ARM-NEONAndroid 1.5 (API Level 3) and higher
      x86Android 2.3 (API Level 9) and higher
      MIPSAndroid 2.3 (API Level 9) and higher
      + +

      These requirements mean you can use native libraries produced with the NDK in + applications that are deployable to ARM-based devices running Android 1.5 or later. If you are + deploying native libraries to x86 and MIPS-based devices, your application must target Android + 2.3 or later.

      +
    • + +
    • To ensure compatibility, an application using a native library produced with the NDK + must declare a + <uses-sdk> element in its manifest file, with an + android:minSdkVersion attribute value of "3" or higher. For example: + +
      +<manifest>
      +  <uses-sdk android:minSdkVersion="3" />
      +  ...
      +</manifest>
      +
      +
    • + +
    • If you use this NDK to create a native library that uses the OpenGL ES APIs, the + application containing the library can be deployed only to devices running the minimum platform + versions described in the table below. To ensure compatibility, make sure that your application + declares the proper android:minSdkVersion attribute value, as shown in the + following table.
    • + +
    • + + + + + + + + + + + + + + + + + + + + + + + + +
      OpenGL ES Version UsedCompatible Android Platform(s)Required uses-sdk Attribute
      OpenGL ES 1.1Android 1.6 (API Level 4) and higherandroid:minSdkVersion="4"
      OpenGL ES 2.0Android 2.0 (API Level 5) and higherandroid:minSdkVersion="5"
      + +

      For more information about API Level and its relationship to Android platform versions, + see Android API Levels.

      +
    • + +
    • Additionally, an application using the OpenGL ES APIs should declare a + <uses-feature> element in its manifest, with an + android:glEsVersion attribute that specifies the minimum OpenGl ES version + required by the application. This ensures that Google Play will show your application only + to users whose devices are capable of supporting your application. For example: +
      +<manifest>
      +
      +  <uses-feature android:glEsVersion="0x00020000" />
      +  ...
      +</manifest>
      +
      + +

      For more information, see the <uses-feature> + documentation.

      +
    • + +
    • If you use this NDK to create a native library that uses the API to access Android {@link + android.graphics.Bitmap} pixel buffers or utilizes native activities, the application + containing the library can be deployed only to devices running Android 2.2 (API level 8) or + higher. To ensure compatibility, make sure that your application declares <uses-sdk + android:minSdkVersion="8" /> attribute value in its manifest.
    • +
    diff --git a/docs/html/tools/sdk/older_releases.jd b/docs/html/tools/sdk/older_releases.jd new file mode 100644 index 000000000000..bb274b67aa7a --- /dev/null +++ b/docs/html/tools/sdk/older_releases.jd @@ -0,0 +1,613 @@ +page.title=SDK Archives +@jd:body + +

    This page provides a full list of archived and obsolete SDK releases, +including non-current versions of active releases and "early look" versions that +were released before Android 1.0. These are provided for +informational and archival purposes only.

    + +
    +

    If you are just starting to develop applications for Android, please +download the current Android +SDK. With the current Android SDK, you can add any current and previous +version of the Android platform as a component and use it for +development and testing.

    +

    If you already have an Android SDK for platform version 1.6 or newer, then +you do not need to install a new SDK—especially not one from this page. +You should install older platforms as components of your existing SDK. +See Exploring the SDK.

    +
    + + +

    Archived SDKs

    + +

    The tables below provides Android SDKs that are current in terms of their +platform version, but do not provide the latest Android development +environment and tools. Instead of downloading one of these, as a separate +SDK for each version of the platform, you should instead use the new +version-neutral Android SDK to download each version of +the Android platfrom as an individual component.

    + +

    Please download the current Android SDK.

    + + +

    Release 1.6 r1

    +

    September 2009 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 .6_r1.zip + 260529085 bytes2bcbacbc7af0363058ca1cac6abad848
    Mac OS X (intel) + android-sdk- +mac_x86-1 .6_r1.zip + 247412515 byteseb13cc79602d492e89103efcf48ac1f6
    Linux (i386) + android- +sdk- linux_x86-1.6_r1.tgz + 238224860 bytesb4bf0e610ff6db2fb6fb09c49cba1e79
    + + +

    Release 1.5 r3

    +

    July 2009 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 .5_r3.zip + 191477853 bytes1725fd6963ce69102ba7192568dfc711
    Mac OS X (intel) + android-sdk- +mac_x86-1 .5_r3.zip + 183024673 bytesb1bafdaefdcec89a14b604b504e7daec
    Linux (i386) + android- +sdk- linux_x86-1.5_r3.zip + 178117561 bytes350d0211678ced38da926b8c9ffa4fac
    + + +

    Release 1.1 r1

    +

    February 2009 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 +.1_r1.zip + 86038515 bytes8c4b9080b430025370689e03d20842f3
    Mac OS X (intel) + android-sdk- +mac_x86-1 +.1_r1.zip + 79046151 bytesbecf0f1763d61eedce15d2a903d6c1dd
    Linux (i386) + android- +sdk- +linux_x86-1.1_r1.zip + 79345522 bytesebcb16b0cd4aef198b4dd9a1418efbf1
    + + +

    Release 1.0 r2

    +

    November 2008 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 +.0_r2.zip + 98360564 bytesa5e1af8ac145946b4a9627516ad4a711
    Mac OS X (intel) + android-sdk- +mac_x86-1 +.0_r2.zip + 93771410 bytes87b99d5e9f59b78363a63200c11498e8
    Linux (i386) + android- +sdk- +linux_x86-1.0_r2.zip + 94186463 bytesa1f3b6d854596f850f5008856d0f380e
    + + + + +

    Obsolete SDK Releases

    + +

    These tables provide Android SDK releases that have been superceded by +an active release (shown above) and that are now obsolete.

    + + +

    Release 1.5 r2

    +

    May 2009 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 .5_r2.zip + 178346828 bytesba54ac6bda45921d442b74b6de6ff6a9
    Mac OS X (intel) + android-sdk- +mac_x86-1 .5_r2.zip + 169945128 bytesf4e06a5194410243f213d0177713d6c9
    Linux (i386) + android- +sdk- linux_x86-1.5_r2.zip + 165035130 bytes1d3c3d099e95a31c43a7b3e6ae307ed3
    + + +

    Release 1.5 r1

    +

    April 2009 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 .5_r1.zip + 176263368 bytes42be980eb2d3efaced01ea6c32c0045f
    Mac OS X (intel) + android-sdk- +mac_x86-1 .5_r1.zip + 167848675 bytes5b2a8d9f096032db4a75bfa0d689a51b
    Linux (i386) + android- +sdk- linux_x86-1.5_r1.zip + 162938845 bytes2addfd315da0ad8b5bde6b09d5ff3b06
    + + +

    Release 1.0 r1

    +

    September 23, 2008 - Release +Notes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PlatformPackageSizeMD5 Checksum
    Windows + android-sdk- +windows-1 .0_r1.zip + 89.7 MB bytesd69f4ee93d4010f726c04302662fd999
    Mac OS X (intel) + android-sdk- +mac_x86-1 .0_r1.zip + 87.5 MB bytes564876ada22872e50c2866806de9fc5c
    Linux (i386) + android- +sdk- linux_x86-1.0_r1.zip + 87.8 MB bytes2660b4029039b7d714e59827e9a9a11d
    + + + + +

    Non-Compatible SDK Releases

    + + +

    The SDKs listed below are "early-look" versions that were released in + the year preceding the full release of Android 1.0 in September 2008. Because + these early-look SDKs were released before the Android 1.0 API specification was + finalized, they do not provide a compliant Android execution environment. + Consequently, applications that you develop in these SDKs will not be able to + run on any Android-powered devices.

    + +

    If you have an older application that you built in one of the early-look +SDKs, you must migrate it to the Android 1.0 SDK (or later release) before you +will be able to deploy it to an Android-powered device. To help with this +migration, each SDK package below provides information about API changes from +the previous version. You can find the migration information in the +documentation included in each SDK package.

    + + +

    Version 0.9 Beta

    +

    August 18, 2008 - Release Notes

    + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageSizeMD5 Checksum
    Windows + +android-sdk-windows-0.9_beta.zip93,126,573 bytes305031ad8335d1b6040bdd5a65349d6d
    Mac OS X (intel) + +android-sdk-mac_x86-0.9_beta.zip91,374,464 bytes9a6969159091cede46302e11049fe3ca
    Linux (i386) +android-sdk-linux_x86-0.9_beta.zip91,821,068 bytes077e5ef549dd9c5be54bd88e6a8e196c
    + +

    Version m5-rc15

    +

    March 3, 2008 - Release Notes

    + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageSizeMD5 Checksum
    Windows + +android-sdk_m5-rc15_windows.zip79 MBecce40bc50201886d95ba2690cdbc5ce
    Mac OS X (intel) + +android-sdk_m5-rc15_mac-x86.zip76 MB45a6385bbc1b2cb295409cfc81fb04b4
    Linux (i386) + +android-sdk_m5-rc15_linux-x86.zip76 MBe913f785afecdeed34c30639fd8c5862
    + +

    Version m5-rc14

    +

    February 12, 2008 - Release Notes

    + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageSizeMD5 Checksum
    Windows + +android-sdk_m5-rc14_windows.zip79 MBecc75c1e69588350634ca25867ce05a0
    Mac OS X (intel) + +android-sdk_m5-rc14_mac-x86.zip76 MB844c80d0adb1a326f5a9fff262c61efc
    Linux (i386) + +android-sdk_m5-rc14_linux-x86.zip76 MBf8b863c8a880afe9bb84124f5976aab1
    + + + + +

    Version m3-rc37a

    +

    December 14, 2007 - Release Notes

    + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageSizeMD5 Checksum
    Windows + +android_sdk_windows_m3-rc37a.zip58 MB5db5aea20a2c2f010baefc4b1091a575
    Mac OS X (intel) + +android_sdk_darwin_m3-rc37a.zip54 MB0b22e73fbd07b4af4009387afce3a37f
    Linux (i386) + +android_sdk_linux_m3-rc37a.zip54 MB41285beecc4f9926e6ecf5f12610b356
    + + + + +

    Version m3-rc22a

    +

    November 16, 2007 - Release Notes

    + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageSizeMD5 Checksum
    Windows + +android_sdk_windows_m3-rc22a.zip59 MBaa3dee05a9872752a3bc4efd0f93e98b
    Mac OS X (intel) + +android_sdk_darwin_m3-rc22a.zip55 MB0547f45614ad94c3af22c3c0aa6f709f
    Linux (i386) + +android_sdk_linux_m3-rc22a.zip55 MB84b3455de5cdfd841a172c13d24c382e
    + + + + +

    Version m3-rc20a

    +

    November 12, 2007 - Release Notes

    + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageSizeMD5 Checksum
    Windows + +android_sdk_windows_m3-rc20a.zip59 MBa404b875708df7339ba77bdf2e08dc06
    Mac OS X (intel) + +android_sdk_darwin_m3-rc20a.zip55 MB8fc29aeaa45eda84bfac854ebd02a6da
    Linux (i386) + +android_sdk_linux_m3-rc20a.zip55 MB9196759df9b69cd89a220b156f133364
    diff --git a/docs/html/tools/sdk/platforms.jd b/docs/html/tools/sdk/platforms.jd new file mode 100644 index 000000000000..27e89dea5b6c --- /dev/null +++ b/docs/html/tools/sdk/platforms.jd @@ -0,0 +1,9 @@ +page.title=Android Development Platforms + +@jd:body + + + +

    A page that lists platforms and links to release notes. Links to dashboards etc.

    + + diff --git a/docs/html/tools/sdk/preview/features.jd b/docs/html/tools/sdk/preview/features.jd new file mode 100644 index 000000000000..02897cd5c304 --- /dev/null +++ b/docs/html/tools/sdk/preview/features.jd @@ -0,0 +1,8 @@ +@jd:body + + + +

    You should have already been redirected by your browser. Please go to the +Android 3.0 Platform.

    \ No newline at end of file diff --git a/docs/html/tools/sdk/preview/index.jd b/docs/html/tools/sdk/preview/index.jd new file mode 100644 index 000000000000..ed8f7e0d5522 --- /dev/null +++ b/docs/html/tools/sdk/preview/index.jd @@ -0,0 +1,2 @@ +sdk.redirect=true +@jd:body diff --git a/docs/html/tools/sdk/preview/installing.jd b/docs/html/tools/sdk/preview/installing.jd new file mode 100644 index 000000000000..c40e531cdf17 --- /dev/null +++ b/docs/html/tools/sdk/preview/installing.jd @@ -0,0 +1,8 @@ +@jd:body + + + +

    You should have already been redirected by your browser. Please go to +Installing the SDK.

    \ No newline at end of file diff --git a/docs/html/tools/sdk/preview/requirements.jd b/docs/html/tools/sdk/preview/requirements.jd new file mode 100644 index 000000000000..b5aed80ef644 --- /dev/null +++ b/docs/html/tools/sdk/preview/requirements.jd @@ -0,0 +1,8 @@ +@jd:body + + + +

    You should have already been redirected by your browser. Please go to the +SDK System Requirements.

    \ No newline at end of file diff --git a/docs/html/tools/sdk/preview/upgrading.jd b/docs/html/tools/sdk/preview/upgrading.jd new file mode 100644 index 000000000000..1c53bdbfe07f --- /dev/null +++ b/docs/html/tools/sdk/preview/upgrading.jd @@ -0,0 +1,8 @@ +@jd:body + + + +

    You should have already been redirected by your browser. Please go to +the Android SDK.

    \ No newline at end of file diff --git a/docs/html/tools/sdk/tools-notes.jd b/docs/html/tools/sdk/tools-notes.jd new file mode 100644 index 000000000000..f08209b31f1c --- /dev/null +++ b/docs/html/tools/sdk/tools-notes.jd @@ -0,0 +1,855 @@ +page.title=SDK Tools +@jd:body + +

    SDK Tools is a downloadable component for the Android SDK. It includes the +complete set of development and debugging tools for the Android SDK.

    + +

    If you are new to the Android SDK, the SDK starter package installs the +latest revision of the SDK Tools in the <sdk>/tools directory.

    + +

    If you are already using the SDK and you want to update to the latest version +of the SDK Tools, use the Android SDK Manager to get the +update, rather than downloading a new SDK starter package. For more information +about how to update, see Exploring the SDK.

    + + +

    Revisions

    + +

    The sections below provide notes about successive releases of +the SDK Tools, as denoted by revision number. To determine what revision of the SDK +Tools you are using, refer to the "Installed Packages" listing in the Android SDK Manager.

    + +

    For a summary of all known issues in SDK Tools, see http://tools.android.com/knownissues.

    + + + + +
    + + + SDK Tools, Revision 19 (April 2012) + +
    +

    Note: This update of SDK Tools is only available through +the Android SDK Manager. Use this tool to +download and install this update.

    + +
    +
    Dependencies:
    +
    +
      +
    • Android SDK Platform-tools revision 9 or later.
    • +
    • If you are developing in Eclipse with ADT, note that the SDK Tools r19 is designed for + use with ADT 18.0.0 and later. If you haven't already, we highly recommend updating your + ADT Plugin to 18.0.0.
    • +
    • If you are developing outside Eclipse, you must have + Apache Ant 1.8 or later.
    • +
    +
    +
    Bug fixes:
    +
    +
      +
    • Fixed an issue that prevented some developers from running the emulator with GPU +acceleration.
    • +
    +
    +
    +
    +
    + +
    + + + SDK Tools, Revision 18 (April 2012) + +
    +

    Important: To download the new Android + 4.0 system components from the Android SDK Manager, you must first update the + SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, + the Android 4.0 system components will not be available for download.

    + +
    +
    Dependencies:
    +
    +
      +
    • Android SDK Platform-tools revision 9 or later.
    • +
    • If you are developing in Eclipse with ADT, note that the SDK Tools r18 is designed for + use with ADT 18.0.0 and later. If you haven't already, we highly recommend updating your + ADT Plugin to 18.0.0.
    • +
    • If you are developing outside Eclipse, you must have + Apache Ant 1.8 or later.
    • +
    +
    +
    General notes:
    +
    +
      +
    • Updated the SdkController app to encapsulate both sensor and multitouch emulation + functionality.
    • +
    +
    +
    Bug fixes:
    +
    +
      +
    • Fixed Ant issues where some jar libraries in the {@code libs/} folder are not picked up +in some cases.
    • +
    +
    +
    +
    +
    + +
    + + + SDK Tools, Revision 17 (March 2012) + +
    +

    Important: To download the new Android + 4.0 system components from the Android SDK Manager, you must first update the + SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, + the Android 4.0 system components will not be available for download.

    + +
    +
    Dependencies:
    +
    +
      +
    • Android SDK Platform-tools revision 9 or later.
    • +
    • If you are developing in Eclipse with ADT, note that the SDK Tools r17 is designed for + use with ADT 17.0.0 and later. If you haven't already, we highly recommend updating your + ADT Plugin to 17.0.0.
    • +
    • If you are developing outside Eclipse, you must have + Apache Ant 1.8 or later.
    • +
    +
    +
    General notes:
    +
    +
      +
    • Emulator +
        +
      • Added support for hardware accelerated graphics rendering. This feature requires an +API Level 15, Revision 3 or later system image. +(more info) +
      • +
      • Added support for running Android x86 system images in virtualization mode on +Windows and Mac OS X. +(more info) +

        Note: Use the Android SDK Manager to download and +install x86 system images. Android x86 system images are not available for all API levels.

        +
      • +
      • Added experimental support for multi-touch input by enabing the emulator to receive + touch input from a USB-tethered physical Android device. + (more info)
      • +
      +
    • +
    • Added viewing of live detailed network usage of an app in DDMS. (more info)
    • +
    • ProGuard +
        +
      • Updated the bundled ProGuard tool to version 4.7. In addition to many new features, +this update fixes the {@code Conversion to Dalvik format failed with error 1} error some users have +experienced.
      • +
      • Updated the default {@code proguard.cfg} file with better default flags for + Android.
      • +
      • Split the ProGuard configuration file has been in half, with project specific flags +kept in project and the generic Android flags distributed (and updated) with the tools +themselves.
      • +
      +
    • +
    • Build +
        +
      • Added a feature that allows you to run some code only in debug mode. Builds now +generate a class called {@code BuildConfig} containing a {@code DEBUG} constant that is +automatically set according to your build type. You can check the ({@code BuildConfig.DEBUG}) +constant in your code to run debug-only functions.
      • +
      • Fixed issue when a project and its libraries include the same jar file in their libs + folder. (more + info)
      • +
      • Added support for custom views with custom attributes in libraries. Layouts using +custom attributes must use the namespace URI {@code http://schemas.android.com/apk/res-auto} instead +of the URI that includes the app package name. This URI is replaced with the app specific one at +build time.
      • +
      +
    • +
    • Lint +
        +
      • Updated Lint to check Android application code. Lint rules which previously +performed pattern based searches in the application code (such as the unused resource check) have +been rewritten to use the more accurate Java-style parse trees.
      • +
      • Added support for checking library projects. This change means that rules such as +the unused resource check properly handle resources declared in a library project and referenced in +a downstream project.
      • +
      • Added ability to suppress Lint warnings in Java code with the new +{@code @SuppressLint} annotation, and in XML files with the new tools: namespace and +ignore attribute. (more info)
      • +
      • New Lint checks: +
          +
        • Added check for Android API calls that require a version of Android higher than + the minimum supported version. You can use the new {@code @TargetApi} annotation + to suppress warnings when the code is wrapped in a system version condition. + (more info)
        • +
        • Added over 20 new Lint rules, including checks for + performance, + XML layouts, manifest and file handling.
        • +
        +
      • +
      +
    • +
    +
    +
    +
    +
    + +
    + + + SDK Tools, Revision 16 (December 2011) + +
    +

    Important: To download the new Android + 4.0 system components from the Android SDK Manager, you must first update the + SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, + the Android 4.0 system components will not be available for download.

    + +
    +
    Dependencies:
    +
    +
      +
    • Android SDK Platform-tools revision 9 or later.
    • +
    • If you are developing in Eclipse with ADT, note that the SDK Tools r16 is designed for use + with ADT 16.0.0 and later. If you haven't already, we highly recommend updating your + ADT Plugin to 16.0.0.
    • +
    • If you are developing outside Eclipse, you must have Apache + Ant 1.8 or later.
    • +
    +
    +
    General notes:
    +
    +
      +
    • Added Lint tools to detect common errors in Android projects. + (more info)
    • +
    • Added sensor emulation support, which allows the emulator to read sensor data from a + physical Android device. + (more info)
    • +
    • Added support for using a webcam to emulate a camera on Mac OS X.
    • +
    +
    +
    Bug fixes:
    +
    + +
    +
    +
    +
    + +
    + + + SDK Tools, Revision 15 (October 2011) + +
    +

    Important: To download the new Android + 4.0 system components from the Android SDK Manager, you must first update the + SDK tools to revision 14 or later and restart the Android SDK Manager. If you do not, + the Android 4.0 system components will not be available for download.

    +
    +
    Dependencies:
    +
    +
    • Android SDK Platform-tools revision 9 or later.
    • +
    • If you are developing in Eclipse with ADT, note that the SDK Tools r15 is designed for use + with ADT 15.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 15.0.0.
    • +
    • If you are developing outside Eclipse, you must have Apache + Ant 1.8 or later.
    • +
    + +
    Bug fixes:
    +
    +
      +
    • Fixed emulator crash on Linux due to improper webcam detection + (Issue 20952).
    • +
    • Fixed emulator issue when using the -wipe-data argument.
    • +
    • Fixed build issue when using Renderscript in projects that target API levels 11-13 + (Issue 21006).
    • +
    • Fixed issue when creating an AVD using the GoogleTV addon + (Issue 20963).
    • +
    • Fixed ant test + (Issue 20979).
    • +
    • Fixed android update project + (Issue 20535).
    • +
    • Fixed scrolling issue in the new Logcat panel of DDMS.
    • +
    • Fixed issue with MonkeyRunner + (Issue 20964).
    • +
    • Fixed issues in the SDK Manager + (Issue 20939, + Issue 20607).
    • +
    +
    +
    +
    +
    + +
    + + + SDK Tools, Revision 14 (October 2011) + +
    +

    Important: To download the new Android + 4.0 system components from the Android SDK Manager, you must first update the + SDK tools to revision 14 and restart the Android SDK Manager. If you do not, + the Android 4.0 system components will not be available for download.

    +
    +
    Dependencies:
    +
    +
    • Android SDK Platform-tools revision 8 or later.
    • +
    • If you are developing in Eclipse with ADT, note that the SDK Tools r14 is designed for use + with ADT 14.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 14.0.0.
    • +
    • If you are developing outside Eclipse, you must have Apache + Ant 1.8 or later.
    • +
    + +
    General notes:
    +
    +
      +
    • Added webcam support to Android 4.0 or later platforms to emulate rear-facing cameras when + one webcam is present, and to emulate both rear-facing and front-facing cameras when two + webcams are present. Webcam support is for Windows and Linux only. + Mac support will come in a later release.
    • +
    • Changed default.properties to project.properties and + build.properties to ant.properties. Any existing + projects that you build with Ant must be updated with the android update project + command.
    • +
    • Changed Ant build.xml file to support improvements to the + build system and added and modified Ant commands to support these changes. For a list of Ant +commands, see the +Ant Command +Reference.
    • +
    • Changed how library projects are built.
    • +
    • Improved incremental builds, so that resource compilation runs less frequently. Builds no + longer run when you edit strings or layouts (unless you add a new id) and no longer + run once for each library project.
    • +
    • Introduced a "PNG crunch cache" that only runs on modified PNG files, instead of + crunching all existing PNG files, all the time.
    • +
    • Revamped the SDK Manager UI (more +info).
    • +
    +

    For a complete overview of the build system changes and what you need to do to support them, +see the Android Tools Project +site.

    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 13 (September 2011) +
    +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that the SDK Tools r13 is designed for use with +ADT 12.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 12.0.0.

    + +

    If you are developing outside Eclipse, you must have Apache +Ant 1.8 or later.

    + +
    General notes:
    +
    +
      +
    • Fix compilation issue in Ant (dex step) when paths have spaces.
    • +
    • Fix issue in emulator installation when paths have spaces.
    • +
    • Fix issue when AVD paths have spaces.
    • +
    • Fix rendering issue when using emulator scaling (see more).
    • +
    +
    +
    +
    +
    + + +
    + + +SDK Tools, Revision 12 (July 2011) +
    +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that the SDK Tools r12 is designed for use with +ADT 12.0.0 and later. If you haven't already, we highly recommend updating your ADT Plugin to 12.0.0.

    + +

    If you are developing outside Eclipse, you must have Apache +Ant 1.8 or later.

    + +
    General notes:
    +
    +
      +
    • The AVD manager and emulator can now use system images + compiled for ARM v7 and x86 CPUs.
    • +
    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 11 (May 2011) +
    +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that the SDK Tools r11 is designed for use with +ADT 10.0.1 and later. If you haven't already, we highly recommend updating your ADT Plugin to 10.0.1.

    + +

    If you are developing outside Eclipse, you must have Apache +Ant 1.8 or later.

    + +
    General notes:
    +
    +
      +
    • Miscellaneous emulator changes to support Android 3.1.
    • +
    +
    +
    +
    +
    + + +
    + + +SDK Tools, Revision 10 (February 2011) +
    +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that the SDK Tools r10 is +designed for use with ADT 10.0.0 and later. After installing SDK Tools r10, we +highly recommend updating your ADT Plugin to 10.0.0.

    + +

    If you are developing outside Eclipse, you must have Apache +Ant 1.8 or later.

    + +
    General notes:
    +
    +
      +
    • The tools now automatically generate Java Programming Language source files (in the +gen directory) and + bytecode (in the res/raw directory) from your native .rs files
    • +
    +
    +
    +
    +
    + + + +
    + + +SDK Tools, Revision 9 (January 2011) +
    +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that the SDK Tools r9 is +designed for use with ADT 9.0.0 and later. After installing SDK Tools r9, we +highly recommend updating your ADT Plugin to 9.0.0.

    + +

    If you are developing outside Eclipse, you must have Apache +Ant 1.8 or later.

    + +
    Upgrading to SDK Tools r9:
    +
    +

    If you are upgrading to SDK Tools r9 from SDK Tools r7 or earlier, the default installed location +for the adb tool has changed from <SDK>/tools/adb to +<SDK>/platform-tools/adb. This means that you should +add the new location to your PATH and modify any custom build scripts to +reference the new location. Copying the adb executable from the new +location to the old is not recommended, since subsequent updates to the SDK +Tools will delete the file.

    +
    + +
    General notes:
    +
    +
      +
    • The default ProGuard configuration, proguard.cfg, now ignores the following classes: +
        +
      • classes that extend {@link android.preference.Preference}
      • +
      • classes that extend {@link android.app.backup.BackupAgentHelper}
      • +
      +
    • +
    • Ant lib rules now allow you to override java.encoding, java.source, + and java.target properties.
    • +
    • The default encoding for the javac Ant task is now UTF-8.
    • +
    • The LogCat view in DDMS now properly displays UTF-8 characters.
    • +
    • The SDK Manager is more reliable on Windows. For details on the improvements, see the + Android Tools Project Site.
    • +
    • Early look at the new snapshot feature: To improve startup time for the emulator, you can +enable snapshots for the system state. The emulator will then restore to the state when it last +closed almost instantly. Note: The snapshot feature is still under active +development and might not always perform as expected.
    • +
    • Fixed the missing JAR file error that prevented draw9patch from running.
    • +
    • Fixed the Windows launch scripts hierarchyviewer and ddms to support + the new location of adb.
    • +
    • Known issues with emulator performance: Because the Android emulator must simulate the ARM +instruction set architecture on your computer, emulator performance is slow. We're working hard to +resolve the performance issues and it will improve in future releases.
    • +
    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 8 (December 2010) +
    + +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that SDK Tools r8 is +designed for use with ADT 8.0.0 and later. After installing SDK Tools r8, we +highly recommend updating your ADT Plugin to 8.0.0.

    + +

    If you are developing outside Eclipse, you must have Apache +Ant 1.8 or later.

    + +

    Also note that SDK Tools r8 requires a new SDK component called +Platform-tools. The new Platform-tools component lets all SDK platforms +(Android 2.1, Android 2.2, and so on) use the same (latest) version of build +tools such as adb, aapt, aidl, and +dx. To download the Platform-tools component, use the Android SDK +Manager, as described in Exploring the +SDK

    + +
    Upgrading from SDK Tools r7:
    +
    +

    If you are upgrading to SDK Tools r8 from an earlier version, note that the +the default installed location for the adb tool has changed from +<SDK>/tools/adb to +<SDK>/platform-tools/adb. This means that you should +add the new location to your PATH and modify any custom build scripts to +reference the new location. Copying the adb executable from the new +location to the old is not recommended, since subsequent updates to the SDK +Tools will delete the file.

    +
    + +
    General notes:
    +
    +
      +
    • All SDK platforms now support Library Projects.
    • +
    • Support for a true debug build. Developers no longer need to add the +android:debuggable attribute to the +<application> tag in the manifest — the build tools add +the attribute automatically. In Eclipse/ADT, all incremental builds are assumed +to be debug builds, so the tools insert android:debuggable="true". +When exporting a signed release build, the tools do not add the attribute. In +Ant, a ant debug command automatically inserts the +android:debuggable="true" attribute, while ant release +does not. If android:debuggable="true" is manually set, then +ant release will actually do a debug build, rather than a release +build.
    • +
    • Automatic ProGuard support in release builds. Developers generate a ProGuard +configuration file using the android tool — the build tools +then automatically run ProGuard against the project sources during the build. +For more information, see the ProGuard +documentation.
    • +
    • New overridable Ant javac properties: java.encoding, +java.source, and java.target (default values are +"ascii", "1.5", and "1.5", respectively).
    • +
    • New UI for the HierarchyViewer tool.
    • +
    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 7 (September 2010) +
    + +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that SDK Tools r7 is +designed for use with ADT 0.9.8 and later. After installing SDK Tools r7, we +highly recommend updating your ADT Plugin to 0.9.8.

    +
    + +
    General notes:
    +
    +
      +
    • Added support for library projects that depend on other library projects.
    • +
    • Adds support for aidl files in library projects.
    • +
    • Adds support for extension targets in Ant build to perform tasks between the +normal tasks: -pre-build, -pre-compile, and +-post-compile.
    • +
    • Adds support for "headless" SDK update. See android -h update sdk +for more information.
    • +
    • Fixes location control in DDMS to work in any locale not using '.' as a +decimal point.
    • +
    + +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 6 (May 2010) +
    + +
    +
    Dependencies:
    +
    +

    If you are developing in Eclipse with ADT, note that SDK Tools r6 is +designed for use with ADT 0.9.7 and later. After installing SDK Tools r6, we +highly recommend updating your ADT Plugin to 0.9.7.

    +
    + +
    Library projects:
    +
    +

    The SDK Tools now support the use of library projects during +development, a capability that lets you store shared Android application +code and resources in a separate development project. You can then reference the +library project from other Android projects and, at build time, the tools +compile the shared code and resources as part of the dependent applications. +More information about this feature is available in the Creating and Managing Projects document.

    +

    If you are developing in Eclipse, ADT +provides the equivalent library project support.

    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 5 (March 2010) +
    + +
    +
    Dependencies:
    +
      +
    • If you are developing in Eclipse with ADT, note that SDK Tools r5 is +designed for use with ADT 0.9.6 and later. After installing SDK Tools r5, we +highly recommend updating your ADT Plugin to 0.9.6.
    • +
    • For Mac OS platforms, OS X 10.4.x (Tiger) is no longer +officially supported.
    • +
    +
    + +
    SDK and AVD Manager:
    +
    +
      +
    • Fixes SSL download for the standalone version of the SDK Updater.
    • +
    • Fixes issue with 64-bit JVM on Windows.
    • +
    • Adds support for platform samples components.
    • +
    • Improves support for dependency between components.
    • +
    • AVDs now sorted by API level.
    • +
    • The AVD creation dialog now enforces a minimum SD card size of 9MB.
    • +
    • Prevents deletion of running AVDs.
    • +
    • Settings are now automatically saved, no need to click "Apply".
    • +
    +
    + +
    Emulator:
    +
    +
      +
    • Emulator now requires SD card to be 9MB or more.
    • +
    +
    + +
    Layoutopt:
    +
    +
      +
    • Fixes layoutopt.bat to execute correctly on Windows.
    • +
    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 4 (December 2009) +
    + +
    +
    Dependencies:
    +

    SDK Tools r4 is compatible with ADT 0.9.5 and later, but not +compatible with earlier versions. If you are developing in Eclipse with ADT, you +must update your ADT plugin to version 0.9.5 or higher if you +install SDK Tools r4 in your SDK.

    + +
    General notes:
    +
    +
      +
    • Launcher script now forces GDK_NATIVE_WINDOW=true (linux only), to fix a +compatibility issue between GTK and SWT.
    • +
    +
    + +
    Android SDK and AVD Manager:
    +
    +
      +
    • AVD Launch dialog now shows scale value.
    • +
    • Fixes potential NPE in SDK Manager on AVD launch, for older AVD with no +skin name specified.
    • +
    • Fixes XML validation issue in on older Java versions.
    • +
    • No longer forces the use of Java 1.5 on Mac OS X.
    • +
    +
    + +
    Emulator:
    +
    +
      +
    • No longer limits the size of the system partition.
    • +
    +
    + +
    Ant build tools:
    +
    +
      +
    • .apk packaging now properly ignores vi swap files as well as hidden files.
    • +
    +
    +
    +
    +
    + +
    + + +SDK Tools, Revision 3 (October 2009) +
    + +
    +
    Dependencies:
    +

    SDK Tools r3 is compatible with ADT 0.9.4 and later, but not +compatible with earlier versions. If you are developing in Eclipse with ADT, you +must update your ADT plugin to version 0.9.4 or higher if you +install SDK Tools r3 in your SDK.

    +
    + +
    Android tool:
    +
    +
      +
    • Adds new android create test-project and android update +test-project commands to allow for greater flexibility in the location of the +main and test projects.
    • +
    +
    + +
    DDMS:
    +
    +
      +
    • Adds a button to dump HPROF file for running applications (app must be able +to write to the sdcard).
    • +
    • Button to start/stop profiling of a running application (app must be able to +write to the sdcard). Upon stop, Traceview will automatically be launched to +display the trace.
    • +
    • Fixed DDMS, Traceview, and the AVD Mananger/SDK Updater to run on Mac OS X +10.6.
    • +
    • Fixed screenshot support for devices running 32-bit framebuffer.
    • +
    +
    + +
    Android SDK and AVD Manager:
    +
    +
      +
    • Provides a new UI that lets you set options for controlling +the emulator skin, screen size/density, and scale factor used when launching +an AVD.
    • +
    • Provides improved AVD creation UI, which lets you customize the hardware +properties of your AVDs.
    • +
    • Now enforces dependencies between platforms and tools components, and +between SDK add-ons and platforms.
    • +
    +
    + +
    Layoutopt, a new tool for optimizing layouts:
    + +

    The SDK Tools r3 package includes layoutopt, a new command-line +tool that helps you optimize your layout hierarchies. When run against your +layout files, the tool analyzes their hierarchies and notifies you of +inefficiencies and other potential issues. The tool also provides simple +solutions for the issues it finds. For usage, see layoutopt.

    +
    +
    +
    +
    diff --git a/docs/html/tools/sdk/usb-drivers.jd b/docs/html/tools/sdk/usb-drivers.jd new file mode 100644 index 000000000000..27e89dea5b6c --- /dev/null +++ b/docs/html/tools/sdk/usb-drivers.jd @@ -0,0 +1,9 @@ +page.title=Android Development Platforms + +@jd:body + + + +

    A page that lists platforms and links to release notes. Links to dashboards etc.

    + + diff --git a/docs/html/tools/sdk/win-usb.jd b/docs/html/tools/sdk/win-usb.jd new file mode 100644 index 000000000000..d32234002843 --- /dev/null +++ b/docs/html/tools/sdk/win-usb.jd @@ -0,0 +1,172 @@ +page.title=Google USB Driver +@jd:body + + + +

    The Google USB driver is a downloadable component for the Android SDK, available +from the SDK Manager. The driver is for Windows only and provides the necessary drivers for the +following devices:

    +
      +
    • ADP1 / T-Mobile G1*
    • +
    • ADP2 / Google Ion / T-Mobile myTouch 3G*
    • +
    • Verizon Droid*
    • +
    • Nexus One
    • +
    • Nexus S
    • +
    +

    * Or similar hardware on other carriers

    + +

    All other devices require Windows drivers provided by the hardware manufacturer, as listed in +the OEM USB Drivers document. The Galaxy Nexus +driver is also distributed by Samsung +(listed as model SCH-I515).

    + +

    Note: +If you're developing on Mac OS X or Linux, then you do not need to install a USB driver. To start +developing with your device, also read Using +Hardware Devices.

    + +

    The sections below provide instructions on how to download and install the Google USB Driver +for Windows.

    + + + + +

    Revisions

    + +

    The sections below provide notes about successive revisions of the USB Driver +for Windows, as denoted by revision number. To determine what revision of the +USB Driver for Windows you are using, refer to the "Installed Packages" listing +in the Android SDK Manager.

    + + + + +
    + + +USB Driver for Windows, Revision 4 (December 2010) +
    + +
    +

    Adds support for the Nexus S.

    +
    +
    +
    + +
    + + +USB Driver for Windows, Revision 3 (January 2010) +
    + +
    +

    Adds support for the Nexus One.

    +
    +
    +
    + +
    + + +USB Driver for Windows, Revision 2 (November 2009) +
    + +
    +

    Adds support for the Verizon Droid (or similar hardware on +other carriers).

    +
    +
    +
    + +
    + + +USB Driver for Windows, Revision 1 (October 2009) +
    + +
    +

    Initial release of the WinUsb-based driver, with support +for the T-Mobile G1 and myTouch 3G (and similar devices).

    +
    +
    +
    + + +

    Downloading the Google USB Driver

    + +
    + +

    Figure 1. The SDK Manager + with the Google USB Driver selected.

    +
    + +

    The USB Driver for Windows is available for download as an optional SDK +component. You need the driver only if you are developing on Windows and +want to connect an Android-powered device (ADP, Nexus One, or Nexus S) to your +development environment over USB.

    + +

    To download the driver, use the Android SDK Manager tool that is +included with the Android SDK:

    +
      +
    1. Launch the Android SDK Manager by double-clicking SDK Manager.exe, + at the root of your SDK directory.
    2. +
    3. Expand Extras.
    4. +
    5. Check Google USB Driver package and click Install.
    6. +
    7. Proceed to install the package. When done, the driver files are +downloaded into the <sdk>\extras\google\usb_driver\ directory.
    8. +
    + +

    For installation information, read Installing a USB Driver.

    diff --git a/docs/html/tools/testing/activity_test.jd b/docs/html/tools/testing/activity_test.jd new file mode 100644 index 000000000000..8288249ea820 --- /dev/null +++ b/docs/html/tools/testing/activity_test.jd @@ -0,0 +1,1334 @@ +page.title=Activity Testing Tutorial +parent.title=Testing +parent.link=index.html +@jd:body +
    +
    +

    In this document

    +
      +
    1. + Prerequisites +
    2. +
    3. + Installing the Tutorial Sample Code +
    4. +
    5. + Setting Up the Emulator +
    6. +
    7. + Setting Up the Projects +
    8. +
    9. + Creating the Test Case Class +
        +
      1. + Adding the test case class file +
      2. +
      3. + Adding the test case constructor +
      4. +
      5. + Adding the setup method +
      6. +
      7. + Adding an initial conditions test +
      8. +
      9. + Adding a UI test +
      10. +
      11. + Adding state management tests +
      12. +
      +
    10. +
    11. + Running the Tests and Seeing the Results +
    12. +
    13. + Forcing Some Tests to Fail +
    14. +
    15. + Next Steps +
    16. +
    +

    Appendix

    +
      +
    1. + Installing the Completed Test Application File +
    2. +
    3. + For Users Not Developing In Eclipse +
    4. +
    +

    See Also

    +
      +
    1. + Testing Fundamentals +
    2. +
    3. + {@link android.test.ActivityInstrumentationTestCase2} +
    4. +
    5. + {@link junit.framework.Assert} +
    6. +
    7. + {@link android.test.InstrumentationTestRunner} +
    8. +
    +
    +
    +

    + Android includes powerful tools for testing applications. The tools extend JUnit with additional features, provide convenience classes for mock Android system objects, and use + instrumentation to give you control over your main application while you are testing it. The entire Android testing environment is discussed in the document + Testing Fundamentals. +

    +

    + This tutorial demonstrates the Android testing tools by presenting a simple Android application and then leading you step-by-step through the creation of a test application for it. + The test application demonstrates these key points: +

    +
      +
    • + An Android test is itself an Android application that is linked to the application under test by entries in its AndroidManifest.xml file. +
    • +
    • + Instead of Android components, an Android test application contains one or more test cases. Each of these is a separate class definition. +
    • +
    • + Android test case classes extend the JUnit {@link junit.framework.TestCase} class. +
    • +
    • + Android test case classes for activities extend JUnit and also connect you to the application under test with instrumentation. You can send keystroke or touch events directly to the UI. +
    • +
    • + You choose an Android test case class based on the type of component (application, activity, content provider, or service) you are testing. +
    • +
    • + Additional test tools in Eclipse/ADT provide integrated support for creating test applications, running them, and viewing the results. +
    • +
    +

    + The test application contains methods that perform the following tests: +

    +
      +
    • + Initial conditions test. Tests that the application under test initializes correctly. This is also a unit test of the application's + {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method. Testing initial conditions also provides a confidence measure for subsequent tests. +
    • +
    • + UI test. Tests that the main UI operation works correctly. This test demonstrates the instrumentation features available in activity testing. + It shows that you can automate UI tests by sending key events from the test application to the main application. +
    • +
    • + State management tests. Test the application's code for saving state. This test demonstrates the instrumentation features of the test runner, which + are available for testing any component. +
    • +
    +

    Prerequisites

    +

    + The instructions and code in this tutorial depend on the following: +

    +
      +
    • + Basic knowledge of Android programming. If you haven't yet written an Android application, + do the class + Building Your First App. + If you want to learn more about Spinner, the application under test, then you + might want to review the "Spinner" sample app. +
    • +
    • + Some familiarity with the Android testing framework and concepts. If you haven't explored + Android testing yet, start by reading the + Testing Fundamentals + guide. +
    • +
    • + Eclipse with ADT. This tutorial describes how to set up and run a test application using + Eclipse with ADT. If you haven't yet installed Eclipse and the ADT plugin, + follow the steps in Installing the SDK + to install them before continuing. If you are not developing in Eclipse, you will + find instructions for setting up and running the test application in the + appendix of this document. +
    • +
    • + Android 1.5 platform (API Level 3) or higher. You must have the Android 1.5 platform + (API Level 3) or higher installed in your SDK, because this tutorial uses APIs that + were introduced in that version. +

      + If you are not sure which platforms are installed in your SDK, + open the Android SDK and AVD Manager and check in the + Installed Packages panel. + If aren't sure how to download a platform into your SDK, + read Exploring the SDK. +

      +
    • +
    +

    Installing the Tutorial Sample Code

    +

    + During this tutorial, you will be working with sample code that is provided as part + of the downloadable Samples component of the SDK. Specifically, you will be working + with a pair of related sample applications — an application under test and a test + application: +

    +
      +
    • + Spinner is the application under test. This tutorial focuses on the + common situation of writing tests for an application that already exists, so the main + application is provided to you. +
    • +
    • + SpinnerTest is the test application. In the tutorial, you create this application + step-by-step. If you want to run quickly through the tutorial, + you can install the completed SpinnerTest application first, and then follow the + text. You may get more from the tutorial, however, if you create the test application + as you go. The instructions for installing the completed test application are in the + section + Installing the Completed Test Application File. +
    • +
    +

    + The sample applications are described in more detail in the + Samples topic. Follow the instructions to + download the version of the samples that's appropriate for the platform you're working with. +

    +

    Setting Up the Emulator

    +

    + In this tutorial, you will use the Android emulator to run applications. The emulator needs + an Android Virtual Device (AVD) with an API level equal to or higher than the one you set for the projects in the previous step. + To find out how to check this and create the right AVD if necessary, + see Creating an AVD. +

    +

    + As a test of the AVD and emulator, run the SpinnerActivity application in Eclipse with ADT. When it starts, + click the large downward-pointing arrow to the right of the spinner text. You see the spinner expand and display the title "Select a planet" at the top. + Click one of the other planets. The spinner closes, and your selection appears below it on the screen. +

    +

    Setting Up the Projects

    +

    + When you are ready to get started with the tutorial, begin by setting up Eclipse projects for + both Spinner (the application under test) and SpinnerTest (the test application). +

    +

    + You'll be using the Spinner application as-is, without modification, so you'll be loading it + into Eclipse as a new Android project from existing source. In the process, you'll be + creating a new test project associated with Spinner that will contain the SpinnerTest + application. The SpinnerTest application will be completely new and you'll be + using the code examples in this tutorial to add test classes and tests to it. +

    +

    + To install the Spinner app in a new Android project from existing source, following these steps: +

    +
      +
    1. + In Eclipse, select File > New > Project > Android > Android Project, + then click Next. The New Android Project dialog appears. +
    2. +
    3. + In the Project name text box, enter "SpinnerActivity". The Properties area is filled in automatically. +
    4. +
    5. + In the Contents area, set "Create project from existing source". +
    6. +
    7. + For Location, click Browse, navigate to the directory <SDK_path>/samples/android-8/Spinner, + then click Open. The directory name <SDK_path>/samples/android-8/Spinner now appears in the Location text box. +
    8. +
    9. + In the Build Target area, set a API level of 3 or higher. If you are already developing with a particular target, and it is API level 3 or higher, then use that target. +
    10. +
    11. + In the Properties area, in the Min SDK Version:, enter "3". +
    12. +
    13. + You should now see these values: +
        +
      • Project Name: "SpinnerActivity"
      • +
      • Create project from existing source: set
      • +
      • Location: "<SDK_path>/samples/android-8/Spinner"
      • +
      • Build Target: "API level of 3 or higher" (Target Name "Android 1.5 or higher")
      • +
      • Package name: (disabled, set to "com.android.example.spinner")
      • +
      • Create Activity: (disabled, set to ".SpinnerActivity")
      • +
      • Min SDK Version: "3"
      • +
      +

      + The following screenshot summarizes these values: +

      + + New Android Project dialog with filled-in values + + +
    14. +
    +

    + To create a new test project for the SpinnerTest application, follow these steps: +

    +
      +
    1. + Click Next. The New Android Test Project dialog appears. +
    2. +
    3. + Set "Create a Test Project". +
    4. +
    5. + Leave the other values unchanged. The result should be: +
        +
      • Create a Test Project: checked
      • +
      • Test Project Name: "SpinnerActivityTest"
      • +
      • Use default location: checked (this should contain the directory name "workspace/SpinnerActivityTest").
      • +
      • Build Target: Use the same API level you used in the previous step.
      • +
      • Application name: "SpinnerActivityTest"
      • +
      • Package name: "com.android.example.spinner.test"
      • +
      • Min SDK Version: "3"
      • +
      +

      + The following screenshot summarizes these values: +

      + + New Android Test Project dialog with filled-in values + +
    6. +
    7. + Click Finish. Entries for SpinnerActivity and SpinnerActivityTest should appear in the + Package Explorer. +

      + Note: If you set Build Target to an API level higher than "3", you will see the warning + "The API level for the selected SDK target does not match the Min SDK version". You do not need to change the API level or the Min SDK version. + The message tells you that you are building the projects with one particular API level, but specifying that a lower API level is required. This may + occur if you have chosen not to install the optional earlier API levels. +

      +

      + If you see errors listed in the Problems pane at the bottom of the Eclipse window, or if a red error marker appears next to + the entry for SpinnerActivity in the Package Explorer, highlight the SpinnerActivity entry and then select + Project > Clean. This should fix any errors. +

      +
    8. +
    +

    + You now have the application under test in the SpinnerActivity project, + and an empty test project in SpinnerActivityTest. You may + notice that the two projects are in different directories, but Eclipse with + ADT handles this automatically. You should have no problem in either building or running them. +

    +

    + Notice that Eclipse and ADT have already done some initial setup for your test application. + Expand the SpinnerActivityTest project, and notice that it already has an + Android manifest file AndroidManifest.xml. + Eclipse with ADT created this when you added the test project. + Also, the test application is already set up to use instrumentation. You can see this + by examining AndroidManifest.xml. + Open it, then at the bottom of the center pane click AndroidManifest.xml + to display the XML contents: +

    +
    +<?xml version="1.0" encoding="utf-8"?>
    +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +      package="com.android.example.spinner.test"
    +      android:versionCode="1"
    +      android:versionName="1.0">
    +    <uses-sdk android:minSdkVersion="3" />
    +    <instrumentation
    +        android:targetPackage="com.android.example.spinner"
    +        android:name="android.test.InstrumentationTestRunner" />
    +    <application android:icon="@drawable/icon" android:label="@string/app_name">
    +        <uses-library android:name="android.test.runner" />
    +        ...
    +    </application>
    +</manifest>
    +
    +

    + Notice the <instrumentation> element. The attribute + android:targetPackage="com.android.example.spinner" tells Android that the + application under test is defined in the Android package + com.android.example.spinner. Android now knows to use that + package's AndroidManifest.xml file to launch the application under test. + The <instrumentation> element also contains the attribute + android:name="android.test.InstrumentationTestRunner", which tells Android + instrumentation to run the test application with Android's instrumentation-enabled test runner. +

    +

    Creating the Test Case Class

    + +

    + You now have a test project SpinnerActivityTest, and the basic structure of a test + application also called SpinnerActivityTest. The basic structure includes all the files and + directories you need to build and run a test application, except for the class that + contains your tests (the test case class). +

    +

    + The next step is to define the test case class. In this tutorial, you'll be creating a + test case class that includes: +

    +
      +
    • + Test setup. This use of the JUnit {@link junit.framework.TestCase#setUp() setUp()} + method demonstrates some of the tasks you might perform before running an Android test. +
    • +
    • + Testing initial conditions. This test demonstrates a good testing technique. + It also demonstrates that with Android instrumentation you can look at the application + under test before the main activity starts. The test checks that the application's + important objects have been initialized. + If the test fails, you then know that any other tests against the application are + unreliable, since the application was running in an incorrect state. +

      + Note: The purpose of testing initial conditions is not the same as + using setUp(). The JUnit {@link junit.framework.TestCase#setUp()} runs once + before each test method, and its purpose is to create a clean test + environment. The initial conditions test runs once, and its purpose is to verify that the + application under test is ready to be tested. +

      +
    • +
    • + Testing the UI. This test shows how to control the main application's UI + with instrumentation, a powerful automation feature of Android testing. +
    • +
    • + Testing state management. This test shows some techniques for testing how + well the application maintains state in the Android environment. Remember that to + provide a satisfactory user experience, your application must never lose its current state, + even if it's interrupted by a phone call or destroyed because of memory constraints. + The Android activity lifecycle provides ways to maintain state, and the + SpinnerActivity application uses them. The test shows the techniques for + verifying that they work. +
    • +
    +

    + Android tests are contained in a special type of Android application that contains one or more test class definitions. Each of these contains + one or more test methods that do the actual tests. In this tutorial, you will first add a test case class, and then add tests to it. +

    +

    + You first choose an Android test case class to extend. You choose from the base test case classes according to the Android component you are testing and the types of tests you are doing. + In this tutorial, the application under test has a single simple activity, so the test case class will be for an Activity component. Android offers several, but the one that tests in + the most realistic environment is {@link android.test.ActivityInstrumentationTestCase2}, so you will use it as the base class. Like all activity test case classes, + ActivityInstrumentationTestCase2 offers convenience methods for interacting directly with the UI of the application under test. +

    +

    Adding the test case class file

    +

    + To add ActivityInstrumentationTestCase2 as the base test case class, follow these steps: +

    +
      +
    1. + In the Package Explorer, expand the test project SpinnerActivityTest if it is not open already. +
    2. +
    3. + Within SpinnerActivityTest, expand the src/ folder and then the package marker for + com.android.example.spinner.test. Right-click on the package name and select New > Class:
      + + Menu for creating a new class in the test application + +

      + The New Java Class wizard appears: +

      + + New Java Class wizard dialog + +
    4. +
    5. + In the wizard, enter the following: +
        +
      • + Name: "SpinnerActivityTest". This becomes the name of your test class. +
      • +
      • + Superclass: "android.test.ActivityInstrumentationTestCase2<SpinnerActivity>". The superclass is parameterized, so + you have to provide it your main application's class name. +
      • +
      +

      + Do not change any of the other settings. Click Finish. +

      +
    6. +
    7. + You now have a new file SpinnerActivityTest.java in the project. +
    8. +
    9. + To resolve the reference to SpinnerActivity, add the following import: +
      +import com.android.example.spinner.SpinnerActivity;
      +
      +
    10. +
    +

    Adding the test case constructor

    +

    + To ensure that the test application is instantiated correctly, you must set up a constructor that the test + runner will call when it instantiates your test class. This constructor has no parameters, and its sole + purpose is to pass information to the superclass's default constructor. To set up this constructor, enter the + following code in the class: +

    +
    +  public SpinnerActivityTest() {
    +    super("com.android.example.spinner", SpinnerActivity.class);
    +  } // end of SpinnerActivityTest constructor definition
    +
    +

    + This calls the superclass constructor with the Android package name (com.android.example.spinner)and main activity's class + (SpinnerActivity.class) for the application under test. Android uses this information to find the application and activity to test. +

    +

    + You are now ready to add tests, by adding test methods to the class. +

    +

    Adding the setup method

    +

    + The setUp() method is invoked before every test. You use it to initialize variables and clean up from previous tests. You can also use + the JUnit {@link junit.framework.TestCase#tearDown() tearDown()} method, which runs after every test method. The tutorial does not use it. +

    +

    + The method you are going to add does the following: +

    +
      +
    • + super.setUp(). Invokes the superclass constructor for setUp(), which is required by JUnit. +
    • +
    • + Calls {@link android.test.ActivityInstrumentationTestCase2#setActivityInitialTouchMode(boolean) setActivityInitialTouchMode(false)}. + This turns off touch mode in the device or emulator. If any of your test methods send key events to the application, + you must turn off touch mode before you start any activities; otherwise, the call is ignored. +
    • +
    • + Stores references to system objects. Retrieves and stores a reference to the activity under test, the Spinner + widget used by the activity, the SpinnerAdapter that backs the widget, and the string value of the selection that is + set when the application is first installed. These objects are used in the state management test. The methods invoked are: +
        +
      • + {@link android.test.ActivityInstrumentationTestCase2#getActivity()}. Gets a reference to the activity under test (SpinnerActivity). + This call also starts the activity if it is not already running. +
      • +
      • + {@link android.app.Activity#findViewById(int)}. Gets a reference to the Spinner widget of the application under test. +
      • +
      • + {@link android.widget.AbsSpinner#getAdapter()}. Gets a reference to the adapter (an array of strings) backing the spinner. +
      • +
      +
    • +
    +

    + Add this code to the definition of SpinnerActivityTest, after the constructor definition: +

    +
    +  @Override
    +  protected void setUp() throws Exception {
    +    super.setUp();
    +
    +    setActivityInitialTouchMode(false);
    +
    +    mActivity = getActivity();
    +
    +    mSpinner =
    +      (Spinner) mActivity.findViewById(
    +        com.android.example.spinner.R.id.Spinner01
    +      );
    +
    +      mPlanetData = mSpinner.getAdapter();
    +
    +  } // end of setUp() method definition
    +
    +

    + Add these members to the test case class: +

    +
    +  private SpinnerActivity mActivity;
    +  private Spinner mSpinner;
    +  private SpinnerAdapter mPlanetData;
    +
    +

    + Add these imports: +

    +
    +import android.widget.Spinner;
    +import android.widget.SpinnerAdapter;
    +
    +

    + You now have the the complete setUp() method. +

    +

    Adding an initial conditions test

    +

    + The initial conditions test verifies that the application under test is initialized correctly. It is an illustration of the types of tests you can run, so it is not comprehensive. + It verifies the following: +

    +
      +
    • + The item select listener is initialized. This listener is called when a selection is made from the spinner. +
    • +
    • + The adapter that provides values to the spinner is initialized. +
    • +
    • + The adapter contains the right number of entries. +
    • +
    +

    + The actual initialization of the application under test is done in setUp(), which the test runner calls automatically before every test. The verifications are + done with JUnit {@link junit.framework.Assert} calls. As a useful convention, the method name is testPreConditions(): +

    +
    +  public void testPreConditions() {
    +    assertTrue(mSpinner.getOnItemSelectedListener() != null);
    +    assertTrue(mPlanetData != null);
    +    assertEquals(mPlanetData.getCount(),ADAPTER_COUNT);
    +  } // end of testPreConditions() method definition
    +
    +

    + Add this member: +

    +
    +  public static final int ADAPTER_COUNT = 9;
    +
    +

    Adding a UI test

    +

    + Now create a UI test that selects an item from the Spinner widget. The test sends key events to the UI with key events. + The test confirms that the selection matches the result you expect. +

    +

    + This test demonstrates the power of using instrumentation in Android testing. Only an instrumentation-based test class allows you to send key events (or touch events) + to the application under test. With instrumentation, you can test your UI without having to take screenshots, record the screen, or do human-controlled testing. +

    +

    + To work with the spinner, the test has to request focus for it and then set it to a known position. The test uses {@link android.view.View#requestFocus() requestFocus()} and + {@link android.widget.AbsSpinner#setSelection(int) setSelection()} to do this. Both of these methods interact with a View in the application under test, so you have to call them + in a special way. +

    +

    + Code in a test application that interacts with a View of the application under test must run in the main application's thread, also + known as the UI thread. To do this, you use the {@link android.app.Activity#runOnUiThread(java.lang.Runnable) Activity.runOnUiThread()} + method. You pass the code to runOnUiThread()in an anonymous {@link java.lang.Runnable Runnable} object. To set + the statements in the Runnable object, you override the object's {@link java.lang.Runnable#run()} method. +

    +

    + To send key events to the UI of the application under test, you use the sendKeys() method. + This method does not have to run on the UI thread, since Android uses instrumentation to pass the key events to the application under test. +

    +

    + The last part of the test compares the selection made by sending the key events to a pre-determined value. This tests that the spinner is working as intended. +

    +

    + The following sections show you how to add the code for this test. +

    +
      +
    1. + Get focus and set selection. Create a new method public void testSpinnerUI(). Add + code to to request focus for the spinner and set its position to default or initial position, "Earth". This code is run on the UI thread of + the application under test: +
      +  public void testSpinnerUI() {
      +
      +    mActivity.runOnUiThread(
      +      new Runnable() {
      +        public void run() {
      +          mSpinner.requestFocus();
      +          mSpinner.setSelection(INITIAL_POSITION);
      +        } // end of run() method definition
      +      } // end of anonymous Runnable object instantiation
      +    ); // end of invocation of runOnUiThread
      +
      +

      + Add the following member to the test case class. +

      +
      +  public static final int INITIAL_POSITION = 0;
      +
      +
    2. +
    3. + Make a selection. Send key events to the spinner to select one of the items. To do this, open the spinner by + "clicking" the center keypad button (sending a DPAD_CENTER key event) and then clicking (sending) the down arrow keypad button five times. Finally, + click the center keypad button again to highlight the desired item. Add the following code: +
      +    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
      +    for (int i = 1; i <= TEST_POSITION; i++) {
      +      this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
      +    } // end of for loop
      +
      +    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
      +
      +

      + Add the following member to the test case class: +

      +
      +  public static final int TEST_POSITION = 5;
      +
      +

      + This sets the final position of the spinner to "Saturn" (the spinner's backing adapter is 0-based). +

      +
    4. +
    5. + Check the result. Query the current state of the spinner, and compare its current selection to the expected value. + Call the method {@link android.widget.AdapterView#getSelectedItemPosition() getSelectedItemPosition()} to find out the current selection position, and then + {@link android.widget.AdapterView#getItemAtPosition(int) getItemAtPosition()} to get the object corresponding to that position (casting it to a String). Assert that + this string value matches the expected value of "Saturn": +
      +    mPos = mSpinner.getSelectedItemPosition();
      +    mSelection = (String)mSpinner.getItemAtPosition(mPos);
      +    TextView resultView =
      +      (TextView) mActivity.findViewById(
      +        com.android.example.spinner.R.id.SpinnerResult
      +      );
      +
      +    String resultText = (String) resultView.getText();
      +
      +    assertEquals(resultText,mSelection);
      +
      +  } // end of testSpinnerUI() method definition
      +
      +

      + Add the following members to the test case class: +

      +
      +  private String mSelection;
      +  private int mPos;
      +
      +

      + Add the following imports to the test case class: +

      +
      +  import android.view.KeyEvent;
      +  import android.widget.TextView;
      +
      +
    6. +
    +

    + Pause here to run the tests you have. The procedure for running a test application is different + from running a regular Android application. You run a test application as an Android JUnit + application. To see how to do this, see Running the Tests and Seeing the Results. +

    +

    + Eventually, you will see the SpinnerActivity application start, and the test + application controlling it by sending it key events. You will also see a new + JUnit view in the Explorer pane, showing the results of the + test. The JUnit view is documented in a following section, + Running the Test and Seeing the Results. +

    +

    Adding state management tests

    +

    + You now write two tests that verify that SpinnerActivity maintains its state when it is paused or terminated. + The state, in this case, is the current selection in the spinner. When users make a selection, + pause or terminate the application, and then resume or restart it, they should see + the same selection. +

    +

    + Maintaining state is an important feature of an application. Users may switch from the current + application temporarily to answer the phone, and then switch back. Android may decide to + terminate and restart an activity to change the screen orientation, or terminate an unused + activity to regain storage. In each case, users are best served by having the UI return to its + previous state (except where the logic of the application dictates otherwise). +

    +

    + SpinnerActivity manages its state in these ways: +

    +
      +
    • + Activity is hidden. When the spinner screen (the activity) is running but hidden by some other screen, it + stores the spinner's position and value in a form that persists while the application is running. +
    • +
    • + Application is terminated. When the activity is terminated, it stores the spinner's position and value in + a permanent form. The activity can read the position and value when it restarts, and restore the spinner to its previous state. +
    • +
    • + Activity re-appears. When the user returns to the spinner screen, the previous selection is restored. +
    • +
    • + Application is restarted. When the user starts the application again, the previous selection is restored. +
    • +
    +

    + Note: An application can manage its state in other ways as well, but these are + not covered in this tutorial. +

    +

    + When an activity is hidden, it is paused. When it re-appears, it + resumes. Recognizing that these are key points in an activity's life cycle, + the Activity class provides two callback methods {@link android.app.Activity#onPause()} and + {@link android.app.Activity#onResume()} for handling pauses and resumes. + SpinnerActivity uses them for code that saves and restores state. +

    +

    + Note: If you would like to learn more about the difference between losing + focus/pausing and killing an application, + read about the activity +lifecycle. +

    +

    + The first test verifies that the spinner selection is maintained after the entire application is shut down and then restarted. The test uses instrumentation to + set the spinner's variables outside of the UI. It then terminates the activity by calling {@link android.app.Activity#finish() Activity.finish()}, and restarts it + using the instrumentation method {@link android.test.ActivityInstrumentationTestCase2#getActivity()}. The test then asserts that the current spinner state matches + the test values. +

    +

    + The second test verifies that the spinner selection is maintained after the activity is paused and then resumed. The test uses instrumentation to + set the spinner's variables outside of the UI and then force calls to the onPause() and onResume() methods. The test then + asserts that the current spinner state matches the test values. +

    +

    + Notice that these tests make limited assumptions about the mechanism by which the activity manages state. The tests use the activity's getters and + setters to control the spinner. The first test also knows that hiding an activity calls onPause(), and bringing it back to the foreground + calls onResume(). Other than this, the tests treat the activity as a "black box". +

    +

    + To add the code for testing state management across shutdown and restart, follow these steps: +

    +
      +
    1. + Add the test method testStateDestroy(), then + set the spinner selection to a test value: +
      +  public void testStateDestroy() {
      +    mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
      +    mActivity.setSpinnerSelection(TEST_STATE_DESTROY_SELECTION);
      +
      +
    2. +
    3. + Terminate the activity and restart it: +
      +    mActivity.finish();
      +    mActivity = this.getActivity();
      +
      +
    4. +
    5. + Get the current spinner settings from the activity: +
      +    int currentPosition = mActivity.getSpinnerPosition();
      +    String currentSelection = mActivity.getSpinnerSelection();
      +
      +
    6. +
    7. + Test the current settings against the test values: +
      +    assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
      +    assertEquals(TEST_STATE_DESTROY_SELECTION, currentSelection);
      +  } // end of testStateDestroy() method definition
      +
      +

      + Add the following members to the test case class: +

      +  public static final int TEST_STATE_DESTROY_POSITION = 2;
      +  public static final String TEST_STATE_DESTROY_SELECTION = "Earth";
      +
      +
    8. +
    +

    + To add the code for testing state management across a pause and resume, follow these steps: +

    +
      +
    1. + Add the test method testStatePause(): +
      +    @UiThreadTest
      +    public void testStatePause() {
      +
      +

      + The @UiThreadTest annotation tells Android to build this method so that it runs + on the UI thread. This allows the method to change the state of the spinner widget in the + application under test. This use of @UiThreadTest shows that, if necessary, you + can run an entire method on the UI thread. +

      +
    2. +
    3. + Set up instrumentation. Get the instrumentation object + that is controlling the application under test. This is used later to + invoke the onPause() and onResume() methods: +
      +    Instrumentation mInstr = this.getInstrumentation();
      +
      +
    4. +
    5. + Set the spinner selection to a test value: +
      +    mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION);
      +    mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION);
      +
      +
    6. +
    7. + Use instrumentation to call the Activity's onPause(): +
      +    mInstr.callActivityOnPause(mActivity);
      +
      +

      + Under test, the activity is waiting for input. The invocation of + {@link android.app.Instrumentation#callActivityOnPause(android.app.Activity)} + performs a call directly to the activity's onPause() instead + of manipulating the activity's UI to force it into a paused state. +

      +
    8. +
    9. + Force the spinner to a different selection: +
      +    mActivity.setSpinnerPosition(0);
      +    mActivity.setSpinnerSelection("");
      +
      +

      + This ensures that resuming the activity actually restores the + spinner's state rather than simply leaving it as it was. +

      +
    10. +
    11. + Use instrumentation to call the Activity's onResume(): +
      +    mInstr.callActivityOnResume(mActivity);
      +
      +

      + Invoking {@link android.app.Instrumentation#callActivityOnResume(android.app.Activity)} + affects the activity in a way similar to callActivityOnPause. The + activity's onResume() method is invoked instead of manipulating the + activity's UI to force it to resume. +

      +
    12. +
    13. + Get the current state of the spinner: +
      +    int currentPosition = mActivity.getSpinnerPosition();
      +    String currentSelection = mActivity.getSpinnerSelection();
      +
      +
    14. +
    15. + Test the current spinner state against the test values: +
      +    assertEquals(TEST_STATE_PAUSE_POSITION,currentPosition);
      +    assertEquals(TEST_STATE_PAUSE_SELECTION,currentSelection);
      +  } // end of testStatePause() method definition
      +
      +

      + Add the following members to the test case class: +

      +
      +  public static final int TEST_STATE_PAUSE_POSITION = 4;
      +  public static final String TEST_STATE_PAUSE_SELECTION = "Jupiter";
      +
      +
    16. +
    17. + Add the following imports: +
      +  import android.app.Instrumentation;
      +  import android.test.UiThreadTest;
      +
      +
    18. +
    +

    Running the Tests and Seeing the Results

    +

    + The most simple way to run the SpinnerActivityTest test case is to run it directly from the Package Explorer. +

    +

    + To run the SpinnerActivityTest test, follow these steps: +

    +
      +
    1. + In the Package Explorer, right-click the project SpinnerActivityTest at the top level, and then + select Run As > Android JUnit Test:
      + + Menu to run a test as an Android JUnit test + +
    2. +
    3. + You will see the emulator start. When the unlock option is displayed (its appearance depends on the API level you specified for the AVD), + unlock the home screen. +
    4. +
    5. + The test application starts. You see a new tab for the JUnit view, next to the Package Explorer tab:
      + + The JUnit window + +
    6. +
    +

    + This view contains two sub-panes. The top pane summarizes the tests that were run, and the bottom pane shows failure traces for + highlighted tests. +

    +

    + At the conclusion of a successful test run, this is the view's appearance:
    + + JUnit test run success + +

    +

    + The upper pane summarizes the test: +

    +
      +
    • + Total time elapsed for the test application(labeled Finished after <x> seconds). +
    • +
    • + Number of runs (Runs:) - the number of tests in the entire test class. +
    • +
    • + Number of errors (Errors:) - the number of program errors and exceptions encountered during + the test run. +
    • +
    • + Number of failures (Failures:) - the number of test failures encountered during the test + run. This is the number of assertion failures. A test can fail even if the program does not encounter an error. +
    • +
    • + A progress bar. The progress bar extends from left to right as the tests run. +

      + If all the tests succeed, the bar remains green. If a test fails, the bar turns from green to red. +

      +
    • +
    • + A test method summary. Below the bar, you see a line for each class in the test application. To look at the results for the individual + methods in a test, click the arrow at the left to expand the line. You see the name of each test method. To the + right of the name, you see the time taken by the test. You can look at the test's code + by double-clicking its name. +
    • +
    +

    + The lower pane contains the failure trace. If all the tests are successful, this pane is empty. If some tests fail, + then if you highlight a failed test in the upper pane, the lower view contains a stack trace for the test. This is + demonstrated in the next section. +

    +

    + Note: If you run the test application and nothing seems to happen, look for + the JUnit view. If you do not see it, you may have run the test application + as a regular Android application. + Remember that you need to run it as an Android JUnit + application. +

    +

    Forcing Some Tests to Fail

    +

    + A test is as useful when it fails as when it succeeds. This section shows what happens in Eclipse with ADT when a test fails. You + can quickly see that a test class has failed, find the method or methods that failed, and then use a failure trace to find + the exact problem. +

    +

    + The example application SpinnerActivity that you downloaded passes all the tests in the test application SpinnerActivityTest. + To force the test to fail, you must modify the example application. You change a line of setup code in the application under test. This + causes the testPreConditions() and testTextView() test methods to fail. +

    +

    + To force the tests to fail, follow these steps: +

    +
      +
    1. + In Eclipse with ADT, go to the SpinnerActivity project and open the file SpinnerActivity.java. +
    2. +
    3. + At the top of SpinnerActivity.java, at the end of the onCreate() method, find the following line: +
      +    // mySpinner.setOnItemSelectedListener(null);
      +
      +

      Remove the forward slash characters at the beginning of the line to + uncomment the line. This sets the listener callback to null: +

      +
      +    mySpinner.setOnItemSelectedListener(null);
      +
      +
    4. +
    5. + The testPreConditions() method in SpinnerActivityTest contains the following test: + assertTrue(mSpinner.getOnItemSelectedListener() != null);. This test asserts that the listener callback is not null. + Since you have modified the application under test, this assertion now fails. +
    6. +
    7. + Run the test, as described in the previous section Running the Tests and Seeing the Results. +
    8. +
    +

    + The JUnit view is either created or updated with the results of the test. Now, however, the progress bar is red, + the number of failures is 2, and small "x" icons appear in the list icons next to the testPreConditions and + TestSpinnerUI tests. This indicates that the tests have failed. The display is similar to this:
    + + The JUnit Failure window + +

    +

    + You now want to look at the failures to see exactly where they occurred. +

    +

    + To examine the failures, follow these steps: +

    +
      +
    1. + Click the testPreconditions entry. In the lower pane entitled Failure Trace, + you see a stack trace of the calls that led to the failure. This trace is similar to the following screenshot:
      + + The JUnit failure trace + +
    2. +
    3. + The first line of the trace tells you the error. In this case, a JUnit assertion failed. To look at the + assertion in the test code, double-click the next line (the first line of the trace). In the center pane + a new tabbed window opens, containing the code for the test application SpinnerActivityTest. The failed assertion + is highlighted in the middle of the window. +
    4. +
    +

    + The assertion failed because you modified the main application to set the getOnItemSelectedListener callback to null. +

    +

    + You can look at the failure in testTextView if you want. Remember, though, that testPreConditions is meant to verify the + initial setup of the application under test. If testPreConditions() fails, then succeeding tests can't be trusted. The best strategy to follow is to + fix the problem and re-run all the tests. +

    +

    + Remember to go back to SpinnerActivity.java and re-comment the line you uncommented in an earlier step. +

    +

    + You have now completed the tutorial. +

    +

    Next Steps

    +

    + This example test application has shown you how to create a test project and link it to + the application you want to test, how to choose and add a test case class, how to write + UI and state management tests, and how to run the tests against the application under + test. Now that you are familiar with the basics of testing Android applications, here + are some suggested next steps: +

    +

    + Learn more about testing on Android +

    +
      +
    • + If you haven't done so already, read the + Testing Fundamentals + document in the Dev Guide. It provides an overview of how testing on Android + works. If you are just getting started with Android testing, reading that document will + help you understand the tools available to you, so that you can develop effective + tests. +
    • +
    +

    + Review the main Android test case classes +

    +
      +
    • + {@link android.test.ActivityInstrumentationTestCase2} +
    • +
    • + {@link android.test.ActivityUnitTestCase} +
    • +
    • + {@link android.test.ProviderTestCase2} +
    • +
    • + {@link android.test.ServiceTestCase} +
    • +
    +

    + Learn more about the assert and utility classes +

    +
      +
    • + {@link junit.framework.Assert}, the JUnit Assert class. +
    • +
    • + {@link android.test.MoreAsserts}, additional Android assert methods. +
    • +
    • + {@link android.test.ViewAsserts}, useful assertion methods for testing Views. +
    • +
    • + {@link android.test.TouchUtils}, utility methods for simulating touch events in an Activity. +
    • +
    +

    + Learn about instrumentation and the instrumented test runner +

    +
      +
    • + {@link android.app.Instrumentation}, the base instrumentation class. +
    • +
    • + {@link android.test.InstrumentationTestCase}, the base instrumentation test case. +
    • +
    • + {@link android.test.InstrumentationTestRunner}, the standard Android test runner. +
    • +
    +

    Appendix

    +

    Installing the Completed Test Application File

    +

    + The recommended approach to this tutorial is to follow the instructions step-by-step and + write the test code as you go. However, if you want to do this tutorial quickly, + you can install the entire file for the test application into the test project. +

    +

    + To do this, you first create a test project with the necessary structure and files by using + the automated tools in Eclipse. Then you exit Eclipse and copy the test application's file + from the SpinnerTest sample project into your test project. The SpinnerTest sample project is + part of the Samples component of the SDK. +

    +

    + The result is a complete test application, ready to run against the Spinner sample application. +

    +

    + To install the test application file, follow these steps: +

    +
      +
    1. + Set up the projects for the application under test and the test application, as described + in the section section Setting Up the Projects. +
    2. +
    3. + Set up the emulator, as described in the section Setting Up the Emulator. +
    4. +
    5. + Add the test case class, as described in the section Adding the test case class file. +
    6. +
    7. + Close Eclipse with ADT. +
    8. +
    9. + Copy the file <SDK_path>/samples/android-8/SpinnerTest/src/com/android/example/spinner/test/SpinnerActivityTest.java + to the directory workspace/SpinnerActivityTest/src/com/android/example/spinner/test/. +
    10. +
    11. + Restart Eclipse with ADT. +
    12. +
    13. + In Eclipse with ADT, re-build the project SpinnerActivityTest by selecting it in the Package Explorer, right-clicking, + and selecting Project > Clean. +
    14. +
    15. + The complete, working test application should now be in the SpinnerActivityTest project. +
    16. +
    +

    + You can now continue with the tutorial, starting at the section Adding the test case constructor and + following along in the text. +

    +

    For Users Not Developing In Eclipse

    +

    + If you are not developing in Eclipse, you can still do this tutorial. Android provides tools for + creating test applications using a code editor and command-line tools. You use the following tools: +

    +
      +
    • + adb - Installs and uninstalls applications and test applications to a device or the emulator. You + also use this tool to run the test application from the command line. +
    • +
    • + android - Manages projects and test projects. This tool also manages AVDs and Android platforms. +
    • +
    +

    + You use the emulator tool to run the emulator from the command line. +

    +

    + Here are the general steps for doing this tutorial using an editor and the command line: +

    +
      +
    1. + As described in the section Installing the Tutorial Sample Code, get the sample code. You will then + have a directory <SDK_path>/samples/android-8, containing (among others) the directories Spinner + and SpinnerTest: +
        +
      • + Spinner contains the main application, also known as the application under test. This tutorial focuses on the + common situation of writing tests for an application that already exists, so the main application is provided to you. +
      • +
      • + SpinnerTest contains all the code for the test application. If you want to run quickly through the tutorial, you can + install the test code and then follow the text. You may get more from the tutorial, however, if you write the code as you go. The instructions + for installing the test code are in the section Appendix: Installing the Completed Test Application File. +
      • +
      +
    2. +
    3. + Navigate to the directory <SDK_path>/samples/android-8. +
    4. +
    5. + Create a new Android application project using android create project: +
      +$ android create project -t <APItarget> -k com.android.example.spinner -a SpinnerActivity -n SpinnerActivity -p Spinner
      +
      +

      + The value of <APItarget> should be "3" (API level 3) or higher. If you are already developing with a particular API level, and it is + higher than 3, then use that API level. +

      +

      + This a new Android project SpinnerActivity in the existing Spinner directory. The existing source and + resource files are not touched, but the android tool adds the necessary build files. +

      +
    6. +
    7. + Create a new Android test project using android create test-project: +
      +$ android create test-project -m ../Spinner -n SpinnerActivityTest -p SpinnerActivityTest
      +
      +

      + This will create a new Android test project in the new directory SpinnerActivityTest. You do this + so that the solution to the tutorial that is in SpinnerTest is left untouched. If you want to use the solution + code instead of entering it as you read through the tutorial, refer to the section + Appendix: Installing the Completed Test Application File. +

      +

      + Note: Running android create test-project will automatically create + the file AndroidManifest.xml with the correct <instrumentation> element. +

      +
    8. +
    9. + Build the sample application. If you are building with Ant, then it is easiest to use the command ant debug to build a debug version, since the SDK comes + with a debug signing key. The result will be the file Spinner/bin/SpinnerActivity-debug.apk. + You can install this to your device or emulator. Attach your device or start the emulator if you haven't already, and run the command: +
      +$ adb install Spinner/bin/SpinnerActivity-debug.apk
      +
      +
    10. +
    11. + To create the test application, create a file SpinnerActivityTest.java in the directory + SpinnerActivityTest/src/com/android/example/spinner/test/. +
    12. +
    13. + Follow the tutorial, starting with the section Creating the Test Case Class. When you are prompted to + run the sample application, go the the Launcher screen in your device or emulator and select SpinnerActivity. + When you are prompted to run the test application, return here to continue with the following instructions. +
    14. +
    15. + Build the test application. If you are building with Ant, then it is easiest to use the command ant debug to build a + debug version, since the SDK comes with a debug signing key. The result will be the Android file + SpinnerActivityTest/bin/SpinnerActivityTest-debug.apk. You can install this to your device or emulator. + Attach your device or start the emulator if you haven't already, and run the command: +
      +$ adb install SpinnerActivityTest/bin/SpinnerActivityTest-debug.apk
      +
      +
    16. +
    17. + In your device or emulator, check that both the main application SpinnerActivity and the test application + SpinnerActivityTest are installed. +
    18. +
    19. + To run the test application, enter the following at the command line: +
      +$ adb shell am instrument -w com.android.example.spinner.test/android.test.InstrumentationTestRunner
      + 
      +
    20. +
    +

    + The result of a successful test looks like this: +

    +
    +com.android.example.spinner.test.SpinnerActivityTest:....
    +Test results for InstrumentationTestRunner=....
    +Time: 10.098
    +OK (4 tests)
    +
    +

    + If you force the test to fail, as described in the previous section Forcing Some Tests to Fail, then + the output looks like this: +

    +
    +com.android.example.spinner.test.SpinnerActivityTest:
    +Failure in testPreConditions:
    +junit.framework.AssertionFailedError
    +  at com.android.example.spinner.test.SpinnerActivityTest.testPreConditions(SpinnerActivityTest.java:104)
    +  at java.lang.reflect.Method.invokeNative(Native Method)
    +  at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)
    +  at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)
    +  at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:175)
    +  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
    +  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
    +  at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
    +  at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
    +Failure in testSpinnerUI:
    +junit.framework.ComparisonFailure: expected:<Result> but was:<Saturn>
    +  at com.android.example.spinner.test.SpinnerActivityTest.testSpinnerUI(SpinnerActivityTest.java:153)
    +  at java.lang.reflect.Method.invokeNative(Native Method)
    +  at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)
    +  at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)
    +  at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:175)
    +  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
    +  at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
    +  at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
    +  at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
    +..
    +Test results for InstrumentationTestRunner=.F.F..
    +Time: 9.377
    +FAILURES!!!
    +Tests run: 4,  Failures: 2,  Errors: 0
    +
    diff --git a/docs/html/tools/testing/activity_testing.jd b/docs/html/tools/testing/activity_testing.jd new file mode 100644 index 000000000000..7190b98d1a9f --- /dev/null +++ b/docs/html/tools/testing/activity_testing.jd @@ -0,0 +1,375 @@ +page.title=Activity Testing +parent.title=Testing +parent.link=index.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. + The Activity Testing API +
        +
      1. + ActivityInstrumentationTestCase2 +
      2. +
      3. + ActivityUnitTestCase +
      4. +
      5. + SingleLaunchActivityTestCase +
      6. +
      7. + Mock objects and activity testing +
      8. +
      9. + Assertions for activity testing +
      10. +
      +
    2. +
    3. + What to Test +
    4. +
    5. + Next Steps +
    6. +
    7. + Appendix: UI Testing Notes +
        +
      1. + Testing on the UI thread +
      2. +
      3. + Turning off touch mode +
      4. +
      5. + Unlocking the Emulator or Device +
      6. +
      7. + Troubleshooting UI tests +
      8. +
      +
    8. +
    +

    Key Classes

    +
      +
    1. {@link android.test.InstrumentationTestRunner}
    2. +
    3. {@link android.test.ActivityInstrumentationTestCase2}
    4. +
    5. {@link android.test.ActivityUnitTestCase}
    6. +
    +

    Related Tutorials

    +
      +
    1. + Activity Testing Tutorial +
    2. +
    +

    See Also

    +
      +
    1. + + Testing from Eclipse with ADT +
    2. +
    3. + + Testing from Other IDEs +
    4. +
    +
    +
    +

    + Activity testing is particularly dependent on the the Android instrumentation framework. + Unlike other components, activities have a complex lifecycle based on callback methods; these + can't be invoked directly except by instrumentation. Also, the only way to send events to the + user interface from a program is through instrumentation. +

    +

    + This document describes how to test activities using instrumentation and other test + facilities. The document assumes you have already read + Testing Fundamentals, + the introduction to the Android testing and instrumentation framework. +

    +

    The Activity Testing API

    +

    + The activity testing API base class is {@link android.test.InstrumentationTestCase}, + which provides instrumentation to the test case subclasses you use for Activities. +

    +

    + For activity testing, this base class provides these functions: +

    +
      +
    • + Lifecycle control: With instrumentation, you can start the activity under test, pause it, + and destroy it, using methods provided by the test case classes. +
    • +
    • + Dependency injection: Instrumentation allows you to create mock system objects such as + Contexts or Applications and use them to run the activity under test. This + helps you control the test environment and isolate it from production systems. You can + also set up customized Intents and start an activity with them. +
    • +
    • + User interface interaction: You use instrumentation to send keystrokes or touch events + directly to the UI of the activity under test. +
    • +
    +

    + The activity testing classes also provide the JUnit framework by extending + {@link junit.framework.TestCase} and {@link junit.framework.Assert}. +

    +

    + The two main testing subclasses are {@link android.test.ActivityInstrumentationTestCase2} and + {@link android.test.ActivityUnitTestCase}. To test an Activity that is launched in a mode + other than standard, you use {@link android.test.SingleLaunchActivityTestCase}. +

    +

    ActivityInstrumentationTestCase2

    +

    + The {@link android.test.ActivityInstrumentationTestCase2} test case class is designed to do + functional testing of one or more Activities in an application, using a normal system + infrastructure. It runs the Activities in a normal instance of the application under test, + using a standard system Context. It allows you to send mock Intents to the activity under + test, so you can use it to test an activity that responds to multiple types of intents, or + an activity that expects a certain type of data in the intent, or both. Notice, though, that it + does not allow mock Contexts or Applications, so you can not isolate the test from the rest of + a production system. +

    +

    ActivityUnitTestCase

    +

    + The {@link android.test.ActivityUnitTestCase} test case class tests a single activity in + isolation. Before you start the activity, you can inject a mock Context or Application, or both. + You use it to run activity tests in isolation, and to do unit testing of methods + that do not interact with Android. You can not send mock Intents to the activity under test, + although you can call + {@link android.app.Activity#startActivity(Intent) Activity.startActivity(Intent)} and then + look at arguments that were received. +

    +

    SingleLaunchActivityTestCase

    +

    + The {@link android.test.SingleLaunchActivityTestCase} class is a convenience class for + testing a single activity in an environment that doesn't change from test to test. + It invokes {@link junit.framework.TestCase#setUp() setUp()} and + {@link junit.framework.TestCase#tearDown() tearDown()} only once, instead of once per + method call. It does not allow you to inject any mock objects. +

    +

    + This test case is useful for testing an activity that runs in a mode other than + standard. It ensures that the test fixture is not reset between tests. You + can then test that the activity handles multiple calls correctly. +

    +

    Mock objects and activity testing

    +

    + This section contains notes about the use of the mock objects defined in + {@link android.test.mock} with activity tests. +

    +

    + The mock object {@link android.test.mock.MockApplication} is only available for activity + testing if you use the {@link android.test.ActivityUnitTestCase} test case class. + By default, ActivityUnitTestCase, creates a hidden MockApplication + object that is used as the application under test. You can inject your own object using + {@link android.test.ActivityUnitTestCase#setApplication(Application) setApplication()}. +

    +

    Assertions for activity testing

    +

    + {@link android.test.ViewAsserts} defines assertions for Views. You use it to verify the + alignment and position of View objects, and to look at the state of ViewGroup objects. +

    +

    What To Test

    +
      +
    • + Input validation: Test that an activity responds correctly to input values in an + EditText View. Set up a keystroke sequence, send it to the activity, and then + use {@link android.view.View#findViewById(int)} to examine the state of the View. You can + verify that a valid keystroke sequence enables an OK button, while an invalid one leaves the + button disabled. You can also verify that the Activity responds to invalid input by + setting error messages in the View. +
    • +
    • + Lifecycle events: Test that each of your application's activities handles lifecycle events + correctly. In general, lifecycle events are actions, either from the system or from the + user, that trigger a callback method such as onCreate() or + onClick(). For example, an activity should respond to pause or destroy events + by saving its state. Remember that even a change in screen orientation causes the current + activity to be destroyed, so you should test that accidental device movements don't + accidentally lose the application state. +
    • +
    • + Intents: Test that each activity correctly handles the intents listed in the intent + filter specified in its manifest. You can use + {@link android.test.ActivityInstrumentationTestCase2} to send mock Intents to the + activity under test. +
    • +
    • + Runtime configuration changes: Test that each activity responds correctly to the + possible changes in the device's configuration while your application is running. These + include a change to the device's orientation, a change to the current language, and so + forth. Handling these changes is described in detail in the topic + Handling Runtime + Changes. +
    • +
    • + Screen sizes and resolutions: Before you publish your application, make sure to test it on + all of the screen sizes and densities on which you want it to run. You can test the + application on multiple sizes and densities using AVDs, or you can test your application + directly on the devices that you are targeting. For more information, see the topic + Supporting Multiple Screens. +
    • +
    +

    Next Steps

    +

    + To learn how to set up and run tests in Eclipse, please refer to +Testing from Eclipse with ADT. + If you're not working in Eclipse, refer to +Testing from Other IDEs. +

    +

    + If you want a step-by-step introduction to testing activities, try the + Activity Testing Tutorial, which + guides you through a testing scenario that you develop against an activity-oriented application. +

    +

    Appendix: UI Testing Notes

    +

    + The following sections have tips for testing the UI of your Android application, specifically + to help you handle actions that run in the UI thread, touch screen and keyboard events, and home + screen unlock during testing. +

    +

    Testing on the UI thread

    +

    + An application's activities run on the application's UI thread. Once the + UI is instantiated, for example in the activity's onCreate() method, then all + interactions with the UI must run in the UI thread. When you run the application normally, it + has access to the thread and does not have to do anything special. +

    +

    + This changes when you run tests against the application. With instrumentation-based classes, + you can invoke methods against the UI of the application under test. The other test classes + don't allow this. To run an entire test method on the UI thread, you can annotate the thread + with @UIThreadTest. Notice that this will run all of the method statements + on the UI thread. Methods that do not interact with the UI are not allowed; for example, you + can't invoke Instrumentation.waitForIdleSync(). +

    +

    + To run a subset of a test method on the UI thread, create an anonymous class of type + Runnable, put the statements you want in the run() method, and + instantiate a new instance of the class as a parameter to the method + appActivity.runOnUiThread(), where appActivity is + the instance of the application you are testing. +

    +

    + For example, this code instantiates an activity to test, requests focus (a UI action) for the + Spinner displayed by the activity, and then sends a key to it. Notice that the calls to + waitForIdleSync and sendKeys aren't allowed to run on the UI thread: +

    +
    +  private MyActivity mActivity; // MyActivity is the class name of the app under test
    +  private Spinner mSpinner;
    +
    +  ...
    +
    +  protected void setUp() throws Exception {
    +      super.setUp();
    +      mInstrumentation = getInstrumentation();
    +
    +      mActivity = getActivity(); // get a references to the app under test
    +
    +      /*
    +       * Get a reference to the main widget of the app under test, a Spinner
    +       */
    +      mSpinner = (Spinner) mActivity.findViewById(com.android.demo.myactivity.R.id.Spinner01);
    +
    +  ...
    +
    +  public void aTest() {
    +      /*
    +       * request focus for the Spinner, so that the test can send key events to it
    +       * This request must be run on the UI thread. To do this, use the runOnUiThread method
    +       * and pass it a Runnable that contains a call to requestFocus on the Spinner.
    +       */
    +      mActivity.runOnUiThread(new Runnable() {
    +          public void run() {
    +              mSpinner.requestFocus();
    +          }
    +      });
    +
    +      mInstrumentation.waitForIdleSync();
    +
    +      this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
    +
    + +

    Turning off touch mode

    +

    + To control the emulator or a device with key events you send from your tests, you must turn off + touch mode. If you do not do this, the key events are ignored. +

    +

    + To turn off touch mode, you invoke + ActivityInstrumentationTestCase2.setActivityTouchMode(false) + before you call getActivity() to start the activity. You must invoke the + method in a test method that is not running on the UI thread. For this reason, you + can't invoke the touch mode method from a test method that is annotated with + @UIThread. Instead, invoke the touch mode method from setUp(). +

    +

    Unlocking the emulator or device

    +

    + You may find that UI tests don't work if the emulator's or device's home screen is disabled with + the keyguard pattern. This is because the application under test can't receive key events sent + by sendKeys(). The best way to avoid this is to start your emulator or device + first and then disable the keyguard for the home screen. +

    +

    + You can also explicitly disable the keyguard. To do this, + you need to add a permission in the manifest file (AndroidManifest.xml) and + then disable the keyguard in your application under test. Note, though, that you either have to + remove this before you publish your application, or you have to disable it with code in + the published application. +

    +

    + To add the the permission, add the element + <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/> + as a child of the <manifest> element. To disable the KeyGuard, add the + following code to the onCreate() method of activities you intend to test: +

    +
    +  mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    +  mLock = mKeyGuardManager.newKeyguardLock("activity_classname");
    +  mLock.disableKeyguard();
    +
    +

    where activity_classname is the class name of the activity.

    +

    Troubleshooting UI tests

    +

    + This section lists some of the common test failures you may encounter in UI testing, and their + causes: +

    +
    +
    WrongThreadException
    +
    +

    Problem:

    + For a failed test, the Failure Trace contains the following error message: + + android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created + a view hierarchy can touch its views. + +

    Probable Cause:

    + This error is common if you tried to send UI events to the UI thread from outside the UI + thread. This commonly happens if you send UI events from the test application, but you don't + use the @UIThread annotation or the runOnUiThread() method. The + test method tried to interact with the UI outside the UI thread. +

    Suggested Resolution:

    + Run the interaction on the UI thread. Use a test class that provides instrumentation. See + the previous section Testing on the UI Thread + for more details. +
    +
    java.lang.RuntimeException
    +
    +

    Problem:

    + For a failed test, the Failure Trace contains the following error message: + + java.lang.RuntimeException: This method can not be called from the main application thread + +

    Probable Cause:

    + This error is common if your test method is annotated with @UiThreadTest but + then tries to do something outside the UI thread or tries to invoke + runOnUiThread(). +

    Suggested Resolution:

    + Remove the @UiThreadTest annotation, remove the runOnUiThread() + call, or re-factor your tests. +
    +
    diff --git a/docs/html/tools/testing/contentprovider_testing.jd b/docs/html/tools/testing/contentprovider_testing.jd new file mode 100644 index 000000000000..a6440df0f4c4 --- /dev/null +++ b/docs/html/tools/testing/contentprovider_testing.jd @@ -0,0 +1,217 @@ +page.title=Content Provider Testing +parent.title=Testing +parent.link=index.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. + Content Provider Design and Testing +
    2. +
    3. + The Content Provider Testing API +
        +
      1. + ProviderTestCase2 +
      2. +
      3. + Mock object classes +
      4. +
      +
    4. +
    5. + What To Test +
    6. +
    7. + Next Steps +
    8. +
    +

    Key Classes

    +
      +
    1. {@link android.test.InstrumentationTestRunner}
    2. +
    3. {@link android.test.ProviderTestCase2}
    4. +
    5. {@link android.test.IsolatedContext}
    6. +
    7. {@link android.test.mock.MockContentResolver}
    8. +
    +

    Related Tutorials

    +
      +
    1. + Activity Testing Tutorial +
    2. +
    +

    See Also

    +
      +
    1. + + Testing Fundamentals +
    2. +
    3. + + Testing From Eclipse with ADT +
    4. +
    5. + + Testing From Other IDEs +
    6. +
    +
    +
    +

    + Content providers, which store and retrieve data and make it accessible across applications, + are a key part of the Android API. As an application developer you're allowed to provide your + own public providers for use by other applications. If you do, then you should test them + using the API you publish. +

    +

    + This document describes how to test public content providers, although the information is + also applicable to providers that you keep private to your own application. If you aren't + familiar with content providers or the Android testing framework, please read + Content Providers, + the guide to developing content providers, and + Testing Fundamentals, + the introduction to the Android testing and instrumentation framework. +

    +

    Content Provider Design and Testing

    +

    + In Android, content providers are viewed externally as data APIs that provide + tables of data, with their internals hidden from view. A content provider may have many + public constants, but it usually has few if any public methods and no public variables. + This suggests that you should write your tests based only on the provider's public members. + A content provider that is designed like this is offering a contract between itself and its + users. +

    +

    + The base test case class for content providers, + {@link android.test.ProviderTestCase2}, allows you to test your content provider in an + isolated environment. Android mock objects such as {@link android.test.IsolatedContext} and + {@link android.test.mock.MockContentResolver} also help provide an isolated test environment. +

    +

    + As with other Android tests, provider test packages are run under the control of the test + runner {@link android.test.InstrumentationTestRunner}. The section + + Running Tests With InstrumentationTestRunner describes the test runner in + more detail. The topic + Testing From Eclipse with ADT shows you how to run a test package in Eclipse, and the + topic + Testing From Other IDEs + shows you how to run a test package from the command line. +

    +

    Content Provider Testing API

    +

    + The main focus of the provider testing API is to provide an isolated testing environment. This + ensures that tests always run against data dependencies set explicitly in the test case. It + also prevents tests from modifying actual user data. For example, you want to avoid writing + a test that fails because there was data left over from a previous test, and you want to + avoid adding or deleting contact information in a actual provider. +

    +

    + The test case class and mock object classes for provider testing set up this isolated testing + environment for you. +

    +

    ProviderTestCase2

    +

    + You test a provider with a subclass of {@link android.test.ProviderTestCase2}. This base class + extends {@link android.test.AndroidTestCase}, so it provides the JUnit testing framework as well + as Android-specific methods for testing application permissions. The most important + feature of this class is its initialization, which creates the isolated test environment. +

    +

    + The initialization is done in the constructor for {@link android.test.ProviderTestCase2}, which + subclasses call in their own constructors. The {@link android.test.ProviderTestCase2} + constructor creates an {@link android.test.IsolatedContext} object that allows file and + database operations but stubs out other interactions with the Android system. + The file and database operations themselves take place in a directory that is local to the + device or emulator and has a special prefix. +

    +

    + The constructor then creates a {@link android.test.mock.MockContentResolver} to use as the + resolver for the test. The {@link android.test.mock.MockContentResolver} class is described in + detail in the section + Mock object +classes. +

    +

    + Lastly, the constructor creates an instance of the provider under test. This is a normal + {@link android.content.ContentProvider} object, but it takes all of its environment information + from the {@link android.test.IsolatedContext}, so it is restricted to + working in the isolated test environment. All of the tests done in the test case class run + against this isolated object. +

    +

    Mock object classes

    +

    + {@link android.test.ProviderTestCase2} uses {@link android.test.IsolatedContext} and + {@link android.test.mock.MockContentResolver}, which are standard mock object classes. To + learn more about them, please read + + Testing Fundamentals. +

    +

    What To Test

    +

    + The topic What To Test + lists general considerations for testing Android components. + Here are some specific guidelines for testing content providers. +

    +
      +
    • + Test with resolver methods: Even though you can instantiate a provider object in + {@link android.test.ProviderTestCase2}, you should always test with a resolver object + using the appropriate URI. This ensures that you are testing the provider using the same + interaction that a regular application would use. +
    • +
    • + Test a public provider as a contract: If you intent your provider to be public and + available to other applications, you should test it as a contract. This includes + the following ideas: +
        +
      • + Test with constants that your provider publicly exposes. For + example, look for constants that refer to column names in one of the provider's + data tables. These should always be constants publicly defined by the provider. +
      • +
      • + Test all the URIs offered by your provider. Your provider may offer several URIs, + each one referring to a different aspect of the data. The + Note Pad sample, + for example, features a provider that offers one URI for retrieving a list of notes, + another for retrieving an individual note by it's database ID, and a third for + displaying notes in a live folder. +
      • +
      • + Test invalid URIs: Your unit tests should deliberately call the provider with an + invalid URI, and look for errors. Good provider design is to throw an + IllegalArgumentException for invalid URIs. + +
      • +
      +
    • +
    • + Test the standard provider interactions: Most providers offer six access methods: + query, insert, delete, update, getType, and onCreate(). Your tests should verify that all + of these methods work. These are described in more detail in the topic + Content Providers. +
    • +
    • + Test business logic: Don't forget to test the business logic that your provider should + enforce. Business logic includes handling of invalid values, financial or arithmetic + calculations, elimination or combining of duplicates, and so forth. A content provider + does not have to have business logic, because it may be implemented by activities that + modify the data. If the provider does implement business logic, you should test it. +
    • +
    +

    Next Steps

    +

    + To learn how to set up and run tests in Eclipse, please refer to +Testing from Eclipse with ADT. + If you're not working in Eclipse, refer to +Testing From Other IDEs. +

    +

    + If you want a step-by-step introduction to testing activities, try the + Activity Testing Tutorial, which + guides you through a testing scenario that you develop against an activity-oriented application. +

    + diff --git a/docs/html/tools/testing/index.jd b/docs/html/tools/testing/index.jd new file mode 100644 index 000000000000..56de4cf80658 --- /dev/null +++ b/docs/html/tools/testing/index.jd @@ -0,0 +1,40 @@ +page.title=Testing +@jd:body + +

    The Android framework includes an integrated testing framework that helps you test all aspects +of your application and the SDK tools include tools for setting up and running test applications. +Whether you are working in Eclipse with ADT or working from the command line, the SDK tools help you +set up and run your tests within an emulator or the device you are targeting.

    + +

    If you aren't yet familiar with the Android testing framework, start by reading Testing Fundamentals. For a step-by-step +introduction to Android testing, try the Activity Testing Tutorial.

    + + + + + + diff --git a/docs/html/tools/testing/service_testing.jd b/docs/html/tools/testing/service_testing.jd new file mode 100644 index 000000000000..7c56fd947df6 --- /dev/null +++ b/docs/html/tools/testing/service_testing.jd @@ -0,0 +1,176 @@ +page.title=Service Testing +parent.title=Testing +parent.link=index.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. + Service Design and Testing +
    2. +
    3. + ServiceTestCase +
    4. +
    5. + Mock object classes +
    6. +
    7. + What to Test +
    8. +
    +

    Key Classes

    +
      +
    1. {@link android.test.InstrumentationTestRunner}
    2. +
    3. {@link android.test.ServiceTestCase}
    4. +
    5. {@link android.test.mock.MockApplication}
    6. +
    7. {@link android.test.RenamingDelegatingContext}
    8. +
    +

    Related Tutorials

    +
      +
    1. + Activity Testing Tutorial +
    2. +
    +

    See Also

    +
      +
    1. + + Testing From Eclipse with ADT +
    2. +
    3. + + Testing From Other IDEs +
    4. +
    +
    +
    +

    + Android provides a testing framework for Service objects that can run them in + isolation and provides mock objects. The test case class for Service objects is + {@link android.test.ServiceTestCase}. Since the Service class assumes that it is separate + from its clients, you can test a Service object without using instrumentation. +

    +

    + This document describes techniques for testing Service objects. If you aren't familiar with the + Service class, please read the + Services document. If you aren't familiar with Android testing, please read + Testing Fundamentals, + the introduction to the Android testing and instrumentation framework. +

    +

    Service Design and Testing

    +

    + When you design a Service, you should consider how your tests can examine the various states + of the Service lifecycle. If the lifecycle methods that start up your Service, such as + {@link android.app.Service#onCreate() onCreate()} or + {@link android.app.Service#onStartCommand(Intent, int, int) onStartCommand()} do not normally + set a global variable to indicate that they were successful, you may want to provide such a + variable for testing purposes. +

    +

    + Most other testing is facilitated by the methods in the {@link android.test.ServiceTestCase} + test case class. For example, the {@link android.test.ServiceTestCase#getService()} method + returns a handle to the Service under test, which you can test to confirm that the Service is + running even at the end of your tests. +

    +

    ServiceTestCase

    +

    + {@link android.test.ServiceTestCase} extends the JUnit {@link junit.framework.TestCase} class + with with methods for testing application permissions and for controlling the application and + Service under test. It also provides mock application and Context objects that isolate your + test from the rest of the system. +

    +

    + {@link android.test.ServiceTestCase} defers initialization of the test environment until you + call {@link android.test.ServiceTestCase#startService(Intent) ServiceTestCase.startService()} or + {@link android.test.ServiceTestCase#bindService(Intent) ServiceTestCase.bindService()}. This + allows you to set up your test environment, particularly your mock objects, before the Service + is started. +

    +

    + Notice that the parameters to ServiceTestCase.bindService()are different from + those for Service.bindService(). For the ServiceTestCase version, + you only provide an Intent. Instead of returning a boolean, + ServiceTestCase.bindService() returns an object that subclasses + {@link android.os.IBinder}. +

    +

    + The {@link android.test.ServiceTestCase#setUp()} method for {@link android.test.ServiceTestCase} + is called before each test. It sets up the test fixture by making a copy of the current system + Context before any test methods touch it. You can retrieve this Context by calling + {@link android.test.ServiceTestCase#getSystemContext()}. If you override this method, you must + call super.setUp() as the first statement in the override. +

    +

    + The methods {@link android.test.ServiceTestCase#setApplication(Application) setApplication()} + and {@link android.test.AndroidTestCase#setContext(Context)} setContext()} allow you to set + a mock Context or mock Application (or both) for the Service, before you start it. These mock + objects are described in Mock object classes. +

    +

    + By default, {@link android.test.ServiceTestCase} runs the test method + {@link android.test.AndroidTestCase#testAndroidTestCaseSetupProperly()}, which asserts that + the base test case class successfully set up a Context before running. +

    +

    Mock object classes

    +

    + ServiceTestCase assumes that you will use a mock Context or mock Application + (or both) for the test environment. These objects isolate the test environment from the + rest of the system. If you don't provide your own instances of these objects before you + start the Service, then {@link android.test.ServiceTestCase} will create its own internal + instances and inject them into the Service. You can override this behavior by creating and + injecting your own instances before starting the Service +

    +

    + To inject a mock Application object into the Service under test, first create a subclass of + {@link android.test.mock.MockApplication}. MockApplication is a subclass of + {@link android.app.Application} in which all the methods throw an Exception, so to use it + effectively you subclass it and override the methods you need. You then inject it into the + Service with the + {@link android.test.ServiceTestCase#setApplication(Application) setApplication()} method. + This mock object allows you to control the application values that the Service sees, and + isolates it from the real system. In addition, any hidden dependencies your Service has on + its application reveal themselves as exceptions when you run the test. +

    +

    + You inject a mock Context into the Service under test with the + {@link android.test.AndroidTestCase#setContext(Context) setContext()} method. The mock + Context classes you can use are described in more detail in + + Testing Fundamentals. +

    +

    What to Test

    +

    + The topic What To Test + lists general considerations for testing Android components. + Here are some specific guidelines for testing a Service: +

    +
      +
    • + Ensure that the {@link android.app.Service#onCreate()} is called in response to + {@link android.content.Context#startService(Intent) Context.startService()} or + {@link android.content.Context#bindService(Intent,ServiceConnection,int) Context.bindService()}. + Similarly, you should ensure that {@link android.app.Service#onDestroy()} is called in + response to {@link android.content.Context#stopService(Intent) Context.stopService()}, + {@link android.content.Context#unbindService(ServiceConnection) Context.unbindService()}, + {@link android.app.Service#stopSelf()}, or + {@link android.app.Service#stopSelfResult(int) stopSelfResult()}. +
    • +
    • + Test that your Service correctly handles multiple calls from + Context.startService(). Only the first call triggers + Service.onCreate(), but all calls trigger a call to + Service.onStartCommand(). +

      + In addition, remember that startService() calls don't + nest, so a single call to Context.stopService() or + Service.stopSelf() (but not stopSelf(int)) + will stop the Service. You should test that your Service stops at the correct point. +

      +
    • +
    • + Test any business logic that your Service implements. Business logic includes checking for + invalid values, financial and arithmetic calculations, and so forth. +
    • +
    diff --git a/docs/html/tools/testing/testing_android.jd b/docs/html/tools/testing/testing_android.jd new file mode 100755 index 000000000000..acf5ec2ef1eb --- /dev/null +++ b/docs/html/tools/testing/testing_android.jd @@ -0,0 +1,640 @@ +page.title=Testing Fundamentals +parent.title=Testing +parent.link=index.html +@jd:body + +
    +
    +

    In this document

    +
      +
    1. + Test Structure +
    2. +
    3. + Test Projects +
    4. +
    5. + The Testing API +
        +
      1. + JUnit +
      2. +
      3. + Instrumentation +
      4. +
      5. + Test case classes +
      6. +
      7. + Assertion classes +
      8. +
      9. + Mock object classes +
      10. +
      +
    6. +
    7. + Running Tests +
    8. +
    9. + Seeing Test Results +
    10. +
    11. + monkey and monkeyrunner +
    12. +
    13. + Working With Package Names +
    14. +
    15. + What To Test +
    16. +
    17. + Next Steps +
    18. +
    +

    Key classes

    +
      +
    1. {@link android.test.InstrumentationTestRunner}
    2. +
    3. {@link android.test}
    4. +
    5. {@link android.test.mock}
    6. +
    7. {@link junit.framework}
    8. +
    +

    Related tutorials

    +
      +
    1. + Activity Testing Tutorial +
    2. +
    +

    See also

    +
      +
    1. + + Testing from Eclipse with ADT +
    2. +
    3. + + Testing from Other IDEs +
    4. +
    5. + + monkeyrunner +
    6. +
    7. + UI/Application Exerciser Monkey +
    8. +
    +
    +
    +

    + The Android testing framework, an integral part of the development environment, + provides an architecture and powerful tools that help you test every aspect of your application + at every level from unit to framework. +

    +

    + The testing framework has these key features: +

    +
      +
    • + Android test suites are based on JUnit. You can use plain JUnit to test a class that doesn't + call the Android API, or Android's JUnit extensions to test Android components. If you're + new to Android testing, you can start with general-purpose test case classes such as {@link + android.test.AndroidTestCase} and then go on to use more sophisticated classes. +
    • +
    • + The Android JUnit extensions provide component-specific test case classes. These classes + provide helper methods for creating mock objects and methods that help you control the + lifecycle of a component. +
    • +
    • + Test suites are contained in test packages that are similar to main application packages, so + you don't need to learn a new set of tools or techniques for designing and building tests. +
    • +
    • + The SDK tools for building and tests are available in Eclipse with ADT, and also in + command-line form for use with other IDES. These tools get information from the project of + the application under test and use this information to automatically create the build files, + manifest file, and directory structure for the test package. +
    • +
    • + The SDK also provides + monkeyrunner, an API + testing devices with Python programs, and UI/Application Exerciser Monkey, + a command-line tool for stress-testing UIs by sending pseudo-random events to a device. +
    • +
    +

    + This document describes the fundamentals of the Android testing framework, including the + structure of tests, the APIs that you use to develop tests, and the tools that you use to run + tests and view results. The document assumes you have a basic knowledge of Android application + programming and JUnit testing methodology. +

    +

    + The following diagram summarizes the testing framework: +

    +
    + + The Android testing framework + +
    +

    Test Structure

    +

    + Android's build and test tools assume that test projects are organized into a standard + structure of tests, test case classes, test packages, and test projects. +

    +

    + Android testing is based on JUnit. In general, a JUnit test is a method whose + statements test a part of the application under test. You organize test methods into classes + called test cases (or test suites). Each test is an isolated test of an individual module in + the application under test. Each class is a container for related test methods, although it + often provides helper methods as well. +

    +

    + In JUnit, you build one or more test source files into a class file. Similarly, in Android you + use the SDK's build tools to build one or more test source files into class files in an + Android test package. In JUnit, you use a test runner to execute test classes. In Android, you + use test tools to load the test package and the application under test, and the tools then + execute an Android-specific test runner. +

    +

    Test Projects

    +

    + Tests, like Android applications, are organized into projects. +

    +

    + A test project is a directory or Eclipse project in which you create the source code, manifest + file, and other files for a test package. The Android SDK contains tools for Eclipse with ADT + and for the command line that create and update test projects for you. The tools create the + directories you use for source code and resources and the manifest file for the test package. + The command-line tools also create the Ant build files you need. +

    +

    + You should always use Android tools to create a test project. Among other benefits, + the tools: +

    +
      +
    • + Automatically set up your test package to use + {@link android.test.InstrumentationTestRunner} as the test case runner. You must use + InstrumentationTestRunner (or a subclass) to run JUnit tests. +
    • +
    • + Create an appropriate name for the test package. If the application + under test has a package name of com.mydomain.myapp, then the + Android tools set the test package name to com.mydomain.myapp.test. This + helps you identify their relationship, while preventing conflicts within the system. +
    • +
    • + Automatically create the proper build files, manifest file, and directory + structure for the test project. This helps you to build the test package without + having to modify build files and sets up the linkage between your test package and + the application under test. + The +
    • +
    +

    + You can create a test project anywhere in your file system, but the best approach is to + add the test project so that its root directory tests/ is at the same level + as the src/ directory of the main application's project. This helps you find the + tests associated with an application. For example, if your application project's root directory + is MyProject, then you should use the following directory structure: +

    +
    +  MyProject/
    +      AndroidManifest.xml
    +      res/
    +          ... (resources for main application)
    +      src/
    +          ... (source code for main application) ...
    +      tests/
    +          AndroidManifest.xml
    +          res/
    +              ... (resources for tests)
    +          src/
    +              ... (source code for tests)
    +
    +

    The Testing API

    +

    + The Android testing API is based on the JUnit API and extended with a instrumentation + framework and Android-specific testing classes. +

    +

    JUnit

    +

    + You can use the JUnit {@link junit.framework.TestCase TestCase} class to do unit testing on + a class that doesn't call Android APIs. TestCase is also the base class for + {@link android.test.AndroidTestCase}, which you can use to test Android-dependent objects. + Besides providing the JUnit framework, AndroidTestCase offers Android-specific setup, + teardown, and helper methods. +

    +

    + You use the JUnit {@link junit.framework.Assert} class to display test results. + The assert methods compare values you expect from a test to the actual results and + throw an exception if the comparison fails. Android also provides a class of assertions that + extend the possible types of comparisons, and another class of assertions for testing the UI. + These are described in more detail in the section + Assertion classes +

    +

    + To learn more about JUnit, you can read the documentation on the + junit.org home page. + Note that the Android testing API supports JUnit 3 code style, but not JUnit 4. Also, you must + use Android's instrumented test runner {@link android.test.InstrumentationTestRunner} to run + your test case classes. This test runner is described in the + section Running Tests. +

    +

    Instrumentation

    +

    + Android instrumentation is a set of control methods or "hooks" in the Android system. These hooks + control an Android component independently of its normal lifecycle. They also control how + Android loads applications. +

    +

    + Normally, an Android component runs in a lifecycle determined by the system. For example, an + Activity object's lifecycle starts when the Activity is activated by an Intent. The object's + onCreate() method is called, followed by onResume(). When the user + starts another application, the onPause() method is called. If the Activity + code calls the finish() method, the onDestroy() method is called. + The Android framework API does not provide a way for your code to invoke these callback + methods directly, but you can do so using instrumentation. +

    +

    + Also, the system runs all the components of an application into the same + process. You can allow some components, such as content providers, to run in a separate process, + but you can't force an application to run in the same process as another application that is + already running. +

    +

    + With Android instrumentation, though, you can invoke callback methods in your test code. + This allows you to run through the lifecycle of a component step by step, as if you were + debugging the component. The following test code snippet demonstrates how to use this to + test that an Activity saves and restores its state: +

    + +
    +    // Start the main activity of the application under test
    +    mActivity = getActivity();
    +
    +    // Get a handle to the Activity object's main UI widget, a Spinner
    +    mSpinner = (Spinner)mActivity.findViewById(com.android.example.spinner.R.id.Spinner01);
    +
    +    // Set the Spinner to a known position
    +    mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
    +
    +    // Stop the activity - The onDestroy() method should save the state of the Spinner
    +    mActivity.finish();
    +
    +    // Re-start the Activity - the onResume() method should restore the state of the Spinner
    +    mActivity = getActivity();
    +
    +    // Get the Spinner's current position
    +    int currentPosition = mActivity.getSpinnerPosition();
    +
    +    // Assert that the current position is the same as the starting position
    +    assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
    +
    +

    + The key method used here is + {@link android.test.ActivityInstrumentationTestCase2#getActivity()}, which is a + part of the instrumentation API. The Activity under test is not started until you call this + method. You can set up the test fixture in advance, and then call this method to start the + Activity. +

    +

    + Also, instrumentation can load both a test package and the application under test into the + same process. Since the application components and their tests are in the same process, the + tests can invoke methods in the components, and modify and examine fields in the components. +

    +

    Test case classes

    +

    + Android provides several test case classes that extend {@link junit.framework.TestCase} and + {@link junit.framework.Assert} with Android-specific setup, teardown, and helper methods. +

    +

    AndroidTestCase

    +

    + 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 setUp() and tearDown() 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. +

    +

    Component-specific test cases

    +

    + A key feature of the Android testing framework is its component-specific test case classes. + These address specific component testing needs with methods for fixture setup and + teardown and component lifecycle control. They also provide methods for setting up mock objects. + These classes are described in the component-specific testing topics: +

    + +

    + Android does not provide a separate test case class for BroadcastReceiver. Instead, test a + BroadcastReceiver by testing the component that sends it Intent objects, to verify that the + BroadcastReceiver responds correctly. +

    +

    ApplicationTestCase

    +

    + You use the {@link android.test.ApplicationTestCase} test case class to test the setup and + teardown of {@link android.app.Application} objects. These objects maintain the global state of + information that applies to all the components in an application package. The test case can + be useful in verifying that the <application> element in the manifest file is correctly + set up. Note, however, that this test case does not allow you to control testing of the + components within your application package. +

    +

    InstrumentationTestCase

    +

    + If you want to use instrumentation methods in a test case class, you must use + {@link android.test.InstrumentationTestCase} or one of its subclasses. The + {@link android.app.Activity} test cases extend this base class with other functionality that + assists in Activity testing. +

    + +

    Assertion classes

    +

    + Because Android test case classes extend JUnit, you can use assertion methods to display the + results of tests. An assertion method compares an actual value returned by a test to an + expected value, and throws an AssertionException if the comparison test fails. Using assertions + is more convenient than doing logging, and provides better test performance. +

    +

    + Besides the JUnit {@link junit.framework.Assert} class methods, the testing API also provides + the {@link android.test.MoreAsserts} and {@link android.test.ViewAsserts} classes: +

    +
      +
    • + {@link android.test.MoreAsserts} contains more powerful assertions such as + {@link android.test.MoreAsserts#assertContainsRegex}, which does regular expression + matching. +
    • +
    • + {@link android.test.ViewAsserts} contains useful assertions about Views. For example + it contains {@link android.test.ViewAsserts#assertHasScreenCoordinates} that tests if a View + has a particular X and Y position on the visible screen. These asserts simplify testing of + geometry and alignment in the UI. +
    • +
    +

    Mock object classes

    +

    + To facilitate dependency injection in testing, Android provides classes that create mock system + objects such as {@link android.content.Context} objects, + {@link android.content.ContentProvider} objects, {@link android.content.ContentResolver} + objects, and {@link android.app.Service} objects. Some test cases also provide mock + {@link android.content.Intent} objects. You use these mocks both to isolate tests + from the rest of the system and to facilitate dependency injection for testing. These classes + are found in the packages {@link android.test} and {@link android.test.mock}. +

    +

    + 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 stubs out the + {@link android.content.ContentResolver#notifyChange(Uri, ContentObserver, boolean)} method + so that observer objects outside the test environment are not accidentally triggered. +

    +

    + Mock object classes also facilitate dependency injection by providing a subclass of the + normal object that is non-functional except for overrides you define. For example, the + {@link android.test.mock.MockResources} object provides a subclass of + {@link android.content.res.Resources} in which all the methods throw Exceptions when called. + To use it, you override only those methods that must provide information. +

    +

    + These are the mock object classes available in Android: +

    +

    Simple mock object classes

    +

    + {@link android.test.mock.MockApplication}, {@link android.test.mock.MockContext}, + {@link android.test.mock.MockContentProvider}, {@link android.test.mock.MockCursor}, + {@link android.test.mock.MockDialogInterface}, {@link android.test.mock.MockPackageManager}, and + {@link android.test.mock.MockResources} provide a simple and useful mock strategy. They are + stubbed-out versions of the corresponding system object class, and all of their methods throw an + {@link java.lang.UnsupportedOperationException} exception if called. To use them, you override + the methods you need in order to provide mock dependencies. +

    +

    Note: + {@link android.test.mock.MockContentProvider} + and {@link android.test.mock.MockCursor} are new as of API level 8. +

    +

    Resolver mock objects

    +

    + {@link android.test.mock.MockContentResolver} provides isolated testing of content providers by + masking out the normal system resolver framework. Instead of looking in the system to find a + content provider given an authority string, MockContentResolver uses its own internal table. You + must explicitly add providers to this table using + {@link android.test.mock.MockContentResolver#addProvider(String,ContentProvider)}. +

    +

    + With this feature, you can associate a mock content provider with an authority. You can create + an instance of a real provider but use test data in it. You can even set the provider for an + authority to null. In effect, a MockContentResolver object isolates your test + from providers that contain real data. You can control the + function of the provider, and you can prevent your test from affecting real data. +

    +

    Contexts for testing

    +

    + Android provides two Context classes that are useful for testing: +

    +
      +
    • + {@link android.test.IsolatedContext} provides an isolated {@link android.content.Context}, + File, directory, and database operations that use this Context take place in a test area. + Though its functionality is limited, this Context has enough stub code to respond to + system calls. +

      + This class allows you to test an application's data operations without affecting real + data that may be present on the device. +

      +
    • +
    • + {@link android.test.RenamingDelegatingContext} provides a Context in which + most functions are handled by an existing {@link android.content.Context}, but + file and database operations are handled by a {@link android.test.IsolatedContext}. + The isolated part uses a test directory and creates special file and directory names. + You can control the naming yourself, or let the constructor determine it automatically. +

      + This object provides a quick way to set up an isolated area for data operations, + while keeping normal functionality for all other Context operations. +

      +
    • +
    +

    Running Tests

    +

    + Test cases are run by a test runner class that loads the test case class, set ups, + runs, and tears down each test. An Android test runner must also be instrumented, so that + the system utility for starting applications can control how the test package + loads test cases and the application under test. You tell the Android platform + which instrumented test runner to use by setting a value in the test package's manifest file. +

    +

    + {@link android.test.InstrumentationTestRunner} is the primary Android test runner class. It + extends the JUnit test runner framework and is also instrumented. It can run any of the test + case classes provided by Android and supports all possible types of testing. +

    +

    + You specify InstrumentationTestRunner or a subclass in your test package's + manifest file, in the +<instrumentation> + element. Also, InstrumentationTestRunner code resides + in the shared library android.test.runner, which is not normally linked to + Android code. To include it, you must specify it in a +<uses-library> + element. You do not have to set up these elements yourself. Both Eclipse with ADT and the + android command-line tool construct them automatically and add them to your + test package's manifest file. +

    +

    + Note: If you use a test runner other than + InstrumentationTestRunner, you must change the <instrumentation> + element to point to the class you want to use. +

    +

    + To run {@link android.test.InstrumentationTestRunner}, you use internal system classes called by + Android tools. When you run a test in Eclipse with ADT, the classes are called automatically. + When you run a test from the command line, you run these classes with + Android Debug Bridge (adb). +

    +

    + The system classes load and start the test package, kill any processes that + are running an instance of the application under test, and then load a new instance of the + application under test. They then pass control to + {@link android.test.InstrumentationTestRunner}, which runs + each test case class in the test package. You can also control which test cases and + methods are run using settings in Eclipse with ADT, or using flags with the command-line tools. +

    +

    + Neither the system classes nor {@link android.test.InstrumentationTestRunner} run + the application under test. Instead, the test case does this directly. It either calls methods + in the application under test, or it calls its own methods that trigger lifecycle events in + the application under test. The application is under the complete control of the test case, + which allows it to set up the test environment (the test fixture) before running a test. This + is demonstrated in the previous code snippet that tests an + Activity that displays a Spinner widget. +

    +

    + To learn more about running tests, please read the topics + + Testing from Eclipse with ADT or + + Testing from Other IDEs. +

    +

    Seeing Test Results

    +

    + The Android testing framework returns test results back to the tool that started the test. + If you run a test in Eclipse with ADT, the results are displayed in a new JUnit view pane. If + you run a test from the command line, the results are displayed in STDOUT. In + both cases, you see a test summary that displays the name of each test case and method that + was run. You also see all the assertion failures that occurred. These include pointers to the + line in the test code where the failure occurred. Assertion failures also list the expected + value and actual value. +

    +

    + The test results have a format that is specific to the IDE that you are using. The test + results format for Eclipse with ADT is described in + + Testing from Eclipse with ADT. The test results format for tests run from the + command line is described in + + Testing from Other IDEs. +

    +

    monkey and monkeyrunner

    +

    + The SDK provides two tools for functional-level application testing: +

    +
      +
    • +The UI/Application Exerciser Monkey, + usually called "monkey", is a command-line tool that sends pseudo-random streams of + keystrokes, touches, and gestures to a device. You run it with the + Android Debug Bridge (adb) tool. + You use it to stress-test your application and report back errors that are encountered. + You can repeat a stream of events by running the tool each time with the same random + number seed. +
    • +
    • + The monkeyrunner tool + is an API and execution environment for test programs written in Python. The API + includes functions for connecting to a device, installing and uninstalling packages, + taking screenshots, comparing two images, and running a test package against an + application. Using the API, you can write a wide range of large, powerful, and complex + tests. You run programs that use the API with the monkeyrunner command-line + tool. +
    • +
    +

    Working With Package names

    +

    + In the test environment, you work with both Android application package names and + Java package identifiers. Both use the same naming format, but they represent substantially + different entities. You need to know the difference to set up your tests correctly. +

    +

    + An Android package name is a unique system name for a .apk file, set by the + "android:package" attribute of the <manifest> element in the package's + manifest. The Android package name of your test package must be different from the + Android package name of the application under test. By default, Android tools create the + test package name by appending ".test" to the package name of the application under test. +

    +

    + The test package also uses an Android package name to target the application package it + tests. This is set in the "android:targetPackage" attribute of the + <instrumentation> element in the test package's manifest. +

    +

    + A Java package identifier applies to a source file. This package name reflects the directory + path of the source file. It also affects the visibility of classes and members to each other. +

    +

    + Android tools that create test projects set up an Android test package name for you. + From your input, the tools set up the test package name and the target package name for the + application under test. For these tools to work, the application project must already exist. +

    +

    + By default, these tools set the Java package identifier for the test class to be the same + as the Android package identifier. You may want to change this if you want to expose + members in the application under test by giving them package visibility. If you do this, + change only the Java package identifier, not the Android package names, and change only the + test case source files. Do not change the Java package name of the generated + R.java class in your test package, because it will then conflict with the + R.java class in the application under test. Do not change the Android package name + of your test package to be the same as the application it tests, because then their names + will no longer be unique in the system. +

    +

    What to Test

    +

    + The topic What To Test + describes the key functionality you should test in an Android application, and the key + situations that might affect that functionality. +

    +

    + Most unit testing is specific to the Android component you are testing. + The topics Activity Testing, + + Content Provider Testing, and + Service Testing each have a section entitled "What To Test" that lists possible testing + areas. +

    +

    + When possible, you should run these tests on an actual device. If this is not possible, you can + use the Android Emulator with + Android Virtual Devices configured for the hardware, screens, and versions you want to test. +

    +

    Next Steps

    +

    + To learn how to set up and run tests in Eclipse, please refer to +Testing from Eclipse with ADT. + If you're not working in Eclipse, refer to +Testing from Other IDEs. +

    +

    + If you want a step-by-step introduction to Android testing, try the + Activity Testing Tutorial. +

    diff --git a/docs/html/tools/testing/testing_eclipse.jd b/docs/html/tools/testing/testing_eclipse.jd new file mode 100644 index 000000000000..7d3be47ec1da --- /dev/null +++ b/docs/html/tools/testing/testing_eclipse.jd @@ -0,0 +1,535 @@ +page.title=Testing from Eclipse with ADT +parent.title=Testing +parent.link=index.html +@jd:body + +

    + This topic explains how create and run tests of Android applications in Eclipse with ADT. + Before you read this topic, you should read about how to create an Android application with the + basic processes for creating and running applications with ADT, as described in + Managing Projects from +Eclipse + and Building and Running +from Eclipse. + You may also want to read + Testing Fundamentals, + which provides an overview of the Android testing framework. +

    +

    + ADT provides several features that help you set up and manage your testing environment + effectively: +

    +
      +
    • + It lets you quickly create a test project and link it to the application under test. + When it creates the test project, it automatically inserts the necessary + <instrumentation> element in the test package's manifest file. +
    • +
    • + It lets you quickly import the classes of the application under test, so that your + tests can inspect them. +
    • +
    • + It lets you create run configurations for your test package and include in + them flags that are passed to the Android testing framework. +
    • +
    • + It lets you run your test package without leaving Eclipse. ADT builds both the + application under test and the test package automatically, installs them if + necessary to your device or emulator, runs the test package, and displays the + results in a separate window in Eclipse. +
    • +
    +

    + If you are not developing in Eclipse or you want to learn how to create and run tests from the + command line, see + Testing from Other IDEs. +

    +

    Creating a Test Project

    +

    + To set up a test environment for your Android application, you must first create a separate + project that holds the test code. The new project follows the directory structure + used for any Android application. It includes the same types of content and files, such as + source code, resources, a manifest file, and so forth. The test package you + create is connected to the application under test by an + + <instrumentation> element in its manifest file. +

    +

    + The New Android Test Project dialog makes it easy for you to generate a + new test project that has the proper structure, including the + <instrumentation> element in the manifest file. You can use the New + Android Test Project dialog to generate the test project at any time. The dialog appears + just after you create a new Android main application project, but you can also run it to + create a test project for a project that you created previously. +

    +

    + To create a test project in Eclipse with ADT: +

    +
      +
    1. + In Eclipse, select File > New > Other. This opens the Select a + Wizard dialog. +
    2. +
    3. + In the dialog, in the Wizards drop-down list, find the entry for Android, then + click the toggle to the left. Select Android Test Project, then at the + bottom of the dialog click Next. The New Android Test Project + wizard appears. +
    4. +
    5. + Next to Test Project Name, enter a name for the project. You may use any name, + but you may want to associate the name with the project name for the application under test. + One way to do this is to take the application's project name, append the string "Test" to + it, and then use this as the test package project name. +

      + The name becomes part of the suggested project path, but you can change this in the + next step. +

      +
    6. +
    7. + In the Content panel, examine the suggested path to the project. + If Use default location is set, then the wizard will suggest a path that is + a concatenation of the workspace path and the project name you entered. For example, + if your workspace path is /usr/local/workspace and your project name is + MyTestApp, then the wizard will suggest + /usr/local/workspace/MyTestApp. To enter your own + choice for a path, unselect Use default location, then enter or browse to the + path where you want your project. +

      + To learn more about choosing the location of test projects, please read + + Testing Fundamentals. +

      +
    8. +
    9. + In the Test Target panel, set An Existing Android Project, click Browse, then select your + Android application from the list. You now see that the wizard has completed the Test + Target Package, Application Name, and Package Name fields for you (the latter two are in + the Properties panel). +
    10. +
    11. + In the Build Target panel, select the Android SDK platform that the application under test + uses. +
    12. +
    13. + Click Finish to complete the wizard. If Finish is disabled, look for error messages at the + top of the wizard dialog, and then fix any problems. +
    14. +
    +

    Creating a Test Package

    +

    + Once you have created a test project, you populate it with a test package. This package does not + require an Activity, although you can define one if you wish. Although your test package can + combine Activity classes, test case classes, or ordinary classes, your main test case + should extend one of the Android test case classes or JUnit classes, because these provide the + best testing features. +

    +

    + Test packages do not need to have an Android GUI. When you run the package in + Eclipse with ADT, its results appear in the JUnit view. Running tests and seeing the results is + described in more detail in the section Running Tests. +

    + +

    + To create a test package, start with one of Android's test case classes defined in + {@link android.test android.test}. These extend the JUnit + {@link junit.framework.TestCase TestCase} class. The Android test classes for Activity objects + also provide instrumentation for testing an Activity. To learn more about test case + classes, please read the topic + Testing Fundamentals. +

    +

    + Before you create your test package, you choose the Java package identifier you want to use + for your test case classes and the Android package name you want to use. To learn more + about this, please read + + Testing Fundamentals. +

    +

    + To add a test case class to your project: +

    +
      +
    1. + In the Project Explorer tab, open your test project, then open the src + folder. +
    2. +
    3. + Find the Java package identifier set by the projection creation wizard. If you haven't + added classes yet, this node won't have any children, and its icon will not be filled in. + If you want to change the identifier value, right-click the identifier and select + Refactor > Rename, then enter the new name. +
    4. +
    5. + When you are ready, right-click the Java package identifier again and select + New > Class. This displays the New Java Class + dialog, with the Source folder and Package values already set. +
    6. +
    7. + In the Name field, enter a name for the test case class. One way to choose a + class name is to append the string "Test" to the class of the component you are testing. + For example, if you are testing the class MyAppActivity, your test case class + name would be MyAppActivityTest. Leave the modifiers set to public. +
    8. +
    9. + In the Superclass field, enter the name of the Android test case class you + are extending. You can also browse the available classes. +
    10. +
    11. + In Which method stubs would you like to create?, unset all the options, then + click Finish. You will set up the constructor manually. +
    12. +
    13. + Your new class appears in a new Java editor pane. +
    14. +
    +

    + You now have to ensure that the constructor is set up correctly. Create a constructor for your + class that has no arguments; this is required by JUnit. As the first statement in this + constructor, add a call to the base class' constructor. Each base test case class has its + own constructor signature. Refer to the class documentation in the documentation for + {@link android.test} for more information. +

    +

    + To control your test environment, you will want to override the setUp() and + tearDown() methods: +

    +
      +
    • + setUp(): This method is invoked before any of the test methods in the class. + Use it to set up the environment for the test (the test fixture. You can use + setUp() to instantiate a new Intent with the action ACTION_MAIN. + You can then use this intent to start the Activity under test. +
    • +
    • + tearDown(): This method is invoked after all the test methods in the class. Use + it to do garbage collection and to reset the test fixture. +
    • +
    +

    + Another useful convention is to add the method testPreconditions() to your test + class. Use this method to test that the application under test is initialized correctly. If this + test fails, you know that that the initial conditions were in error. When this happens, further + test results are suspect, regardless of whether or not the tests succeeded. +

    +

    + The Resources tab contains an + Activity Testing + tutorial with more information about creating test classes and methods. +

    +

    Running Tests

    + +

    + When you run a test package in Eclipse with ADT, the output appears in the Eclipse JUnit view. + You can run the entire test package or one test case class. To do run tests, Eclipse runs the + adb command for running a test package, and displays the output, so there is no + difference between running tests inside Eclipse and running them from the command line. +

    +

    + As with any other package, to run a test package in Eclipse with ADT you must either attach a + device to your computer or use the Android emulator. If you use the emulator, you must have an + Android Virtual Device (AVD) that uses the same target as the test package. +

    +

    + To run a test in Eclipse, you have two choices:

    +
      +
    • + Run a test just as you run an application, by selecting + Run As... > Android JUnit Test from the project's context menu or + from the main menu's Run item. +
    • +
    • + Create an Eclipse run configuration for your test project. This is useful if you want + multiple test suites, each consisting of selected tests from the project. To run + a test suite, you run the test configuration. +

      + Creating and running test configurations is described in the next section. +

      +
    • +
    +

    + To create and run a test suite using a run configuration: +

    +
      +
    1. + In the Package Explorer, select the test project, then from the main menu, select + Run > Run Configurations.... The Run Configurations dialog appears. +
    2. +
    3. + In the left-hand pane, find the Android JUnit Test entry. In the right-hand pane, click the + Test tab. The Name: text box shows the name of your project. The Test class: dropdown box + shows one of the test classes in your project. +
    4. +
    5. + To run one test class, click Run a single test, then enter your project name in the + Project: text box and the class name in the Test class: text box. +

      + To run all the test classes, click Run all tests in the selected project or package, + then enter the project or package name in the text box. +

      +
    6. +
    7. + Now click the Target tab. +
        +
      • + Optional: If you are using the emulator, click Automatic, then in the Android + Virtual Device (AVD) selection table, select an existing AVD. +
      • +
      • + In the Emulator Launch Parameters pane, set the Android emulator flags you want to + use. These are documented in the topic + + Android Emulator. +
      • +
      +
    8. +
    9. + Click the Common tab. In the Save As pane, click Local to save this run configuration + locally, or click Shared to save it to another project. +
    10. +
    11. + Optional: Add the configuration to the Run toolbar and the Favorites + menu: in the Display in Favorites pane click the checkbox next to Run. +
    12. +
    13. + Optional: To add this configuration to the Debug menu and toolbar, click + the checkbox next to Debug. +
    14. +
    15. + To save your settings, click Close.
      +

      Note: + Although you can run the test immediately by clicking Run, you should save the test + first and then run it by selecting it from the Eclipse standard toolbar. +

      +
    16. +
    17. + On the Eclipse standard toolbar, click the down arrow next to the green Run arrow. This + displays a menu of saved Run and Debug configurations. +
    18. +
    19. + Select the test run configuration you just created. The test starts. +
    20. +
    +

    + The progress of your test appears in the Console view as a series of messages. Each message is + preceded by a timestamp and the .apk filename to which it applies. For example, + this message appears when you run a test to the emulator, and the emulator is not yet started: +

    + +
    +    [yyyy-mm-dd hh:mm:ss - testfile] Waiting for HOME ('android.process.acore') to be launched...
    +
    +

    + In the following description of these messages, devicename is the name of + the device or emulator you are using to run the test, and port is the + port number for the device. The name and port number are in the format used by the + adb devices + command. Also, testfile is the .apk filename of the test + package you are running, and appfile is the filename of the application under test. +

    +
      +
    • + If you are using an emulator and you have not yet started it, then Eclipse + first starts the emulator. When this is complete, you see + the message: +

      + HOME is up on device 'devicename-port' +

      +
    • +
    • + If you have not already installed your test package, then you see + the message: +

      + Uploading testfile onto device 'devicename-port' + +

      +

      + then the message Installing testfile. +

      +

      + and finally the message Success! +

      +
    • +
    +

    + The following lines are an example of this message sequence: +

    + +[2010-07-01 12:44:40 - MyTest] HOME is up on device 'emulator-5554'
    +[2010-07-01 12:44:40 - MyTest] Uploading MyTest.apk onto device 'emulator-5554'
    +[2010-07-01 12:44:40 - MyTest] Installing MyTest.apk...
    +[2010-07-01 12:44:49 - MyTest] Success!
    +
    +
    +
      +
    • + Next, if you have not yet installed the application under test to the device or + emulator, you see the message +

      + Project dependency found, installing: appfile +

      +

      + then the message Uploading appfile onto device + 'devicename-port' +

      +

      + then the message Installing appfile +

      +

      + and finally the message Success! +

      +
    • +
    +

    + The following lines are an example of this message sequence: +

    + +[2010-07-01 12:44:49 - MyTest] Project dependency found, installing: MyApp
    +[2010-07-01 12:44:49 - MyApp] Uploading MyApp.apk onto device 'emulator-5554'
    +[2010-07-01 12:44:49 - MyApp] Installing MyApp.apk...
    +[2010-07-01 12:44:54 - MyApp] Success!
    +
    +
    +
      +
    • + Next, you see the message + Launching instrumentation instrumentation_class on device + devicename-port +

      + instrumentation_class is the fully-qualified class name of the + instrumentation test runner you have specified (usually + {@link android.test.InstrumentationTestRunner}. +

      +
    • +
    • + Next, as {@link android.test.InstrumentationTestRunner} builds a list of tests to run, + you see the message +

      + Collecting test information +

      +

      + followed by +

      +

      + Sending test information to Eclipse +

      +
    • +
    • + Finally, you see the message Running tests, which indicates that your tests + are running. At this point, you should start seeing the test results in the JUnit view. + When the tests are finished, you see the console message Test run complete. + This indicates that your tests are finished. +
    • +
    +

    + The following lines are an example of this message sequence: +

    + +[2010-01-01 12:45:02 - MyTest] Launching instrumentation android.test.InstrumentationTestRunner on device emulator-5554
    +[2010-01-01 12:45:02 - MyTest] Collecting test information
    +[2010-01-01 12:45:02 - MyTest] Sending test information to Eclipse
    +[2010-01-01 12:45:02 - MyTest] Running tests...
    +[2010-01-01 12:45:22 - MyTest] Test run complete
    +
    +
    +

    + The test results appear in the JUnit view. This is divided into an upper summary pane, + and a lower stack trace pane. +

    +

    + The upper pane contains test information. In the pane's header, you see the following + information: +

    +
      +
    • + Total time elapsed for the test package (labeled Finished after x seconds). +
    • +
    • + Number of runs (Runs:) - the number of tests in the entire test class. +
    • +
    • + Number of errors (Errors:) - the number of program errors and exceptions encountered + during the test run. +
    • +
    • + Number of failures (Failures:) - the number of test failures encountered during the test + run. This is the number of assertion failures. A test can fail even if the program does + not encounter an error. +
    • +
    • + A progress bar. The progress bar extends from left to right as the tests run. If all the + tests succeed, the bar remains green. If a test fails, the bar turns from green to red. +
    • +
    +

    + The body of the upper pane contains the details of the test run. For each test case class + that was run, you see a line with the class name. To look at the results for the individual + test methods in that class, you click the left arrow to expand the line. You now see a + line for each test method in the class, and to its right the time it took to run. + If you double-click the method name, Eclipse opens the test class source in an editor view + pane and moves the focus to the first line of the test method. +

    +

    + The results of a successful test are shown in figure 1. +

    + + Messages for a successful test + +

    + Figure 1. Messages for a successful test. +

    +

    + The lower pane is for stack traces. If you highlight a failed test in the upper pane, the + lower pane contains a stack trace for the test. If a line corresponds to a point in your + test code, you can double-click it to display the code in an editor view pane, with the + line highlighted. For a successful test, the lower pane is empty. +

    +

    The results of a failed test are shown in figure 2.

    + + + +

    + Figure 2. Messages for a test failure. +

    diff --git a/docs/html/tools/testing/testing_otheride.jd b/docs/html/tools/testing/testing_otheride.jd new file mode 100644 index 000000000000..0678f52bf29e --- /dev/null +++ b/docs/html/tools/testing/testing_otheride.jd @@ -0,0 +1,690 @@ +page.title=Testing from Other IDEs +parent.title=Testing +parent.link=index.html +@jd:body + + +

    + This document describes how to create and run tests directly from the command line. + You can use the techniques described here if you are developing in an IDE other than Eclipse + or if you prefer to work from the command line. This document assumes that you already know how + to create a Android application in your programming environment. Before you start this + document, you should read the topic + Testing Fundamentals, + which provides an overview of Android testing. +

    +

    + If you are developing in Eclipse with ADT, you can set up and run your tests + directly in Eclipse. For more information, please read + + Testing from Eclipse with ADT. +

    +

    Working with Test Projects

    +

    + You use the android tool to create test projects. + You also use android to convert existing test code into an Android test project, + or to add the run-tests Ant target to an existing Android test project. + These operations are described in more detail in the section + Updating a test project. The run-tests target is described in + Quick build and run with Ant. +

    +

    Creating a test project

    +

    + To create a test project with the android tool, enter: +

    +
    +android create test-project -m <main_path> -n <project_name> -p <test_path>
    +
    +

    + You must supply all the flags. The following table explains them in detail: +

    + + + + + + + + + + + + + + + + + + + + + +
    FlagValueDescription
    -m, --main + Path to the project of the application under test, relative to the test package + directory. + + For example, if the application under test is in source/HelloAndroid, and + you want to create the test project in source/HelloAndroidTest, then the + value of --main should be ../HelloAndroid. +

    + To learn more about choosing the location of test projects, please read + + Testing Fundamentals. +

    +
    -n, --nameName that you want to give the test project. 
    -p, --pathDirectory in which you want to create the new test project. + The android tool creates the test project files and directory structure + in this directory. If the directory does not exist, android creates it. +
    +

    + If the operation is successful, android lists to STDOUT the names of the files + and directories it has created. +

    +

    + This creates a new test project with the appropriate directories and build files. The directory + structure and build file contents are identical to those in a regular Android application + project. They are described in detail in the topic + Managing Projects. +

    +

    + The operation also creates an AndroidManifest.xml file with instrumentation + information. When you run the test, Android uses this information to load the application you + are testing and control it with instrumentation. +

    +

    + For example, suppose you create a project in the directory ~/source/HelloAndroid, +with the package name com.example.helloandroid, + and the activity name HelloAndroid. You can to create the test for this in + ~/source/HelloAndroidTest. To do so, you enter: +

    +
    +$ cd ~/source
    +$ android create test-project -m ../HelloAndroid -n HelloAndroidTest -p HelloAndroidTest
    +
    +

    + This creates a directory called ~/src/HelloAndroidTest. In the new directory you + see the file AndroidManifest.xml. This file contains the following + instrumentation-related elements and attributes: +

    +
      +
    • + <application>: to contain the + <uses-library> element. +
    • +
    • + <uses-library android:name="android.test.runner": + specifies this testing application uses the android.test.runner library. +
    • +
    • + <instrumentation>: contains attributes that control Android + instrumentation. The attributes are: +
        +
      • + android:name="android.test.InstrumentationTestRunner": + {@link android.test.InstrumentationTestRunner} runs test cases. It extends both + JUnit test case runner classes and Android instrumentation classes. +
      • +
      • + android:targetPackage="com.example.helloandroid": specifies + that the tests in HelloAndroidTest should be run against the application with the + Android package name com.example.helloandroid. +
      • +
      • + android:label="Tests for .HelloAndroid": specifies a + user-readable label for the instrumentation class. By default, + the android tool gives it the value "Tests for " plus + the name of the main Activity of the application under test. +
      • +
      +
    • +
    +

    Updating a test project

    +

    + You use the android tool when you need to change the path to the + project of the application under test. If you are changing an existing test project created in + Eclipse with ADT so that you can also build and run it from the command line, you must use the + "create" operation. See the section Creating a test project. +

    +

    + Note: If you change the Android package name of the application under test, + you must manually change the value of the <android:targetPackage> + attribute within the AndroidManifest.xml file of the test package. + Running android update test-project does not do this. +

    +

    + To update a test project with the android tool, enter: +

    +
    android update test-project -m <main_path> -p <test_path>
    + + + + + + + + + + + + + + + + + +
    FlagValueDescription
    -m, --mainThe path to the project of the application under test, relative to the test project + For example, if the application under test is in source/HelloAndroid, and + the test project is in source/HelloAndroidTest, then the value for + --main is ../HelloAndroid. +
    -p, --pathThe of the test project. + For example, if the test project is in source/HelloAndroidTest, then the + value for --path is HelloAndroidTest. +
    +

    + If the operation is successful, android lists to STDOUT the names of the files + and directories it has created. +

    +

    Creating a Test Package

    +

    + Once you have created a test project, you populate it with a test package. + The application does not require an {@link android.app.Activity Activity}, + although you can define one if you wish. Although your test package can + combine Activities, Android test class extensions, JUnit extensions, or + ordinary classes, you should extend one of the Android test classes or JUnit classes, + because these provide the best testing features. +

    +

    + If you run your tests with {@link android.test.InstrumentationTestRunner} + (or a related test runner), then it will run all the methods in each class. You can modify + this behavior by using the {@link junit.framework.TestSuite TestSuite} class. +

    + +

    + To create a test package, start with one of Android's test classes in the Java package + {@link android.test android.test}. These extend the JUnit + {@link junit.framework.TestCase TestCase} class. With a few exceptions, the Android test + classes also provide instrumentation for testing. +

    +

    + For test classes that extend {@link junit.framework.TestCase TestCase}, you probably want to + override the setUp() and tearDown() methods: +

    +
      +
    • + setUp(): This method is invoked before any of the test methods in the class. + Use it to set up the environment for the test. You can use setUp() + to instantiate a new Intent object with the action ACTION_MAIN. + You can then use this intent to start the Activity under test. +

      + Note: If you override this method, call + super.setUp() as the first statement in your code. +

      +
    • +
    • + tearDown(): This method is invoked after all the test methods in the class. Use + it to do garbage collection and re-setting before moving on to the next set of tests. +

      Note: If you override this method, you must call + super.tearDown() as the last statement in your code.

      +
    • +
    +

    + Another useful convention is to add the method testPreConditions() to your test + class. Use this method to test that the application under test is initialized correctly. If this + test fails, you know that that the initial conditions were in error. When this happens, further + test results are suspect, regardless of whether or not the tests succeeded. +

    +

    + To learn more about creating test packages, see the topic Testing Fundamentals, + which provides an overview of Android testing. If you prefer to follow a tutorial, + try the Activity Testing + tutorial, which leads you through the creation of tests for an actual Android application. +

    +

    Running Tests

    +

    + You run tests from the command line, either with Ant or with an + + Android Debug Bridge (adb) shell. +

    +

    Quick build and run with Ant

    +

    + You can use Ant to run all the tests in your test project, using the target + run-tests, which is created automatically when you create a test project with + the android tool. +

    +

    + This target re-builds your main project and test project if necessary, installs the test + application to the current AVD or device, and then runs all the test classes in the test + application. The results are directed to STDOUT. +

    +

    + You can update an existing test project to use this feature. To do this, use the + android tool with the update test-project option. This is described + in the section Updating a test project. +

    +

    Running tests on a device or emulator

    +

    + When you run tests from the command line with + + Android Debug Bridge (adb), you get more options for choosing the tests + to run than with any other method. You can select individual test methods, filter tests + according to their annotation, or specify testing options. Since the test run is controlled + entirely from a command line, you can customize your testing with shell scripts in various ways. +

    +

    + To run a test from the command line, you run adb shell to start a command-line + shell on your device or emulator, and then in the shell run the am instrument + command. You control am and your tests with command-line flags. +

    +

    + As a shortcut, you can start an adb shell, call am instrument, and + specify command-line flags all on one input line. The shell opens on the device or emulator, + runs your tests, produces output, and then returns to the command line on your computer. +

    +

    + To run a test with am instrument: +

    +
      +
    1. + If necessary, rebuild your main application and test package. +
    2. +
    3. + Install your test package and main application Android package files + (.apk files) to your current Android device or emulator
    4. +
    5. + At the command line, enter: +
      +$ adb shell am instrument -w <test_package_name>/<runner_class>
      +
      +

      + where <test_package_name> is the Android package name of your test + application, and <runner_class> is the name of the Android test + runner class you are using. The Android package name is the value of the + package attribute of the manifest element in the manifest file + (AndroidManifest.xml) of your test package. The Android test runner + class is usually {@link android.test.InstrumentationTestRunner}. +

      +

      + Your test results appear in STDOUT. +

      +
    6. +
    +

    + This operation starts an adb shell, then runs am instrument + with the specified parameters. This particular form of the command will run all of the tests + in your test package. You can control this behavior with flags that you pass to + am instrument. These flags are described in the next section. +

    +

    Using the am instrument Command

    +

    + The general syntax of the am instrument command is: +

    +
    +    am instrument [flags] <test_package>/<runner_class>
    +
    +

    + The main input parameters to am instrument are described in the following table: +

    + + + + + + + + + + + + + + + + +
    + Parameter + + Value + + Description +
    + <test_package> + + The Android package name of the test package. + + The value of the package attribute of the manifest + element in the test package's manifest file. +
    + <runner_class> + + The class name of the instrumented test runner you are using. + + This is usually {@link android.test.InstrumentationTestRunner}. +
    +

    + The flags for am instrument are described in the following table: +

    + + + + + + + + + + + + + + + + + + + + + +
    + Flag + + Value + + Description +
    + -w + + (none) + + Forces am instrument to wait until the instrumentation terminates + before terminating itself. The net effect is to keep the shell open until the tests + have finished. This flag is not required, but if you do not use it, you will not + see the results of your tests. +
    + -r + + (none) + + Outputs results in raw format. Use this flag when you want to collect + performance measurements, so that they are not formatted as test results. This flag is + designed for use with the flag -e perf true (documented in the section + Instrument options). +
    + -e + + <test_options> + + Provides testing options as key-value pairs. The + am instrument tool passes these to the specified instrumentation class + via its onCreate() method. You can specify multiple occurrences of + -e <test_options>. The keys and values are described in the + section am instrument options. +

    + The only instrumentation class that uses these key-value pairs is + {@link android.test.InstrumentationTestRunner} (or a subclass). Using them with + any other class has no effect. +

    +
    + +

    am instrument options

    +

    + The am instrument tool passes testing options to + InstrumentationTestRunner or a subclass in the form of key-value pairs, + using the -e flag, with this syntax: +

    +
    +    -e <key> <value>
    +
    +

    + Some keys accept multiple values. You specify multiple values in a comma-separated list. + For example, this invocation of InstrumentationTestRunner provides multiple + values for the package key: +

    +
    +$ adb shell am instrument -w -e package com.android.test.package1,com.android.test.package2 \
    +> com.android.test/android.test.InstrumentationTestRunner
    +
    +

    + The following table describes the key-value pairs and their result. Please review the + Usage Notes following the table. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    KeyValueDescription
    + package + + <Java_package_name> + + The fully-qualified Java package name for one of the packages in the test + application. Any test case class that uses this package name is executed. Notice that + this is not an Android package name; a test package has a single + Android package name but may have several Java packages within it. +
    class<class_name> + The fully-qualified Java class name for one of the test case classes. Only this test + case class is executed. +
    <class_name>#method name + A fully-qualified test case class name, and one of its methods. Only this method is + executed. Note the hash mark (#) between the class name and the method name. +
    functrue + Runs all test classes that extend {@link android.test.InstrumentationTestCase}. +
    unittrue + Runs all test classes that do not extend either + {@link android.test.InstrumentationTestCase} or + {@link android.test.PerformanceTestCase}. +
    size + [small | medium | large] + + Runs a test method annotated by size. The annotations are @SmallTest, + @MediumTest, and @LargeTest. +
    perftrue + Runs all test classes that implement {@link android.test.PerformanceTestCase}. + When you use this option, also specify the -r flag for + am instrument, so that the output is kept in raw format and not + re-formatted as test results. +
    debugtrue + Runs tests in debug mode. +
    logtrue + Loads and logs all specified tests, but does not run them. The test + information appears in STDOUT. Use this to verify combinations of other + filters and test specifications. +
    emmatrue + Runs an EMMA code coverage analysis and writes the output to + /data//coverage.ec on the device. To override the file location, use the + coverageFile key that is described in the following entry. +

    + Note: This option requires an EMMA-instrumented build of the test + application, which you can generate with the coverage target. +

    +
    coverageFile<filename> + Overrides the default location of the EMMA coverage file on the device. Specify this + value as a path and filename in UNIX format. The default filename is described in the + entry for the emma key. +
    +-e Flag Usage Notes +
      +
    • + am instrument invokes + {@link android.test.InstrumentationTestRunner#onCreate(Bundle)} + with a {@link android.os.Bundle} containing the key-value pairs. +
    • +
    • + The package key takes precedence over the class key. If you + specifiy a package, and then separately specify a class within that package, Android + will run all the tests in the package and ignore the class key. +
    • +
    • + The func key and unit key are mutually exclusive. +
    • +
    +

    Usage examples

    +

    +The following sections provide examples of using am instrument to run tests. +They are based on the following structure:

    +
      +
    • + The test package has the Android package name com.android.demo.app.tests +
    • +
    • + There are three test classes: +
        +
      • + UnitTests, which contains the methods + testPermissions and testSaveState. +
      • +
      • + FunctionTests, which contains the methods + testCamera, testXVGA, and testHardKeyboard. +
      • +
      • + IntegrationTests, + which contains the method testActivityProvider. +
      • +
      +
    • +
    • + The test runner is {@link android.test.InstrumentationTestRunner}. +
    • +
    +

    Running the entire test package

    +

    + To run all of the test classes in the test package, enter: +

    +
    +$ adb shell am instrument -w com.android.demo.app.tests/android.test.InstrumentationTestRunner
    +
    +

    Running all tests in a test case class

    +

    + To run all of the tests in the class UnitTests, enter: +

    +
    +$ adb shell am instrument -w  \
    +> -e class com.android.demo.app.tests.UnitTests \
    +> com.android.demo.app.tests/android.test.InstrumentationTestRunner
    +
    +

    + am instrument gets the value of the -e flag, detects the + class keyword, and runs all the methods in the UnitTests class. +

    +

    Selecting a subset of tests

    +

    + To run all of the tests in UnitTests, and the testCamera method in + FunctionTests, enter: +

    +
    +$ adb shell am instrument -w \
    +> -e class com.android.demo.app.tests.UnitTests,com.android.demo.app.tests.FunctionTests#testCamera \
    +> com.android.demo.app.tests/android.test.InstrumentationTestRunner
    +
    +

    + You can find more examples of the command in the documentation for + {@link android.test.InstrumentationTestRunner}. +

    diff --git a/docs/html/tools/testing/what_to_test.jd b/docs/html/tools/testing/what_to_test.jd new file mode 100644 index 000000000000..77ae2114f3e2 --- /dev/null +++ b/docs/html/tools/testing/what_to_test.jd @@ -0,0 +1,86 @@ +page.title=What To Test +parent.title=Testing +parent.link=index.html +@jd:body +

    + As you develop Android applications, knowing what to test is as important as knowing how to + test. This document lists some most common Android-related situations that you should consider + when you test, even at the unit test level. This is not an exhaustive list, and you consult the + documentation for the features that you use for more ideas. The + android-developers Google Groups + site is another resource for information about testing. +

    +

    Ideas for Testing

    +

    + The following sections are organized by behaviors or situations that you should test. Each + section contains a scenario that further illustrates the situation and the test or tests you + should do. +

    +

    Change in orientation

    +

    + For devices that support multiple orientations, Android detects a change in orientation when + the user turns the device so that the display is "landscape" (long edge is horizontal) instead + of "portrait" (long edge is vertical). +

    +

    + When Android detects a change in orientation, its default behavior is to destroy and then + re-start the foreground Activity. You should consider testing the following: +

    +
      +
    • + Is the screen re-drawn correctly? Any custom UI code you have should handle changes in the + orientation. +
    • +
    • + Does the application maintain its state? The Activity should not lose anything that the + user has already entered into the UI. The application should not "forget" its place in the + current transaction. +
    • +
    +

    Change in configuration

    +

    + A situation that is more general than a change in orientation is a change in the device's + configuration, such as a change in the availability of a keyboard or a change in system + language. +

    +

    + A change in configuration also triggers the default behavior of destroying and then restarting + the foreground Activity. Besides testing that the application maintains the UI and its + transaction state, you should also test that the application updates itself to respond + correctly to the new configuration. +

    +

    Battery life

    +

    + Mobile devices primarily run on battery power. A device has finite "battery budget", and when it + is gone, the device is useless until it is recharged. You need to write your application to + minimize battery usage, you need to test its battery performance, and you need to test the + methods that manage battery usage. +

    +

    + Techniques for minimizing battery usage were presented at the 2010 Google I/O conference in the + presentation + + Coding for Life -- Battery Life, That Is. This presentation describes the impact on battery + life of various operations, and the ways you can design your application to minimize these + impacts. When you code your application to reduce battery usage, you also write the + appropriate unit tests. +

    +

    Dependence on external resources

    +

    + If your application depends on network access, SMS, Bluetooth, or GPS, then you should + test what happens when the resource or resources are not available. +

    +

    + For example, if your application uses the network,it can notify the user if access is + unavailable, or disable network-related features, or do both. For GPS, it can switch to + IP-based location awareness. It can also wait for WiFi access before doing large data transfers, + since WiFi transfers maximize battery usage compared to transfers over 3G or EDGE. +

    +

    + You can use the emulator to test network access and bandwidth. To learn more, please see + Network Speed Emulation. + To test GPS, you can use the emulator console and {@link android.location.LocationManager}. To + learn more about the emulator console, please see + + Using the Emulator Console. +

    diff --git a/docs/html/tools/tools_toc.cs b/docs/html/tools/tools_toc.cs new file mode 100644 index 000000000000..27fbd2de74fc --- /dev/null +++ b/docs/html/tools/tools_toc.cs @@ -0,0 +1,214 @@ + + + diff --git a/docs/html/tools/workflow.jd b/docs/html/tools/workflow.jd new file mode 100644 index 000000000000..4eb5adace56b --- /dev/null +++ b/docs/html/tools/workflow.jd @@ -0,0 +1,150 @@ +page.title=Introduction +@jd:body + +

    Developing applications for Android devices is facilitated by a group of tools that are + provided with the SDK. You can access these tools through an Eclipse plugin called ADT (Android + Development Tools) or from the command line. Developing with Eclipse is the preferred method because + it can directly invoke the tools that you need while developing applications.

    + +

    However, you may choose to develop with another IDE or a simple text editor and invoke the + tools on the command line or with scripts. This is a less streamlined way to develop because you + will sometimes have to call command line tools manually, but you will have access to the same + number of features that you would have in Eclipse.

    + +
    + Development process for Android applications +

    + Figure 1. The development process for Android applications. +

    +
    + +

    The basic steps for developing applications (with or without Eclipse) are shown in figure 1. The +development steps encompass four development phases, which include:

    + +
      +
    • Setup +

      During this phase you install and set up your development environment. You also create + Android Virtual Devices (AVDs) and connect hardware devices on which you can install your + applications.

      +

      See Managing Virtual Devices + and Using Hardware Devices for more + information. +

    • +
    • Development +

      During this phase you set up and develop your Android project, which contains all of the + source code and resource files for your application. For more informations, see + Create an Android project.

      +
    • +
    • Debugging and Testing +

      During this phase you build your project into a debuggable .apk package that you + can install and run on the emulator or an Android-powered device. If you are using Eclipse, + builds are generated each time you project is saved. If you're using another IDE, + you can build your project using Ant and install it on a device using + adb. For more information, see + Build and run your application.

      +

      Next, you debug your application using a JDWP-compliant debugger along with the debugging + and logging tools that are provided with the Android SDK. Eclipse already comes packaged with + a compatible debugger. For more information see, + Debug your application with the + SDK debugging and logging tools.

      +

      Last, you test your application using various Android SDK testing tools. For more + information, see Test your application + with the Testing and Instrumentation framework.

      +
    • +
    • Publishing +

      During this phase you configure and build your application for release and distribute your + application to users. For more information, see + Publishing Overview.

      +
    • +
    + +

    Essential command line tools

    + +

    When developing in IDEs or editors other than Eclipse, be familiar with + all of the tools below, because you will have to run them from the command line.

    + +
    +
    android
    + +
    Create and update Android projects and create, move, and delete AVDs.
    + +
    Android Emulator
    + +
    Run your Android applications on an emulated Android platform.
    + +
    Android Debug Bridge
    + +
    Interface with your emulator or connected device (install apps, shell the device, issue + commands, etc.).
    +
    + +

    In addition to the above tools that are included with the SDK, you need the following open + source and third-party tools:

    + +
    +
    Ant
    + +
    To compile and build your Android project into an installable .apk file.
    + +
    Keytool
    + +
    To generate a keystore and private key, used to sign your .apk file. Keytool is part of the + JDK.
    + +
    Jarsigner (or similar signing tool)
    + +
    To sign your .apk file with a private key generated by Keytool. Jarsigner is part of the + JDK.
    +
    + +

    If you are using Eclipse and ADT, tools such as adb and android + are automatically called by Eclipse and ADT so you don't have to manually invoke these tools. + You need to be familiar with adb, however, because certain functions are not +accessible from + Eclipse, such as the adb shell commands. You might also need to call Keytool and +Jarsigner to + sign your applications, but you can set up Eclipse to do this automatically as well.

    + +

    For more information on the tools provided with the Android SDK, see the + Tools section of the documentation.

    + +

    Other Third-Party Development Tools

    +

    + The tools described in this section are not developed by the Android SDK team. The Android Dev Guide + does not provide documentation for these tools. Please refer to the linked documents in each + section for documentation. +

    +

    Developing in IntelliJ IDEA

    +
    +The IntelliJ graphical user interface +
    +

    + IntelliJ IDEA is a powerful Java IDE from JetBrains that provides + full-cycle Android development support in both the free Community + Edition and the Ultimate edition. +

    +

    + The IDE ensures compatibility with the latest Android SDK and offers a + smart code editor with completion, quick navigation between code and + resources, a graphical debugger, unit testing support using Android + Testing Framework, and the ability to run applications in either the + emulator or a USB-connected device. +

    +

    + Links: +

    + + diff --git a/docs/html/tools/workflow/app-signing.jd b/docs/html/tools/workflow/app-signing.jd new file mode 100644 index 000000000000..ac45242516b5 --- /dev/null +++ b/docs/html/tools/workflow/app-signing.jd @@ -0,0 +1,618 @@ +page.title=Signing Your Applications +@jd:body + +
    +
    + +

    Quickview

    + +
      +
    • All Android apps must be signed
    • +
    • You can sign with a self-signed key
    • +
    • How you sign your apps is critical — read this document carefully
    • +
    • Determine your signing strategy early in the development process
    • +
    + +

    In this document

    + +
      +
    1. Signing Process
    2. +
    3. Signing Strategies
    4. +
    5. Basic Setup for Signing
    6. +
    7. Signing in Debug Mode
    8. +
    9. Signing Release Mode +
        +
      1. Obtain a suitable private key
      2. +
      3. Compile the application in release mode
      4. +
      5. Sign your application with your private key
      6. +
      7. Align the final APK package
      8. +
      9. Compile and sign with Eclipse ADT
      10. +
      +
    10. +
    11. Securing Your Private Key
    12. + +
    + +

    See also

    + +
      +
    1. Versioning Your Applications
    2. +
    3. Preparing to Publish
    4. +
    + +
    +
    + +

    The Android system requires that all installed applications be digitally signed with a +certificate whose private key is held by the application's developer. The Android system uses the +certificate as a means of identifying the author of an application and establishing trust +relationships between applications. The certificate is not used to control which applications the +user can install. The certificate does not need to be signed by a certificate authority: it is +perfectly allowable, and typical, for Android applications to use self-signed certificates.

    + +

    The important points to understand about signing Android applications are:

    + +
      +
    • All applications must be signed. The system will not install an application +on an emulator or a device if it is not signed.
    • +
    • To test and debug your application, the build tools sign your application with a special debug + key that is created by the Android SDK build tools.
    • +
    • When you are ready to release your application for end-users, you must sign it with a suitable + private key. You cannot publish an application that is signed with the debug key generated + by the SDK tools.
    • +
    • You can use self-signed certificates to sign your applications. No certificate authority is + needed.
    • +
    • The system tests a signer certificate's expiration date only at install time. If an +application's signer certificate expires after the application is installed, the application +will continue to function normally.
    • +
    • You can use standard tools — Keytool and Jarsigner — to generate keys and +sign your application {@code .apk} files.
    • +
    • After you sign your application for release, we recommend that you use the + zipalign tool to optimize the final APK package.
    • +
    + +

    The Android system will not install or run an application that is not signed appropriately. This +applies wherever the Android system is run, whether on an actual device or on the emulator. +For this reason, you must set up signing for your application before you can +run it or debug it on an emulator or device.

    + +

    Signing Process

    + +

    The Android build process signs your application differently depending on which build mode you +use to build your application. There are two build modes: debug mode and release +mode. You use debug mode when you are developing and testing your application. You use +release mode when you want to build a release version of your application that you can +distribute directly to users or publish on an application marketplace such as Google Play.

    + +

    When you build in debug mode the Android SDK build tools use the Keytool utility +(included in the JDK) to create a debug key. Because the SDK build tools created the debug key, +they know the debug key's alias and password. Each time you compile your application in debug mode, +the build tools use the debug key along with the Jarsigner utility (also included in the JDK) to +sign your application's .apk file. Because the alias and password are known to the SDK +build tools, the tools don't need to prompt you for the debug key's alias and password each time +you compile.

    + +

    When you build in release mode you use your own private key to sign your application. If +you don't have a private key, you can use the Keytool utility to create one for you. When you +compile your application in release mode, the build tools use your private key along with the +Jarsigner utility to sign your application's .apk file. Because the certificate and +private key you use are your own, you will have to provide the password for the keystore and key +alias.

    + +

    The debug signing process happens automatically when you run or debug your application using +Eclipse with the ADT plugin. Debug signing also happens automatically when you use the Ant build +script with the debug option. You can automate the release signing process by using the +Eclipse Export Wizard or by modifying the Ant build script and building with the +release option.

    + +

    Signing Strategies

    + +

    Some aspects of application signing may affect how you approach the development +of your application, especially if you are planning to release multiple +applications.

    + +

    In general, the recommended strategy for all developers is to sign +all of your applications with the same certificate, throughout the expected +lifespan of your applications. There are several reasons why you should do so:

    + +
      +
    • Application upgrade – As you release updates to your application, you +will want to continue to sign the updates with the same certificate or set of +certificates, if you want users to upgrade seamlessly to the new version. When +the system is installing an update to an application, it compares the +certificate(s) in the new version with those in the existing version. If the +certificates match exactly, including both the certificate data and order, then +the system allows the update. If you sign the new version without using matching +certificates, you will also need to assign a different package name to the +application — in this case, the user installs the new version as a +completely new application.
    • + +
    • Application modularity – The Android system allows applications that +are signed by the same certificate to run in the same process, if the +applications so requests, so that the system treats them as a single application. +In this way you can deploy your application in modules, and users can update +each of the modules independently if needed.
    • + +
    • Code/data sharing through permissions – The Android system provides +signature-based permissions enforcement, so that an application can expose +functionality to another application that is signed with a specified +certificate. By signing multiple applications with the same certificate and +using signature-based permissions checks, your applications can share code and +data in a secure manner.
    • + +
    + +

    Another important consideration in determining your signing strategy is +how to set the validity period of the key that you will use to sign your +applications.

    + +
      +
    • If you plan to support upgrades for a single application, you should ensure +that your key has a validity period that exceeds the expected lifespan of +that application. A validity period of 25 years or more is recommended. +When your key's validity period expires, users will no longer be +able to seamlessly upgrade to new versions of your application.
    • + +
    • If you will sign multiple distinct applications with the same key, +you should ensure that your key's validity period exceeds the expected +lifespan of all versions of all of the applications, including +dependent applications that may be added to the suite in the future.
    • + +
    • If you plan to publish your application(s) on Google Play, the +key you use to sign the application(s) must have a validity period +ending after 22 October 2033. Google Play enforces this requirement +to ensure that users can seamlessly upgrade applications when +new versions are available.
    • +
    + +

    As you design your application, keep these points in mind and make sure to +use a suitable certificate to sign your applications.

    + +

    Basic Setup for Signing

    + +

    Before you begin, make sure that the Keytool utility and Jarsigner utility are available to +the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell +the SDK build tools how to find these utilities by setting your JAVA_HOME environment +variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and +Jarsigner to your PATH variable.

    + +

    If you are developing on a version of Linux that originally came with GNU Compiler for +Java, make sure that the system is using the JDK version of Keytool, rather than the gcj +version. If Keytool is already in your PATH, it might be pointing to a symlink at +/usr/bin/keytool. In this case, check the symlink target to be sure it points +to the Keytool in the JDK.

    + +

    Signing in Debug Mode

    + +

    The Android build tools provide a debug signing mode that makes it easier for you +to develop and debug your application, while still meeting the Android system +requirement for signing your APK. +When using debug mode to build your app, the SDK tools invoke Keytool to automatically create +a debug keystore and key. This debug key is then used to automatically sign the APK, so +you do not need to sign the package with your own key.

    + +

    The SDK tools create the debug keystore/key with predetermined names/passwords:

    +
      +
    • Keystore name: "debug.keystore"
    • +
    • Keystore password: "android"
    • +
    • Key alias: "androiddebugkey"
    • +
    • Key password: "android"
    • +
    • CN: "CN=Android Debug,O=Android,C=US"
    • +
    + +

    If necessary, you can change the location/name of the debug keystore/key or +supply a custom debug keystore/key to use. However, any custom debug +keystore/key must use the same keystore/key names and passwords as the default +debug key (as described above). (To do so in Eclipse/ADT, go to +Windows > Preferences > +Android > Build.)

    + +

    Caution: You cannot release your application +to the public when signed with the debug certificate.

    + +

    Eclipse Users

    + +

    If you are developing in Eclipse/ADT (and have set up Keytool and Jarsigner as described above in +Basic Setup for Signing), +signing in debug mode is enabled by default. When you run or debug your +application, ADT signs the {@code .apk} file with the debug certificate, runs {@code zipalign} on +the package, then installs it on +the selected emulator or connected device. No specific action on your part is needed, +provided ADT has access to Keytool.

    + +

    Ant Users

    + +

    If you are using Ant to build your {@code .apk} file, debug signing mode +is enabled by using the debug option with the ant command +(assuming that you are using a build.xml file generated by the +android tool). When you run ant debug to +compile your app, the build script generates a keystore/key and signs the APK for you. +The script then also aligns the APK with the zipalign tool. +No other action on your part is needed. Read +Building and Running Apps +on the Command Line for more information.

    + + +

    Expiry of the Debug Certificate

    + +

    The self-signed certificate used to sign your application in debug mode (the default on +Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.

    + +

    When the certificate expires, you will get a build error. On Ant builds, the error +looks like this:

    + +
    debug:
    +[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
    +[exec] Debug Certificate expired on 8/4/08 3:43 PM
    + +

    In Eclipse/ADT, you will see a similar error in the Android console.

    + +

    To fix this problem, simply delete the debug.keystore file. +The default storage location for AVDs is in ~/.android/ on OS X and Linux, +in C:\Documents and Settings\<user>\.android\ on Windows XP, and in +C:\Users\<user>\.android\ on Windows Vista and Windows 7.

    + + +

    The next time you build, the build tools will regenerate a new keystore and debug key.

    + +

    Note that, if your development machine is using a non-Gregorian locale, the build +tools may erroneously generate an already-expired debug certificate, so that you get an +error when trying to compile your application. For workaround information, see the +troubleshooting topic +I can't compile my app because the build tools generated an expired debug +certificate.

    + + +

    Signing in Release Mode

    + +

    When your application is ready for release to other users, you must:

    +
      +
    1. Obtain a suitable private key
    2. +
    3. Compile the application in release mode
    4. +
    5. Sign your application with your private key
    6. +
    7. Align the final APK package
    8. +
    + +

    If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard +to perform the compile, sign, and align procedures. The Export Wizard even allows you to +generate a new keystore and private key in the process. So if you use Eclipse, you can +skip to Compile and sign with Eclipse ADT.

    + + + +

    1. Obtain a suitable private key

    + +

    In preparation for signing your application, you must first ensure that +you have a suitable private key with which to sign. A suitable private +key is one that:

    + +
      +
    • Is in your possession
    • +
    • Represents the personal, corporate, or organizational entity to be identified +with the application
    • +
    • Has a validity period that exceeds the expected lifespan of the application +or application suite. A validity period of more than 25 years is recommended. +

      If you plan to publish your application(s) on Google Play, note that a +validity period ending after 22 October 2033 is a requirement. You can not upload an +application if it is signed with a key whose validity expires before that date. +

    • +
    • Is not the debug key generated by the Android SDK tools.
    • +
    + +

    The key may be self-signed. If you do not have a suitable key, you must +generate one using Keytool. Make sure that you have Keytool available, as described +in Basic Setup.

    + +

    To generate a self-signed key with Keytool, use the keytool +command and pass any of the options listed below (and any others, as +needed).

    + +

    Warning: Keep your private key secure. +Before you run Keytool, make sure to read +Securing Your Private Key for a discussion of how to keep +your key secure and why doing so is critically important to you and to users. In +particular, when you are generating your key, you should select strong passwords +for both the keystore and key.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Keytool OptionDescription
    -genkeyGenerate a key pair (public and private +keys)
    -vEnable verbose output.
    -alias <alias_name>An alias for the key. Only +the first 8 characters of the alias are used.
    -keyalg <alg>The encryption algorithm to use +when generating the key. Both DSA and RSA are supported.
    -keysize <size>The size of each generated key +(bits). If not supplied, Keytool uses a default key size of 1024 bits. In +general, we recommend using a key size of 2048 bits or higher.
    -dname <name>

    A Distinguished Name that describes +who created the key. The value is used as the issuer and subject fields in the +self-signed certificate.

    Note that you do not need to specify this option +in the command line. If not supplied, Jarsigner prompts you to enter each +of the Distinguished Name fields (CN, OU, and so on).

    -keypass <password>

    The password for the +key.

    As a security precaution, do not include this option in your command +line. If not supplied, Keytool prompts you to enter the password. In this way, +your password is not stored in your shell history.

    -validity <valdays>

    The validity period for the +key, in days.

    Note: A value of 10000 or greater is recommended.

    -keystore <keystore-name>.keystoreA name +for the keystore containing the private key.
    -storepass <password>

    A password for the +keystore.

    As a security precaution, do not include this option in your +command line. If not supplied, Keytool prompts you to enter the password. In +this way, your password is not stored in your shell history.

    + +

    Here's an example of a Keytool command that generates a private key:

    + +
    $ keytool -genkey -v -keystore my-release-key.keystore
    +-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
    + +

    Running the example command above, Keytool prompts you to provide +passwords for the keystore and key, and to provide the Distinguished +Name fields for your key. It then generates the keystore as a file called +my-release-key.keystore. The keystore and key are +protected by the passwords you entered. The keystore contains +a single key, valid for 10000 days. The alias is a name that you — +will use later, to refer to this keystore when signing your application.

    + +

    For more information about Keytool, see the documentation at + +http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

    + + + +

    2. Compile the application in release mode

    + +

    In order to release your application to users, you must compile it in release mode. +In release mode, the compiled application is not signed by default and you will need +to sign it with your private key.

    + +

    Caution: +You can not release your application unsigned, or signed with the debug key.

    + +

    With Eclipse

    + +

    To export an unsigned APK from Eclipse, right-click the project in the Package +Explorer and select Android Tools > Export Unsigned Application +Package. Then specify the file location for the unsigned APK. +(Alternatively, open your AndroidManifest.xml file in Eclipse, select +the Manifest tab, and click Export an unsigned APK.)

    + +

    Note that you can combine the compiling and signing steps with the Export Wizard. See +Compiling and signing with Eclipse ADT.

    + +

    With Ant

    + +

    If you are using Ant, you can enable release mode by using the release option +with the ant command. For example, if you are running Ant from the +directory containing your {@code build.xml} file, the command would look like this:

    + +
    $ ant release
    + +

    By default, the build script compiles the application APK without signing it. The output file +in your project {@code bin/} will be <your_project_name>-unsigned.apk. +Because the application APK is still unsigned, you must manually sign it with your private +key and then align it using {@code zipalign}.

    + +

    However, the Ant build script can also perform the signing +and aligning for you, if you have provided the path to your keystore and the name of +your key alias in the project's {@code ant.properties} file. With this information provided, +the build script will prompt you for your keystore and alias password when you perform +ant release, it will sign the package and then align it. The final output +file in {@code bin/} will instead be +<your_project_name>-release.apk. With these steps +automated for you, you're able to skip the manual procedures below (steps 3 and 4). +To learn how to specify your keystore and alias in the {@code ant.properties} file, +see +Building and Running Apps on the Command Line.

    + + + +

    3. Sign your application with your private key

    + +

    When you have an application package that is ready to be signed, you can do sign it +using the Jarsigner tool. Make sure that you have Jarsigner available on your +machine, as described in Basic Setup. Also, make sure that +the keystore containing your private key is available.

    + +

    To sign your application, you run Jarsigner, referencing both the +application's APK and the keystore containing the private key with which to +sign the APK. The table below shows the options you could use.

    + + + + + + + + + + + + + + + + + + + + + + + + +
    Jarsigner OptionDescription
    -keystore <keystore-name>.keystoreThe name of +the keystore containing your private key.
    -verboseEnable verbose output.
    -sigalgThe name of the signature algorithim to use in signing the APK. +Use the value {@code MD5withRSA}.
    -digestalgThe message digest algorithim to use in processing the entries +of an APK. Use the value {@code SHA1}.
    -storepass <password>

    The password for the +keystore.

    As a security precaution, do not include this option +in your command line unless you are working at a secure computer. +If not supplied, Jarsigner prompts you to enter the password. In this +way, your password is not stored in your shell history.

    -keypass <password>

    The password for the private +key.

    As a security precaution, do not include this option +in your command line unless you are working at a secure computer. +If not supplied, Jarsigner prompts you to enter the password. In this +way, your password is not stored in your shell history.

    + +

    Here's how you would use Jarsigner to sign an application package called +my_application.apk, using the example keystore created above. +

    + +
    $ jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore my-release-key.keystore
    +my_application.apk alias_name
    + +

    Running the example command above, Jarsigner prompts you to provide +passwords for the keystore and key. It then modifies the APK +in-place, meaning the APK is now signed. Note that you can sign an +APK multiple times with different keys.

    + +

    Caution: As of JDK 7, the default signing algorithim has +changed, requiring you to specify the signature and digest algorithims ({@code -sigalg} and {@code +-digestalg}) when you sign an APK.

    + +

    To verify that your APK is signed, you can use a command like this:

    + +
    $ jarsigner -verify my_signed.apk
    + +

    If the APK is signed properly, Jarsigner prints "jar verified". +If you want more details, you can try one of these commands:

    + +
    $ jarsigner -verify -verbose my_application.apk
    + +

    or

    + +
    $ jarsigner -verify -verbose -certs my_application.apk
    + +

    The command above, with the -certs option added, will show you the +"CN=" line that describes who created the key.

    + +

    Note: If you see "CN=Android Debug", this means the APK was +signed with the debug key generated by the Android SDK. If you intend to release +your application, you must sign it with your private key instead of the debug +key.

    + +

    For more information about Jarsigner, see the documentation at + +http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jarsigner.html

    + + +

    4. Align the final APK package

    + +

    Once you have signed the APK with your private key, run zipalign on the file. +This tool ensures that all uncompressed data starts with a particular byte alignment, +relative to the start of the file. Ensuring alignment at 4-byte boundaries provides +a performance optimization when installed on a device. When aligned, the Android +system is able to read files with {@code mmap()}, even if +they contain binary data with alignment restrictions, rather than copying all +of the data from the package. The benefit is a reduction in the amount of +RAM consumed by the running application.

    + +

    The zipalign tool is provided with the Android SDK, inside the +tools/ directory. To align your signed APK, execute:

    + +
    $ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
    + +

    The {@code -v} flag turns on verbose output (optional). {@code 4} is the +byte-alignment (don't use anything other than 4). The first file argument is +your signed {@code .apk} file (the input) and the second file is the destination {@code .apk} file +(the output). If you're overriding an existing APK, add the {@code -f} flag.

    + +

    Caution: Your input APK must be signed with your +private key before you optimize the package with {@code zipalign}. +If you sign it after using {@code zipalign}, it will undo the alignment.

    + +

    For more information, read about the +zipalign tool. + + +

    Compile and sign with Eclipse ADT

    + +

    If you are using Eclipse with the ADT plugin, you can use the Export Wizard to +export a signed APK (and even create a new keystore, +if necessary). The Export Wizard performs all the interaction with +the Keytool and Jarsigner for you, which allows you to sign the package using a GUI +instead of performing the manual procedures to compile, sign, +and align, as discussed above. Once the wizard has compiled and signed your package, +it will also perfom package alignment with {@code zipalign}. +Because the Export Wizard uses both Keytool and Jarsigner, you should +ensure that they are accessible on your computer, as described above +in the Basic Setup for Signing.

    + +

    To create a signed and aligned APK in Eclipse:

    + +
      +
    1. Select the project in the Package +Explorer and select File > Export.
    2. +
    3. Open the Android folder, select Export Android Application, + and click Next. +

      The Export Android Application wizard now starts, which will + guide you through the process of signing your application, + including steps for selecting the private key with which to sign the APK + (or creating a new keystore and private key).

      +
    4. Complete the Export Wizard and your application will be compiled, + signed, aligned, and ready for distribution.
    5. +
    + + + +

    Securing Your Private Key

    + +

    Maintaining the security of your private key is of critical importance, both +to you and to the user. If you allow someone to use your key, or if you leave +your keystore and passwords in an unsecured location such that a third-party +could find and use them, your authoring identity and the trust of the user +are compromised.

    + +

    If a third party should manage to take your key without your knowledge or +permission, that person could sign and distribute applications that maliciously +replace your authentic applications or corrupt them. Such a person could also +sign and distribute applications under your identity that attack other +applications or the system itself, or corrupt or steal user data.

    + +

    Your reputation as a developer entity depends on your securing your private +key properly, at all times, until the key is expired. Here are some tips for +keeping your key secure:

    + +
      +
    • Select strong passwords for the keystore and key.
    • +
    • When you generate your key with Keytool, do not supply the +-storepass and -keypass options at the command line. +If you do so, your passwords will be available in your shell history, +which any user on your computer could access.
    • +
    • Similarly, when signing your applications with Jarsigner, +do not supply the -storepass and -keypass +options at the command line.
    • +
    • Do not give or lend anyone your private key, and do not let unauthorized +persons know your keystore and key passwords.
    • +
    + +

    In general, if you follow common-sense precautions when generating, using, +and storing your key, it will remain secure.

    \ No newline at end of file diff --git a/docs/html/tools/workflow/index.jd b/docs/html/tools/workflow/index.jd new file mode 100644 index 000000000000..5ae06e69faa3 --- /dev/null +++ b/docs/html/tools/workflow/index.jd @@ -0,0 +1,150 @@ +page.title=Introduction +@jd:body + +

    To develop apps for Android devices, you use a set of tools that are included in the Android SDK. +Once you've downloaded and installed the SDK, you can access these tools right from your Eclipse IDE, +through the ADT plugin, or from the command line. Developing with Eclipse is the preferred method because +it can directly invoke the tools that you need while developing applications.

    + +

    However, you may choose to develop with another IDE or a simple text editor and invoke the + tools on the command line or with scripts. This is a less streamlined way to develop because you + will sometimes have to call command line tools manually, but you will have access to the same + number of features that you would have in Eclipse.

    + +
    + Development process for Android applications +

    + Figure 1. The development process for Android applications. +

    +
    + +

    The basic steps for developing applications (with or without Eclipse) are shown in figure 1. The +development steps encompass four development phases, which include:

    + +
      +
    • Setup +

      During this phase you install and set up your development environment. You also create + Android Virtual Devices (AVDs) and connect hardware devices on which you can install your + applications.

      +

      See Managing Virtual Devices + and Using Hardware Devices for more + information. +

    • +
    • Development +

      During this phase you set up and develop your Android project, which contains all of the + source code and resource files for your application. For more informations, see + Create an Android project.

      +
    • +
    • Debugging and Testing +

      During this phase you build your project into a debuggable .apk package that you + can install and run on the emulator or an Android-powered device. If you are using Eclipse, + builds are generated each time you project is saved. If you're using another IDE, + you can build your project using Ant and install it on a device using + adb. For more information, see + Build and run your application.

      +

      Next, you debug your application using a JDWP-compliant debugger along with the debugging + and logging tools that are provided with the Android SDK. Eclipse already comes packaged with + a compatible debugger. For more information see, + Debug your application with the + SDK debugging and logging tools.

      +

      Last, you test your application using various Android SDK testing tools. For more + information, see Test your application + with the Testing and Instrumentation framework.

      +
    • +
    • Publishing +

      During this phase you configure and build your application for release and distribute your + application to users. For more information, see + Publishing Overview.

      +
    • +
    + +

    Essential command line tools

    + +

    When developing in IDEs or editors other than Eclipse, be familiar with + all of the tools below, because you will have to run them from the command line.

    + +
    +
    android
    + +
    Create and update Android projects and create, move, and delete AVDs.
    + +
    Android Emulator
    + +
    Run your Android applications on an emulated Android platform.
    + +
    Android Debug Bridge
    + +
    Interface with your emulator or connected device (install apps, shell the device, issue + commands, etc.).
    +
    + +

    In addition to the above tools that are included with the SDK, you need the following open + source and third-party tools:

    + +
    +
    Ant
    + +
    To compile and build your Android project into an installable .apk file.
    + +
    Keytool
    + +
    To generate a keystore and private key, used to sign your .apk file. Keytool is part of the + JDK.
    + +
    Jarsigner (or similar signing tool)
    + +
    To sign your .apk file with a private key generated by Keytool. Jarsigner is part of the + JDK.
    +
    + +

    If you are using Eclipse and ADT, tools such as adb and android + are automatically called by Eclipse and ADT so you don't have to manually invoke these tools. + You need to be familiar with adb, however, because certain functions are not +accessible from + Eclipse, such as the adb shell commands. You might also need to call Keytool and +Jarsigner to + sign your applications, but you can set up Eclipse to do this automatically as well.

    + +

    For more information on the tools provided with the Android SDK, see the + Tools section of the documentation.

    + +

    Other Third-Party Development Tools

    +

    + The tools described in this section are not developed by the Android SDK team. The Android Dev Guide + does not provide documentation for these tools. Please refer to the linked documents in each + section for documentation. +

    +

    Developing in IntelliJ IDEA

    +
    +The IntelliJ graphical user interface +
    +

    + IntelliJ IDEA is a powerful Java IDE from JetBrains that provides + full-cycle Android development support in both the free Community + Edition and the Ultimate edition. +

    +

    + The IDE ensures compatibility with the latest Android SDK and offers a + smart code editor with completion, quick navigation between code and + resources, a graphical debugger, unit testing support using Android + Testing Framework, and the ability to run applications in either the + emulator or a USB-connected device. +

    +

    + Links: +

    + + diff --git a/docs/html/tools/workflow/publishing/app-signing.jd b/docs/html/tools/workflow/publishing/app-signing.jd new file mode 100644 index 000000000000..ac45242516b5 --- /dev/null +++ b/docs/html/tools/workflow/publishing/app-signing.jd @@ -0,0 +1,618 @@ +page.title=Signing Your Applications +@jd:body + +
    +
    + +

    Quickview

    + +
      +
    • All Android apps must be signed
    • +
    • You can sign with a self-signed key
    • +
    • How you sign your apps is critical — read this document carefully
    • +
    • Determine your signing strategy early in the development process
    • +
    + +

    In this document

    + +
      +
    1. Signing Process
    2. +
    3. Signing Strategies
    4. +
    5. Basic Setup for Signing
    6. +
    7. Signing in Debug Mode
    8. +
    9. Signing Release Mode +
        +
      1. Obtain a suitable private key
      2. +
      3. Compile the application in release mode
      4. +
      5. Sign your application with your private key
      6. +
      7. Align the final APK package
      8. +
      9. Compile and sign with Eclipse ADT
      10. +
      +
    10. +
    11. Securing Your Private Key
    12. + +
    + +

    See also

    + +
      +
    1. Versioning Your Applications
    2. +
    3. Preparing to Publish
    4. +
    + +
    +
    + +

    The Android system requires that all installed applications be digitally signed with a +certificate whose private key is held by the application's developer. The Android system uses the +certificate as a means of identifying the author of an application and establishing trust +relationships between applications. The certificate is not used to control which applications the +user can install. The certificate does not need to be signed by a certificate authority: it is +perfectly allowable, and typical, for Android applications to use self-signed certificates.

    + +

    The important points to understand about signing Android applications are:

    + +
      +
    • All applications must be signed. The system will not install an application +on an emulator or a device if it is not signed.
    • +
    • To test and debug your application, the build tools sign your application with a special debug + key that is created by the Android SDK build tools.
    • +
    • When you are ready to release your application for end-users, you must sign it with a suitable + private key. You cannot publish an application that is signed with the debug key generated + by the SDK tools.
    • +
    • You can use self-signed certificates to sign your applications. No certificate authority is + needed.
    • +
    • The system tests a signer certificate's expiration date only at install time. If an +application's signer certificate expires after the application is installed, the application +will continue to function normally.
    • +
    • You can use standard tools — Keytool and Jarsigner — to generate keys and +sign your application {@code .apk} files.
    • +
    • After you sign your application for release, we recommend that you use the + zipalign tool to optimize the final APK package.
    • +
    + +

    The Android system will not install or run an application that is not signed appropriately. This +applies wherever the Android system is run, whether on an actual device or on the emulator. +For this reason, you must set up signing for your application before you can +run it or debug it on an emulator or device.

    + +

    Signing Process

    + +

    The Android build process signs your application differently depending on which build mode you +use to build your application. There are two build modes: debug mode and release +mode. You use debug mode when you are developing and testing your application. You use +release mode when you want to build a release version of your application that you can +distribute directly to users or publish on an application marketplace such as Google Play.

    + +

    When you build in debug mode the Android SDK build tools use the Keytool utility +(included in the JDK) to create a debug key. Because the SDK build tools created the debug key, +they know the debug key's alias and password. Each time you compile your application in debug mode, +the build tools use the debug key along with the Jarsigner utility (also included in the JDK) to +sign your application's .apk file. Because the alias and password are known to the SDK +build tools, the tools don't need to prompt you for the debug key's alias and password each time +you compile.

    + +

    When you build in release mode you use your own private key to sign your application. If +you don't have a private key, you can use the Keytool utility to create one for you. When you +compile your application in release mode, the build tools use your private key along with the +Jarsigner utility to sign your application's .apk file. Because the certificate and +private key you use are your own, you will have to provide the password for the keystore and key +alias.

    + +

    The debug signing process happens automatically when you run or debug your application using +Eclipse with the ADT plugin. Debug signing also happens automatically when you use the Ant build +script with the debug option. You can automate the release signing process by using the +Eclipse Export Wizard or by modifying the Ant build script and building with the +release option.

    + +

    Signing Strategies

    + +

    Some aspects of application signing may affect how you approach the development +of your application, especially if you are planning to release multiple +applications.

    + +

    In general, the recommended strategy for all developers is to sign +all of your applications with the same certificate, throughout the expected +lifespan of your applications. There are several reasons why you should do so:

    + +
      +
    • Application upgrade – As you release updates to your application, you +will want to continue to sign the updates with the same certificate or set of +certificates, if you want users to upgrade seamlessly to the new version. When +the system is installing an update to an application, it compares the +certificate(s) in the new version with those in the existing version. If the +certificates match exactly, including both the certificate data and order, then +the system allows the update. If you sign the new version without using matching +certificates, you will also need to assign a different package name to the +application — in this case, the user installs the new version as a +completely new application.
    • + +
    • Application modularity – The Android system allows applications that +are signed by the same certificate to run in the same process, if the +applications so requests, so that the system treats them as a single application. +In this way you can deploy your application in modules, and users can update +each of the modules independently if needed.
    • + +
    • Code/data sharing through permissions – The Android system provides +signature-based permissions enforcement, so that an application can expose +functionality to another application that is signed with a specified +certificate. By signing multiple applications with the same certificate and +using signature-based permissions checks, your applications can share code and +data in a secure manner.
    • + +
    + +

    Another important consideration in determining your signing strategy is +how to set the validity period of the key that you will use to sign your +applications.

    + +
      +
    • If you plan to support upgrades for a single application, you should ensure +that your key has a validity period that exceeds the expected lifespan of +that application. A validity period of 25 years or more is recommended. +When your key's validity period expires, users will no longer be +able to seamlessly upgrade to new versions of your application.
    • + +
    • If you will sign multiple distinct applications with the same key, +you should ensure that your key's validity period exceeds the expected +lifespan of all versions of all of the applications, including +dependent applications that may be added to the suite in the future.
    • + +
    • If you plan to publish your application(s) on Google Play, the +key you use to sign the application(s) must have a validity period +ending after 22 October 2033. Google Play enforces this requirement +to ensure that users can seamlessly upgrade applications when +new versions are available.
    • +
    + +

    As you design your application, keep these points in mind and make sure to +use a suitable certificate to sign your applications.

    + +

    Basic Setup for Signing

    + +

    Before you begin, make sure that the Keytool utility and Jarsigner utility are available to +the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell +the SDK build tools how to find these utilities by setting your JAVA_HOME environment +variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and +Jarsigner to your PATH variable.

    + +

    If you are developing on a version of Linux that originally came with GNU Compiler for +Java, make sure that the system is using the JDK version of Keytool, rather than the gcj +version. If Keytool is already in your PATH, it might be pointing to a symlink at +/usr/bin/keytool. In this case, check the symlink target to be sure it points +to the Keytool in the JDK.

    + +

    Signing in Debug Mode

    + +

    The Android build tools provide a debug signing mode that makes it easier for you +to develop and debug your application, while still meeting the Android system +requirement for signing your APK. +When using debug mode to build your app, the SDK tools invoke Keytool to automatically create +a debug keystore and key. This debug key is then used to automatically sign the APK, so +you do not need to sign the package with your own key.

    + +

    The SDK tools create the debug keystore/key with predetermined names/passwords:

    +
      +
    • Keystore name: "debug.keystore"
    • +
    • Keystore password: "android"
    • +
    • Key alias: "androiddebugkey"
    • +
    • Key password: "android"
    • +
    • CN: "CN=Android Debug,O=Android,C=US"
    • +
    + +

    If necessary, you can change the location/name of the debug keystore/key or +supply a custom debug keystore/key to use. However, any custom debug +keystore/key must use the same keystore/key names and passwords as the default +debug key (as described above). (To do so in Eclipse/ADT, go to +Windows > Preferences > +Android > Build.)

    + +

    Caution: You cannot release your application +to the public when signed with the debug certificate.

    + +

    Eclipse Users

    + +

    If you are developing in Eclipse/ADT (and have set up Keytool and Jarsigner as described above in +Basic Setup for Signing), +signing in debug mode is enabled by default. When you run or debug your +application, ADT signs the {@code .apk} file with the debug certificate, runs {@code zipalign} on +the package, then installs it on +the selected emulator or connected device. No specific action on your part is needed, +provided ADT has access to Keytool.

    + +

    Ant Users

    + +

    If you are using Ant to build your {@code .apk} file, debug signing mode +is enabled by using the debug option with the ant command +(assuming that you are using a build.xml file generated by the +android tool). When you run ant debug to +compile your app, the build script generates a keystore/key and signs the APK for you. +The script then also aligns the APK with the zipalign tool. +No other action on your part is needed. Read +Building and Running Apps +on the Command Line for more information.

    + + +

    Expiry of the Debug Certificate

    + +

    The self-signed certificate used to sign your application in debug mode (the default on +Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.

    + +

    When the certificate expires, you will get a build error. On Ant builds, the error +looks like this:

    + +
    debug:
    +[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
    +[exec] Debug Certificate expired on 8/4/08 3:43 PM
    + +

    In Eclipse/ADT, you will see a similar error in the Android console.

    + +

    To fix this problem, simply delete the debug.keystore file. +The default storage location for AVDs is in ~/.android/ on OS X and Linux, +in C:\Documents and Settings\<user>\.android\ on Windows XP, and in +C:\Users\<user>\.android\ on Windows Vista and Windows 7.

    + + +

    The next time you build, the build tools will regenerate a new keystore and debug key.

    + +

    Note that, if your development machine is using a non-Gregorian locale, the build +tools may erroneously generate an already-expired debug certificate, so that you get an +error when trying to compile your application. For workaround information, see the +troubleshooting topic +I can't compile my app because the build tools generated an expired debug +certificate.

    + + +

    Signing in Release Mode

    + +

    When your application is ready for release to other users, you must:

    +
      +
    1. Obtain a suitable private key
    2. +
    3. Compile the application in release mode
    4. +
    5. Sign your application with your private key
    6. +
    7. Align the final APK package
    8. +
    + +

    If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard +to perform the compile, sign, and align procedures. The Export Wizard even allows you to +generate a new keystore and private key in the process. So if you use Eclipse, you can +skip to Compile and sign with Eclipse ADT.

    + + + +

    1. Obtain a suitable private key

    + +

    In preparation for signing your application, you must first ensure that +you have a suitable private key with which to sign. A suitable private +key is one that:

    + +
      +
    • Is in your possession
    • +
    • Represents the personal, corporate, or organizational entity to be identified +with the application
    • +
    • Has a validity period that exceeds the expected lifespan of the application +or application suite. A validity period of more than 25 years is recommended. +

      If you plan to publish your application(s) on Google Play, note that a +validity period ending after 22 October 2033 is a requirement. You can not upload an +application if it is signed with a key whose validity expires before that date. +

    • +
    • Is not the debug key generated by the Android SDK tools.
    • +
    + +

    The key may be self-signed. If you do not have a suitable key, you must +generate one using Keytool. Make sure that you have Keytool available, as described +in Basic Setup.

    + +

    To generate a self-signed key with Keytool, use the keytool +command and pass any of the options listed below (and any others, as +needed).

    + +

    Warning: Keep your private key secure. +Before you run Keytool, make sure to read +Securing Your Private Key for a discussion of how to keep +your key secure and why doing so is critically important to you and to users. In +particular, when you are generating your key, you should select strong passwords +for both the keystore and key.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Keytool OptionDescription
    -genkeyGenerate a key pair (public and private +keys)
    -vEnable verbose output.
    -alias <alias_name>An alias for the key. Only +the first 8 characters of the alias are used.
    -keyalg <alg>The encryption algorithm to use +when generating the key. Both DSA and RSA are supported.
    -keysize <size>The size of each generated key +(bits). If not supplied, Keytool uses a default key size of 1024 bits. In +general, we recommend using a key size of 2048 bits or higher.
    -dname <name>

    A Distinguished Name that describes +who created the key. The value is used as the issuer and subject fields in the +self-signed certificate.

    Note that you do not need to specify this option +in the command line. If not supplied, Jarsigner prompts you to enter each +of the Distinguished Name fields (CN, OU, and so on).

    -keypass <password>

    The password for the +key.

    As a security precaution, do not include this option in your command +line. If not supplied, Keytool prompts you to enter the password. In this way, +your password is not stored in your shell history.

    -validity <valdays>

    The validity period for the +key, in days.

    Note: A value of 10000 or greater is recommended.

    -keystore <keystore-name>.keystoreA name +for the keystore containing the private key.
    -storepass <password>

    A password for the +keystore.

    As a security precaution, do not include this option in your +command line. If not supplied, Keytool prompts you to enter the password. In +this way, your password is not stored in your shell history.

    + +

    Here's an example of a Keytool command that generates a private key:

    + +
    $ keytool -genkey -v -keystore my-release-key.keystore
    +-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
    + +

    Running the example command above, Keytool prompts you to provide +passwords for the keystore and key, and to provide the Distinguished +Name fields for your key. It then generates the keystore as a file called +my-release-key.keystore. The keystore and key are +protected by the passwords you entered. The keystore contains +a single key, valid for 10000 days. The alias is a name that you — +will use later, to refer to this keystore when signing your application.

    + +

    For more information about Keytool, see the documentation at + +http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

    + + + +

    2. Compile the application in release mode

    + +

    In order to release your application to users, you must compile it in release mode. +In release mode, the compiled application is not signed by default and you will need +to sign it with your private key.

    + +

    Caution: +You can not release your application unsigned, or signed with the debug key.

    + +

    With Eclipse

    + +

    To export an unsigned APK from Eclipse, right-click the project in the Package +Explorer and select Android Tools > Export Unsigned Application +Package. Then specify the file location for the unsigned APK. +(Alternatively, open your AndroidManifest.xml file in Eclipse, select +the Manifest tab, and click Export an unsigned APK.)

    + +

    Note that you can combine the compiling and signing steps with the Export Wizard. See +Compiling and signing with Eclipse ADT.

    + +

    With Ant

    + +

    If you are using Ant, you can enable release mode by using the release option +with the ant command. For example, if you are running Ant from the +directory containing your {@code build.xml} file, the command would look like this:

    + +
    $ ant release
    + +

    By default, the build script compiles the application APK without signing it. The output file +in your project {@code bin/} will be <your_project_name>-unsigned.apk. +Because the application APK is still unsigned, you must manually sign it with your private +key and then align it using {@code zipalign}.

    + +

    However, the Ant build script can also perform the signing +and aligning for you, if you have provided the path to your keystore and the name of +your key alias in the project's {@code ant.properties} file. With this information provided, +the build script will prompt you for your keystore and alias password when you perform +ant release, it will sign the package and then align it. The final output +file in {@code bin/} will instead be +<your_project_name>-release.apk. With these steps +automated for you, you're able to skip the manual procedures below (steps 3 and 4). +To learn how to specify your keystore and alias in the {@code ant.properties} file, +see +Building and Running Apps on the Command Line.

    + + + +

    3. Sign your application with your private key

    + +

    When you have an application package that is ready to be signed, you can do sign it +using the Jarsigner tool. Make sure that you have Jarsigner available on your +machine, as described in Basic Setup. Also, make sure that +the keystore containing your private key is available.

    + +

    To sign your application, you run Jarsigner, referencing both the +application's APK and the keystore containing the private key with which to +sign the APK. The table below shows the options you could use.

    + + + + + + + + + + + + + + + + + + + + + + + + +
    Jarsigner OptionDescription
    -keystore <keystore-name>.keystoreThe name of +the keystore containing your private key.
    -verboseEnable verbose output.
    -sigalgThe name of the signature algorithim to use in signing the APK. +Use the value {@code MD5withRSA}.
    -digestalgThe message digest algorithim to use in processing the entries +of an APK. Use the value {@code SHA1}.
    -storepass <password>

    The password for the +keystore.

    As a security precaution, do not include this option +in your command line unless you are working at a secure computer. +If not supplied, Jarsigner prompts you to enter the password. In this +way, your password is not stored in your shell history.

    -keypass <password>

    The password for the private +key.

    As a security precaution, do not include this option +in your command line unless you are working at a secure computer. +If not supplied, Jarsigner prompts you to enter the password. In this +way, your password is not stored in your shell history.

    + +

    Here's how you would use Jarsigner to sign an application package called +my_application.apk, using the example keystore created above. +

    + +
    $ jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore my-release-key.keystore
    +my_application.apk alias_name
    + +

    Running the example command above, Jarsigner prompts you to provide +passwords for the keystore and key. It then modifies the APK +in-place, meaning the APK is now signed. Note that you can sign an +APK multiple times with different keys.

    + +

    Caution: As of JDK 7, the default signing algorithim has +changed, requiring you to specify the signature and digest algorithims ({@code -sigalg} and {@code +-digestalg}) when you sign an APK.

    + +

    To verify that your APK is signed, you can use a command like this:

    + +
    $ jarsigner -verify my_signed.apk
    + +

    If the APK is signed properly, Jarsigner prints "jar verified". +If you want more details, you can try one of these commands:

    + +
    $ jarsigner -verify -verbose my_application.apk
    + +

    or

    + +
    $ jarsigner -verify -verbose -certs my_application.apk
    + +

    The command above, with the -certs option added, will show you the +"CN=" line that describes who created the key.

    + +

    Note: If you see "CN=Android Debug", this means the APK was +signed with the debug key generated by the Android SDK. If you intend to release +your application, you must sign it with your private key instead of the debug +key.

    + +

    For more information about Jarsigner, see the documentation at + +http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jarsigner.html

    + + +

    4. Align the final APK package

    + +

    Once you have signed the APK with your private key, run zipalign on the file. +This tool ensures that all uncompressed data starts with a particular byte alignment, +relative to the start of the file. Ensuring alignment at 4-byte boundaries provides +a performance optimization when installed on a device. When aligned, the Android +system is able to read files with {@code mmap()}, even if +they contain binary data with alignment restrictions, rather than copying all +of the data from the package. The benefit is a reduction in the amount of +RAM consumed by the running application.

    + +

    The zipalign tool is provided with the Android SDK, inside the +tools/ directory. To align your signed APK, execute:

    + +
    $ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk
    + +

    The {@code -v} flag turns on verbose output (optional). {@code 4} is the +byte-alignment (don't use anything other than 4). The first file argument is +your signed {@code .apk} file (the input) and the second file is the destination {@code .apk} file +(the output). If you're overriding an existing APK, add the {@code -f} flag.

    + +

    Caution: Your input APK must be signed with your +private key before you optimize the package with {@code zipalign}. +If you sign it after using {@code zipalign}, it will undo the alignment.

    + +

    For more information, read about the +zipalign tool. + + +

    Compile and sign with Eclipse ADT

    + +

    If you are using Eclipse with the ADT plugin, you can use the Export Wizard to +export a signed APK (and even create a new keystore, +if necessary). The Export Wizard performs all the interaction with +the Keytool and Jarsigner for you, which allows you to sign the package using a GUI +instead of performing the manual procedures to compile, sign, +and align, as discussed above. Once the wizard has compiled and signed your package, +it will also perfom package alignment with {@code zipalign}. +Because the Export Wizard uses both Keytool and Jarsigner, you should +ensure that they are accessible on your computer, as described above +in the Basic Setup for Signing.

    + +

    To create a signed and aligned APK in Eclipse:

    + +
      +
    1. Select the project in the Package +Explorer and select File > Export.
    2. +
    3. Open the Android folder, select Export Android Application, + and click Next. +

      The Export Android Application wizard now starts, which will + guide you through the process of signing your application, + including steps for selecting the private key with which to sign the APK + (or creating a new keystore and private key).

      +
    4. Complete the Export Wizard and your application will be compiled, + signed, aligned, and ready for distribution.
    5. +
    + + + +

    Securing Your Private Key

    + +

    Maintaining the security of your private key is of critical importance, both +to you and to the user. If you allow someone to use your key, or if you leave +your keystore and passwords in an unsecured location such that a third-party +could find and use them, your authoring identity and the trust of the user +are compromised.

    + +

    If a third party should manage to take your key without your knowledge or +permission, that person could sign and distribute applications that maliciously +replace your authentic applications or corrupt them. Such a person could also +sign and distribute applications under your identity that attack other +applications or the system itself, or corrupt or steal user data.

    + +

    Your reputation as a developer entity depends on your securing your private +key properly, at all times, until the key is expired. Here are some tips for +keeping your key secure:

    + +
      +
    • Select strong passwords for the keystore and key.
    • +
    • When you generate your key with Keytool, do not supply the +-storepass and -keypass options at the command line. +If you do so, your passwords will be available in your shell history, +which any user on your computer could access.
    • +
    • Similarly, when signing your applications with Jarsigner, +do not supply the -storepass and -keypass +options at the command line.
    • +
    • Do not give or lend anyone your private key, and do not let unauthorized +persons know your keystore and key passwords.
    • +
    + +

    In general, if you follow common-sense precautions when generating, using, +and storing your key, it will remain secure.

    \ No newline at end of file diff --git a/docs/html/tools/workflow/publishing/preparing.jd b/docs/html/tools/workflow/publishing/preparing.jd new file mode 100644 index 000000000000..4633d7e85af5 --- /dev/null +++ b/docs/html/tools/workflow/publishing/preparing.jd @@ -0,0 +1,358 @@ +page.title=Preparing for Release +@jd:body + +
    +
    +

    Quickview

    +
      +
    • Learn which resources you'll need to release your app.
    • +
    • Find out how to configure and build your app for release.
    • +
    • Learn best practices for releasing your app.
    • +
    +

    In this document

    +
      +
    1. Introduction
    2. +
    3. Gathering Materials and Resources
    4. +
    5. Configuring Your Application
    6. +
    7. Building Your Application
    8. +
    9. Preparing External Servers and Resources
    10. +
    11. Testing Your Application for Release
    12. +
    +

    See also

    +
      +
    1. Publishing Overview
    2. +
    3. Signing Your Applications
    4. +
    5. Publishing on Google Play
    6. +
    +
    +
    + +

    Before you distribute your Android application to users you need to prepare it for release. The +preparation process is a required development +task for all Android applications and is the first step in the publishing process (see figure +1).

    + +

    When you prepare your application for release, you configure, build, and test a release +version of your application. The configuration tasks are straightforward, involving basic code +cleanup and code modification tasks that help optimize your application. The build process is +similar to the debug build process and can be done using JDK and Android SDK tools. The testing +tasks serve as a final check, ensuring that your application performs as expected under real-world +conditions. When you are finished preparing your application for release you have a signed +.apk file, which you can distribute directly to users or distribute through an +application marketplace such as Google Play.

    + +

    This document summarizes the main tasks you need to perform to prepare your application for +release. The tasks that are described in this document apply to all Android applications regardless +how they are released or distributed to users. If you are releasing your application through Google +Play, you should also read Publishing on +Google Play to be sure your release-ready application satisfies all Google Play +requirements.

    + +

    Note: As a best practice, your application should meet all of your +release criteria for functionality, performance, and stability before you perform the tasks outlined +in this document.

    + +Shows how the preparation process fits into the development process +

    + Figure 1. Preparing for release is a required development +task and is the first step in the publishing process. +

    + +

    Introduction

    + +

    To release your application to users you need to create a release-ready package that users can +install and run on their Android-powered devices. The release-ready package contains the same +components as the debug .apk file — compiled source code, resources, manifest +file, and so on — and it is built using the same build tools. However, unlike the debug +.apk file, the release-ready .apk file is signed with your own certificate +and it is optimized with the zipalign tool.

    + +
    + Shows the five tasks you perform to prepare your app for release +

    + Figure 2. You perform five main tasks to prepare your application for + release. +

    +
    + +

    The signing and optimization tasks are usually seamless if you are building your application with +Eclipse and the ADT plugin or with the Ant build script (included with the Android SDK). For +example, you can use the Eclipse Export Wizard to compile, sign, and optimize your application all +at once. You can also configure the Ant build script to do the same when you build from the command +line.

    + +

    To prepare your application for release you typically perform five main tasks (see figure 2). +Each main task may include one or more smaller tasks depending on how you are releasing your +application. For example, if you are releasing your application through Google Play you may want +to add special filtering rules to your manifest while you are configuring your application for +release. Similarly, to meet Google Play publishing guidelines you may have to prepare screenshots +and create promotional text while you are gathering materials for release.

    + +

    You usually perform the tasks listed in figure 2 after you have throroughly debugged and tested +your application. The Android SDK contains several tools to help you test and debug your Android +applications. For more information, see the Debugging and Testing sections in the Dev Guide.

    + +

    Gathering Materials and Resources

    + +

    To begin preparing your application for release you need to gather several supporting items. At a +minimum this includes cryptographic keys for signing your application and an application icon. You +might also want to include an end-user license agreement.

    + +

    Cryptographic keys

    + +

    The Android system requires that each installed application be digitally signed with a +certificate that is owned by the application's developer (that is, a certificate for which the +developer holds the private key). The Android system uses the certificate as a means of identifying +the author of an application and establishing trust relationships between applications. The +certificate that you use for signing does not need to be signed by a certificate authority; the +Android system allows you to sign your applications with a self-signed certificate. To learn about +certificate requirements, see Obtain a +suitable private key.

    + +

    Important: Your application must be signed with a cryptographic +key whose validity period ends after 22 October 2033.

    + +

    You may also have to obtain other release keys if your application accesses a service or uses a +third-party library that requires you to use a key that is based on your private key. For example, +if your application uses the MapView +class, which is part of the Google Maps external +library, you will need to register your application with the Google Maps service and obtain +a Maps API key. For information about getting a Maps API key, see Obtaining a Maps API +key.

    + +

    Application Icon

    + +

    Be sure you have an application icon and that it meets the recommended icon guidelines. Your +application's icon helps users identify your application on a device's Home +screen and in the Launcher window. It also appears in Manage Applications, My Downloads, and +elsewhere. In addition, publishing services such as Google Play display your icon to users.

    + +

    Note: If you are releasing your application on Google Play, you +need to create a high resolution + version of your icon. See Graphic +Assets for your Application for more information.

    + +

    End-user License Agreement

    + +

    Consider preparing an End User License Agreement (EULA) for your application. A EULA can help +protect your person, organization, and intellectual property, and we recommend that you provide one +with your application.

    + +

    Miscellaneous Materials

    + +

    You might also have to prepare promotional and marketing materials to publicize your application. +For example, if you are releasing your application on Google Play you will need to prepare some +promotional text and you will need to create screenshots of your application. For more +information, see + +Graphic Assets for your Application

    + +

    Configuring Your Application for Release

    + +

    After you gather all of your supporting materials you can start configuring your application +for release. This section provides a summary of the configuration changes we recommend that you make +to your source code, resource files, and application manifest prior to releasing your application. +Although most of the configuration changes listed in this section are optional, they are +considered good coding practices and we encourage you to implement them. In some cases, +you may have already made these configuration changes as part of your development process.

    + +

    Choose a good package name

    + +

    Make sure you choose a package name that is suitable over the life of your application. You +cannot change the package name after you distribute your application to users. You can set the +package name in application's manifest file. For more information, see the package attribute +documentation.

    + +

    Turn off logging and debugging

    + +

    Make sure you deactivate logging and disable the debugging option before you build your +application for release. You can deactivate logging by removing calls to +{@link android.util.Log} methods in your source files. You can disable debugging by removing the +android:debuggable attribute from the <application> tag in your +manifest file, or by setting the android:debuggable attribute to +false in your manifest file. Also, remove any log files or static test files that +were created in your project.

    + +

    Also, you should remove all {@link android.os.Debug} tracing calls that you +added to your code, such as {@link android.os.Debug#startMethodTracing()} and +{@link android.os.Debug#stopMethodTracing()} method calls.

    + +

    Clean up your project directories

    + +

    Clean up your project and make sure it conforms to the directory structure described in Android Projects. +Leaving stray or orphaned files in your project can prevent your application from compiling and +cause your application to behave unpredictably. At a minimum you should do the following cleanup +tasks:

    + +
      +
    • Review the contents of your jni/, lib/, and src/ + directories. The jni/ directory should contain only source files associated with the + Android NDK, such as + .c, .cpp, .h, and .mk files. The + lib/ directory should contain only third-party library files or private library + files, including prebuilt shared and static libraries (for example, .so files). The + src/ directory should contain only the source files for your application + (.java and .aidl files). The src/ directory should not + contain any .jar files.
    • +
    • Check your project for private or proprietary data files that your application does not use + and remove them. For example, look in your project's res/ directory for old + drawable files, layout files, and values files that you are no longer using and delete them.
    • +
    • Check your lib/ directory for test libraries and remove them if they are no + longer being used by your application.
    • +
    • Review the contents of your assets/ directory and your res/raw/ + directory for raw asset files and static files that you need to update or remove prior to + release.
    • +
    + +

    Review and update your manifest settings

    + +

    Verify that the following manifest items are set correctly:

    + +
      +
    • + <uses-permission> element +

      You should specify only those permissions that are relevant and required for your application.

      +
    • +
    • android:icon and android:label attributes +

      You must specify values for these attributes, which are located in the + <application> + element.

      +
    • +
    • android:versionCode and android:versionName attributes. +

      We recommend that you specify values for these attributes, which are located in the + <manifest> + element. For more information see + Versioning your Application.

      +
    • +
    + +

    There are several additional manifest elements that you can set if you are releasing your +application on Google Play. For example, the android:minSdkVersion and +android:targetSdkVersion attributes, which are located in the <uses-sdk> element. For more +information about these and other Google Play settings, see Filters on Google Play.

    + +

    Address compatibility issues

    + +

    Android provides several tools and techniques to make your application compatible with a wide +range of devices. To make your application available to the largest number of users, consider +doing the following:

    + +
      +
    • Add support for multiple screen configurations +

      Make sure you meet the + + best practices for supporting multiple screens. By supporting multiple screen configurations + you can create an application that functions properly and looks good on any of the screen sizes + supported by Android.

      +
    • +
    • Optimize your application for Android 3.0 devices. +

      If your application is designed for devices older than Android 3.0, make it compatible + with Android 3.0 devices by following the guidelines and best practices described in + Optimizing Apps for Android 3.0 + .

      +
    • +
    • Consider using the Support Library +

      If your application is designed for devices running Android 3.x, make your application + compatible with older versions of Android by adding the + Support Library to your + application project. The Support Library provides static support libraries that you can add to + your Android application, which enables you to use APIs that are either not available on + older platform versions or use utility APIs that are not part of the framework APIs.

      +
    • +
    + +

    Update URLs for servers and services

    + +

    If your application accesses remote servers or services, make sure you are using the production +URL or path for the server or service and not a test URL or path.

    + +

    Implement Licensing (if you are releasing on Google Play)

    + +

    If you are releasing a paid application through Google Play, consider adding support for +Google Play Licensing. Licensing lets you control access to your application based on whether the +current user has purchased it. Using Google Play Licensing is optional even if you are +releasing your app through Google Play.

    + +

    For more information about Google Play Licensing Service and how to use it in your +application, see Application Licensing.

    + +

    Building Your Application for Release

    + +

    After you finish configuring your application you can build it into a release-ready +.apk fle that is signed and optimized. The JDK includes the tools for signing the +.apk file (Keytool and Jarsigner); the Android SDK includes the tools for compiling and +optimizing the .apk file. If you are using Eclipse with the ADT plugin or you are using +the Ant build script from the command line, you can automate the entire build process.

    + +

    Building with Eclipse

    + +

    You can use the Eclipse Export Wizard to build a release-ready .apk file that is +signed with your private key and optimized. To learn how to run the Export Wizard, see +Compile and sign with Eclipse +ADT. The Export Wizard compiles your application for release, signs your application with your +private key, and optimizes your application with the zipalign tool. The Export Wizard should run +successfully if you have run or debugged your application from Eclipse and you have no errors in +your application (see Building +and Running from Eclipse with ADT for more information.

    + +

    The Export Wizard assumes that you have a certificate and private key +suitable for signing your application. If you do not have a suitable certificate and private key, +the Export Wizard will help you generate one (see +Signing Your Applications for more +information about the signing process and signing guidelines.

    + +

    Building with Ant

    + +

    You can use the Ant build script (included in the Android SDK) to build a release-ready +.apk file that is signed with your private key and optimized. To learn how to do this, +see Building in +Release Mode. This build method assumes you have a certificate and +private key suitable for signing your application. If you do not have a suitable certificate and +private key, the Export Wizard will help you generate one (see +Signing Your Applications for more +information about the signing process and signing guidelines.

    + +

    Preparing External Servers and Resources

    + +

    If your application relies on a remote server, make sure the server is secure and that it is +configured for production use. This is particularly important if you are implementing in-app billing in your application and you are +performing the signature verification step on a remote server.

    + +

    Also, if your application fetches content from a remote server or a real-time service (such as a +content feed), be sure the content you are providing is up to date and production-ready.

    + +

    Testing Your Application for Release

    + +

    Testing the release version of your application helps ensure that your application runs properly +under realistic device and network conditions. Ideally, you should test your application on at least +one handset-sized device and one tablet-sized device to verify that your user interface elements are +sized correctly and that your application's performance and battery efficiency are acceptable.

    + +

    As a starting point for testing, see +What to Test. This article provides +a summary of common Android situations that you should consider when you are testing. When you are +done testing and you are satisfied that the release version of your application +behaves correctly, you can release your application to users. For more information, see +Releasing Your +Application to Users. If you are publishing your application on Google Play, see +Publishing on Google Play.

    + + diff --git a/docs/html/tools/workflow/publishing/publishing.jd b/docs/html/tools/workflow/publishing/publishing.jd new file mode 100644 index 000000000000..a54b030290ed --- /dev/null +++ b/docs/html/tools/workflow/publishing/publishing.jd @@ -0,0 +1,703 @@ +page.title=Publishing on Google Play +@jd:body + +
    +
    + +

    Quickview

    + +
      +
    • Learn how to publish and update apps on Google Play.
    • +
    • Find out how to create links to apps that are published on Google Play.
    • +
    • Learn about Google Play features.
    • +
    + + +

    In this document

    + +
      +
    1. About Google Play +
    2. Publishing Apps on Google Play
    3. +
    4. Publishing Updates on Google Play
    5. +
    6. Using Google Play Licensing Service
    7. +
    8. Using Google Play In-app Billing
    9. +
    10. Linking to Your Apps on Google Play +
        +
      1. Opening an app's details page
      2. +
      3. Performing a search
      4. +
      5. Build a Google Play button
      6. +
      7. Summary of URI formats
      8. +
      +
    11. +
    + +

    See also

    + +
      +
    1. Publishing Overview
    2. +
    3. Preparing for Release
    4. +
    + +
    + +
    + +

    Already know about Google Play and want to get started?

    +

    Go to Google Play, create a developer +account, and upload your application. For more information about required assets, listing details, +and publishing options, see Upload +Applications.

    +
    +
    + +
    +
    + +

    One of the most effective ways to get your application into users' hands is to +publish it on an application marketplace like Google Play. Publishing on Google Play is a +straightforward process that you can do in just a few simple steps—register, configure, +upload, and publish. Registration takes only a few minutes and needs to be done only once. +The configuration and publishing steps can all be done through the Google Play Android Developer Console +after you register as a Google Play developer.

    + +

    To start publishing on Google Play, first read this topic and then go to the Google Play Android Developer Console and register as +a Google Play developer.

    + + +

    About Google Play

    + +

    Google Play is a robust publishing platform that helps you publicize, sell, and distribute +your Android applications to users around the world. When you release your applications through +Google Play you have access to a suite of developer tools that let you analyze your sales, +identify market trends, and control who your applications are being distributed to. You also have +access to several revenue-enhancing features, such as in-app billing and +application licensing.

    + +

    Before you can publish applications on Google Play, you need to register as a Google Play developer. During the +registration process you will need to create a developer profile, pay a registration fee, and agree +to the Google Play +Developer Distribution Agreement. After you register you can access the Developer +Console, where you can upload applications, configure publishing options, and monitor publishing +data. If you want to sell your applications or use the in-app billing feature, you will also need +to set up a Google Checkout merchant account. For more information about the registration process, +see +Developer Registration.

    + +

    Publishing Apps on Google Play

    + +

    Publishing your application on Google Play is a simple process that involves three basic +tasks (see figure 1):

    + +
      +
    • Creating various graphical assets that +accompany your app on Google Play.
    • +
    • Using the Google Play Developer Console to configure publishing options, +specify listing details, and upload your app and graphical assets to Google Play.
    • +
    • Reviewing your publishing settings and changing the release +status of your app from Unpublished to Published.
    • +
    + +Shows the three steps that are required to publish on Google Play +

    + Figure 1. To publish apps on Google Play you must first prepare your app for release and then perform +three simple tasks. +

    + +

    Important: You must prepare your application for release before you +can publish it on Google Play. When you prepare your application for release you configure it for +release and build it in release mode. Building in release mode signs your application's {@code .apk} +file with your private release key. You cannot publish an application on Google Play unless it is +signed with your own private release key.

    + +

    Preparing promotional materials

    + +

    To fully leverage the marketing and publicity capabilities of Google Play, you need to create +several graphical assets that accompany your app on Google Play, such as screenshots, videos, +promotional graphics, and promotional text. At a minimum you must provide two screenshots of your +application and a high resolution application icon. The screenshots are displayed on the details +page for your application on Google Play, and the high resolution application icon is displayed +in various locations throughout Google Play. The high resolution icon does not replace the +launcher icon for your application, rather, it serves as a supplemental icon and should look +the same as your launcher icon. Promotional video, +graphics, and text are optional, although we strongly recommended that you prepare these for your +app. For more information about the graphic assets that accompany your application, see Graphic +Assets for your Application.

    + +

    Configuring options and uploading assets

    + +

    Google Play lets you target your application to a worldwide pool of users and devices. To +reach these users you can use the Developer Console to configure various publishing +options and listing details for your app. For example, you can choose the countries you want to reach, the listing languages you want to use, and the +price you want to charge in each country. You can also configure listing +details such as the application type, category, and content rating. In addition, if you want to sell items within your app using +the in-app billing feature, you can use the Developer Console to create a product list and control which items are available for purchase in your +app.

    + +

    When you are finished setting publishing options and listing details, you can upload your assets +and your application to Google Play. You can also upload your application as a draft +(unpublished) application, which lets you do final testing before you publish it for final +release.

    + +

    To learn more about Google Play publishing settings, see the following resources:

    + + + +

    Publishing your application

    + +

    When you are satisfied that your publishing settings are correctly configured and your uploaded +application is ready to be released to the public, you can simply click Publish in +the Developer Console to make your app available for download +around the world. Keep in mind, it can take several hours for your app to appear on Google +Play after you click Publish in the Developer Console.

    + +

    Controlling Distribution to Devices

    + +

    If your application targets different device configurations, you can control which Android-powered +devices have access to your application on Google Play by +using Google Play filters. Filtering compares device configurations that you declare in your +app's manifest file to the configuration defined by a device. For example, if you declare the camera +filter in your manifest, only those devices that have a camera will see your app on Google +Play. Filters must be configured in your application's manifest file when you are preparing your app for release (that is, before +you upload your app to Google Play). For more information, see Filters on Google Play.

    + +

    You can also use the multiple APK feature to distribute different {@code .apk} files under the same +application listing and the same package name; however, you should use this option only as a last +resort. Android applications usually run on most compatible devices with a single APK, by supplying +alternative resources for different configurations (for example, different layouts for different screen +sizes) and the Android system selects the appropriate resources for the device at runtime. In a +few cases, however, a single APK is unable to support all device configurations, because alternative +resources make the APK file too big (greater than 50MB) or other technical challenges prevent a +single APK from working on all devices. Although we encourage you to develop and publish a single +APK that supports as many device configurations as possible, doing so is sometimes +not possible. To help you publish your application for as many devices as possible, Google Play +allows you to publish multiple APKs under the same application listing. Google Play then supplies +each APK to the appropriate devices based on configuration support you've declared in the manifest +file of each APK. To use this feature, you need to build your separate {@code .apk} files when you are preparing your app for release (that is, before +you upload your app to Google Play). For more information, see Multiple APK Support.

    + +

    Publishing Updates on Google Play

    + +

    At any time after publishing an application on Google Play, you can upload +and publish an update to the same application package. When you publish an +update to an application, users who have already installed the +application may receive a notification that an update is +available for the application. They can then choose to update the application +to the latest version.

    + +

    Before uploading the updated application, be sure that you have incremented +the android:versionCode and android:versionName +attributes in the <manifest> +element of the manifest file. Also, the package name must be the same as the existing version and +the {@code .apk} file must be signed with the same private key. If the package name and signing +certificate do not match those of the existing version, Google Play will +consider it a new application, publish it as such, and will not offer it to existing users as an +update.

    + +

    If you plan to publish your application on Google Play, you must make sure + that it meets the requirements listed below, which are enforced by Google Play + when you upload the application.

    + +

    Using Google Play Licensing Service

    + +

    Google Play offers a licensing service that lets you enforce licensing +policies for paid applications that you publish through Google Play. With +Google Play Licensing, your applications can query Google Play at runtime +to obtain the licensing status for the current user, then allow or disallow +further use of the application as appropriate. Using the service, you can apply a flexible +licensing policy on an application-by-application basis—each +application can enforce its licensing status in the way most appropriate +for it.

    + +

    Any application that you publish through Google Play can use the Google +Play Licensing Service. The service uses no dedicated framework APIs, so you can +add licensing to any application that uses a minimum API Level of 3 or +higher.

    + +

    For complete information about Google Play Licensing Service and how to +use it in your application, read Application Licensing.

    + +

    Using Google Play In-app Billing

    + +

    Google Play In-app Billing +is a Google Play service that lets you sell digital content in your applications. You can use +the service to sell a wide range of content, including downloadable content such as media files or +photos, and virtual content such as game levels or potions.

    + +

    When you use Google Play's in-app billing service to sell an item, Google Play handles all +billing details so your application never has to directly process any financial transactions. +Google Play uses the same checkout service that is used for application purchases, so your users +experience a consistent and familiar purchase flow (see figure 1). Also, the transaction fee for +in-app purchases is the same as the transaction fee for application purchases (30%).

    + +

    Any application that you publish through Google Play can implement in-app billing. No special +account or registration is required other than a Google Play publisher account and a Google +Checkout Merchant account. Also, because the service uses no dedicated framework APIs, you can add +in-app billing to any application that uses a minimum API level of 4 or higher.

    + +

    To help you integrate in-app billing into your application, the Android SDK provides a sample application +that demonstrates a simple implementation of in-app billing. The sample application contains +examples of billing-related classes you can use to implement in-app billing in your application. It +also contains examples of the database, user interface, and business logic you might use to +implement in-app billing. For more information about the in-app billing feature, see the +In-app Billing documentation.

    + +

    Linking to Your Apps on Google Play

    + +

    To help users discover your published applications, you can use two special Google Play URIs +that direct users to your application's details page or perform a search for all of your published +applications on Google Play. You can use these URIs to create a button in your application or a +link on a web page that:

    + +
      +
    • Opens your application's details page in the Google Play application or web site.
    • +
    • Searches for all your published applications in the Google Play application or web +site.
    • +
    + +

    You can launch the Google Play application or web site in the following ways:

    +
      +
    • Initiate an {@link android.content.Intent} from your application that launches the +Google Play application on the user's device.
    • +
    • Provide a link on a web page that opens the Google Play web site (but will also +open the Google Play application if clicked from a device).
    • +
    + +

    In both cases, whether you want to initiate the action from your application or from a web +page, the URIs are quite similar. The only difference is the URI prefix.

    + +

    To open the Google Play application from your application, the prefix for the intent's data +URI is:

    + +

    market://

    + +

    To open Google Play store from your web site, the prefix for the link URI is:

    + +

    http://play.google.com/store/

    + +

    The following sections describe how to create a complete URI for each action.

    + +

    Note: If you create a link to open Google Play from your web +site and the user selects it from an Android-powered device, the device's Google Play application will +resolve the link so the user can use the Google Play application on the device instead of opening the web +site. As such, you should always use {@code http://play.google.com/store/apps/...} URIs when +creating a link on +a web page. When pointing to your apps from within your Android app, use the +{@code market://} URIs in an intent, so that the Google Play application always opens.

    + + +

    Opening an app's details page

    + +

    As described above, you can open the details page for a specific application either on the +Google Play application or the Google Play web site. The details page allows the user to see +the application description, screenshots, reviews and more, and choose to install it.

    + +

    The format for the URI that opens the details page is:

    + +

    <URI_prefix>apps/details?id=<package_name>

    + +

    The <package_name> is a placeholder for the target application's +fully-qualified package name, as declared in the {@code +package} attribute of the {@code +<manifest>} element.

    + +

    For example: http://play.google.com/store/apps/details?id=com.example.myapp

    + + +

    Opening the app details page from your Android app

    + +

    To open the Google Play details page from your application, +create an intent with the {@link android.content.Intent#ACTION_VIEW} action and include a data URI +in this format:

    + +

    market://details?id=<package_name>

    + +

    For example, here's how you can create an intent and open an application's details page in +Google Play:

    + +
    +Intent intent = new Intent(Intent.ACTION_VIEW);
    +intent.setData(Uri.parse("market://details?id=com.example.android"));
    +startActivity(intent);
    +
    + +

    This will open the Google Play application on the device to view the {@code +com.example.android} application.

    + + +

    Opening the app details page from a web site

    + +

    To open the details page from your web site, create a link with a URI in this +format:

    + +

    + http://play.google.com/store/apps/details?id=<package_name> +

    + +

    For example, here's a link that opens an application's details page on Google Play:

    + +
    +<a href="http://play.google.com/store/apps/details?id=com.example.android">App Link</a>
    +
    + +

    When clicked from a desktop web browser, this opens the Google Play web site to view the +{@code com.example.android} application. When clicked from an Android-powered device, users are +given the option to use either their web browser or the Google Play application to view the +application.

    + + + +

    Performing a search

    + +

    To initiate a search on Google Play, the format for the URI is:

    + +

    + <URI_prefix>search?q=<query> +

    + +

    The <query> is a placeholder for the search query to execute in Google +Play. The query can be a raw text string or you can include a parameter that performs a search +based on the publisher name:

    + +
      +
    • To perform a raw text search, append the query string: +

      <URI_prefix>search?q=<search_query>

    • + +
    • To search based on the publisher name, use the {@code pub:} parameter in the query, followed +by the publisher name: +

      <URI_prefix>search?q=pub:<publisher_name>

      +

      You can use this type of search to show all of your published applications.

    • +
    + + +

    Searching from your Android app

    + +

    To initiate a search on Google Play from your application, create an intent with the +{@link android.content.Intent#ACTION_VIEW} action and include a data URI in this format:

    + +

    market://search?q=<query>

    + +

    The query may include the {@code pub:} parameter described above.

    + +

    For example, here's how you can initiate a search in the Google Play application, based on the +publisher name:

    + +
    +Intent intent = new Intent(Intent.ACTION_VIEW);
    +intent.setData(Uri.parse("market://search?q=pub:Your Publisher Name"));
    +startActivity(intent);
    +
    + +

    This opens the Google Play application to perform the search. The search result shows all +applications published by the publisher that are compatible with the current device.

    + + +

    Searching from a web site

    + +

    To initiate a search on Google Play from your web site, create a link with a URI in this +format:

    + +

    + http://play.google.com/store/search?q=<query> +

    + +

    The query may include the {@code pub:} parameter described above.

    + +

    For example, here's a link that initiates a search on Google Play, based on the +publisher name:

    + +
    +<a href="http://play.google.com/store/search?q=pub:Your Publisher Name">Search Link</a>
    +
    + +

    When clicked from a desktop web browser, this opens the Google Play web site and performs the +search. When clicked from an Android-powered device, users are given the option to use either their +web browser or the Google Play application to perform the search.

    + + + +

    Build a Google Play button

    + +

    Use the following form to create a button for your web site that takes users to your application +on Google Play. Input either your application's package name or your publisher name and the button +will take users to Google Play to either view your application's information or view a list of your +published apps. If users click the button while on an Android-powered device, the Google Play +application will respond to show users your application(s).

    + +

    This form offers two styles of the official brand badge each at recommended sizes. You can pick +between either "Get it on Google Play" or "Android app on Google Play." You should not modify the +badge images in any way. For more usage guidelines, +see the Android Brand Guidelines.

    + + + + + +
    + +   + +

     or

    + +   + +

    + +
    + + +      + + +
    + +
    + + +      + + +
    + + +
    +
    + + + + + + + + +

    Summary of URI formats

    + +

    The table below provides a summary of the URIs currently supported by the Google Play (both on +the web and in the Android application), as discussed in the previous sections.

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    For this resultUse this URI in a web page linkOr this URI in an {@link android.content.Intent#ACTION_VIEW} intent
    Display the details screen for a specific applicationhttp://play.google.com/store/apps/details?id=<package_name> +market://details?id=<package_name>
    Search for applications using a general string query.http://play.google.com/store/search?q=<query>market://search?q=<query>
    Search for applications by publisher namehttp://play.google.com/store/search?q=pub:<publisher_name>market://search?q=pub:<publisher_name>
    diff --git a/docs/html/tools/workflow/publishing/publishing_overview.jd b/docs/html/tools/workflow/publishing/publishing_overview.jd new file mode 100755 index 000000000000..ca0dca8ce233 --- /dev/null +++ b/docs/html/tools/workflow/publishing/publishing_overview.jd @@ -0,0 +1,231 @@ +page.title=Publishing Overview +@jd:body + +
    +
    +

    Quickview

    +
      +
    • Learn how to publish Android apps.
    • +
    • Find out how to prepare apps for release.
    • +
    • Learn how to release apps to users.
    • +
    +

    In this document

    +
      +
    1. Preparing Your Application for Release
    2. +
    3. Releasing Your Application to Users +
        +
      1. Releasing on Google Play
      2. +
      3. Releasing on your own website
      4. +
      5. Releasing through email
      6. +
      +
    +

    See also

    +
      +
    1. Preparing for + Release
    2. +
    3. Publishing on Google Play
    4. +
    +
    +
    + +

    Publishing is the process that makes your Android applications available to users. When you +publish an Android application you perform two main tasks:

    + +
      +
    • You prepare the application for release. +

      During the preparation step you build a release version of your application, which users can + download and install on their Android-powered devices.

      +
    • +
    • You release the application to users. +

      During the release step you publicize, sell, and distribute the release version of your + application to users.

      +
    • +
    + +

    Usually, you release your application through an application marketplace, such as Google Play. +However, you can also release applications by sending them directly to users or by letting users +download them from your own website.

    + +

    Figure 1 shows how the publishing process fits into the overall Android application development process. +The publishing process is typically performed after you finish testing your application in a debug +environment. Also, as a best practice, your application should meet all of your release criteria for +functionality, performance, and stability before you begin the publishing process.

    + +Shows where the publishing
+       process fits into the overall development process +

    + Figure 1. Publishing is the last phase of the Android application development process. +

    + +

    Preparing Your Application for Release

    + +

    Preparing your application for release is a multi-step process that involves the following +tasks:

    + +
      + +
    • Configuring your application for release. +

      At a minimum you need to remove {@link android.util.Log} calls and remove the + android:debuggable + attribute from your manifest file. You should also provide values for the + android:versionCode and android:versionName attributes, which are + located in the + <manifest> + element. You may also have to configure several other settings to meet Google Play + requirements or accomodate whatever method you're using to release your application.

      +
    • +
    • Building and signing a release version of your application. +

      The Android Development Tools (ADT) plugin and the Ant build script that are provided + with the Android SDK tools provide everything you need to build and sign a release version of + your application.

      +
    • +
    • Testing the release version of your application. +

      Before you distribute your application, you should thoroughly test the release version on at + least one target handset device and one target tablet device.

      +
    • +
    • Updating application resources for release. +

      You need to be sure that all application resources such as multimedia files and graphics + are updated and included with your application or staged on the proper production servers.

      +
    • +
    • Preparing remote servers and services that your application depends on. +

      If your application depends on external servers or services, you need to be sure they + are secure and production ready.

      +
    • +
    + +

    You may have to perform several other tasks as part of the preparation process. For example, you +will need to get a private key for signing your application, and you may need to get a Maps API +release key if you are using the Google Maps external +library. You will also need to create an icon for your application, and you may want to prepare +an End User License Agreement (EULA) to protect your person, organization, and intellectual +property.

    + +

    When you are finished preparing your application for release you will have a signed +.apk file that you can distribute to users.

    + +

    To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This +topic provides step-by-step instructions for configuring and building a release version of your +application.

    + +

    Releasing Your Application to Users

    + +

    You can release your Android applications several ways. Usually, you release applications +through an application marketplace, such as Google Play, but you can also release applications +on your own website or by sending an application directly to a user. Google Play is the +recommended marketplace for Android applications and is particularly useful if you want to +distribute your applications to a large global audience. The other two release methods—server +distribution and email distribution—are useful if you are releasing an application to a small +group of users (for example, a work group in an enterprise environment), or if you do not want to +make your application available to the general public.

    + +

    Releasing Your Applications on Google Play

    + +

    Google Play is a robust publishing platform that helps you publicize, sell, and distribute +your Android applications to users around the world. When you release your applications through +Google Play you have access to a suite of developer tools that let you analyze your sales, +identify market trends, and control who your applications are being distributed to. You also have +access to several revenue-enhancing features that are not available anywhere else, such as in-app billing and application licensing. This rich array of tools +and features, coupled with numerous end-user community features, makes Google Play the premier +marketplace for selling and buying Android applications.

    + +

    Releasing your application on Google Play is a simple process that involves three basic + steps:

    + +
    + Screenshot showing the graphical user interface element that allows unknown sources
+       to be installed +

    + Figure 2. The Unknown sources setting lets you install + applications that are not published on Google Play . +

    +
    + +
      +
    • Preparing promotional materials. +

      To fully leverage the marketing and publicity capabilities of Google Play, you need to + create promotional materials for your application, such as screenshots, videos, graphics, and + promotional text.

      +
    • +
    • Configuring options and uploading assets. +

      Google Play lets you target your application to a worldwide pool of users and devices. + By configuring various Google Play settings, you can choose the countries you want to + reach, the listing languages you want to use, and the price you want to charge in each + country. You can also configure listing details such as the application type, category, and + content rating. When you are done configuring options you can upload your promotional materials + and your application as a draft (unpublished) application.

      +
    • +
    • Publishing the release version of your application. +

      If you are satisfied that your publishing settings are correctly configured and your + uploaded application is ready to be released to the public, you can simply click + Publish in the developer console and within minutes your application will be + live and available for download around the world.

      +
    • +
    + +

    For information about Google Play, see Publishing on Google Play. This +topic provides an introduction to Google Play features and provides a step-by-step guide for +distributing your applications on Google Play.

    + +

    Releasing your application on your own website

    + +

    If you do not want to release your application on an application marketplace like Google Play, +you can release your application by making it available for download on your own website or server. +To do this, you must first prepare your application for release (that is, you must build it for +release and sign it). Then all you need to do is host the release-ready application on your website +and provide a download link for the application. When users browse to your website with their +Android-powered devices and download your application, the Android system will automatically start +installing the application on the device. However, the installation process will start automatically +only if the user has configured their device to allow the installation of non-Google Play +applications.

    + +
    + Screenshot showing the graphical user interface users see when you send them an app +

    + Figure 3. Users can simply click Install when you send them + an application via email. +

    +
    + +

    By default, Android-powered devices allow users to install applications only if the applications +have been downloaded from Google Play. To allow the installation of applications from other +sources, users need to enable the Unknown sources setting on their devices, and +they need to make this configuration change before they download your application to their +device (see figure 2).

    + +

    Note: Some network providers do not allow users to install +applications from unknown sources.

    + +

    Although it is relatively easy to release your application on your own website, it can be +inefficient and cumbersome. For example, if you want to monetize your application you will +have to process and track all financial transactions yourself and you will not be able to use +Google Play's in-app billing feature to sell in-app products. In addition, you will not be +able to use the licensing feature to help prevent unauthorized installation and use of your +application.

    + +

    Releasing your application through email

    + +

    The easiest and quickest way to release your application is to send it to a user through +email. To do this, you prepare your application for release and then attach it to an email +and send it to a user. When the user opens your email message on their Android-powered device +the Android system will recognize the .apk and display an Install Now +button in the email message (see figure 3). Users can install your application by touching the +button.

    + +

    Note: The Install Now button appears only if a +user has configured their device to allow the installation of non-Google Play applications and +they open your email with the native Gmail application.

    + +

    Releasing applications through email is convenient if you are sending your application to +only a few trusted users, but it provides few protections from piracy and unauthorized +distribution; that is, anyone you send your application to can simply forward it to someone else. +else. diff --git a/docs/html/tools/workflow/publishing/versioning.jd b/docs/html/tools/workflow/publishing/versioning.jd new file mode 100644 index 000000000000..e0b443501306 --- /dev/null +++ b/docs/html/tools/workflow/publishing/versioning.jd @@ -0,0 +1,174 @@ +page.title=Versioning Your Applications +@jd:body + +

    +
    + +

    Quickview

    + +
      +
    • Your application must be versioned
    • +
    • You set the version in the application's manifest file
    • +
    • How you version your applications affects how users upgrade
    • +
    • Determine your versioning strategy early in the development process, including considerations for future releases.
    • +
    + +

    In this document

    + +
      +
    1. Setting Application Version
    2. +
    3. Specifying Your Application's System API Requirements +
    + + +

    See also

    + +
      +
    1. Preparing to Publish Your Application
    2. +
    3. Publishing On Google Play
    4. +
    5. The AndroidManifest.xml File
    6. +
    + +
    +
    + +

    Versioning is a critical component of your application upgrade and maintenance +strategy. Versioning is important because:

    + +
      +
    • Users need to have specific information about the application version that +is installed on their devices and the upgrade versions available for +installation.
    • +
    • Other applications — including other applications that you publish as +a suite — need to query the system for your application's version, to +determine compatibility and identify dependencies.
    • +
    • Services through which you will publish your application(s) may also need to +query your application for its version, so that they can display the version to +users. A publishing service may also need to check the application version to +determine compatibility and establish upgrade/downgrade relationships.
    • +
    + +

    The Android system does not use app version information to enforce +restrictions on upgrades, downgrades, or compatibility of third-party apps. Instead, you (the +developer) are responsible for enforcing version restrictions within your application or by +informing users of the version restrictions and limitations. The Android system does, however, +enforce system version compatibility as expressed by the minSdkVersion attribute in the +manifest. This attribute allows an application to specify the minimum system API with which it is +compatible. For more information see Specifying Minimum System API +Version.

    + +

    Setting Application Version

    +

    To define the version information for your application, you set attributes in +the application's manifest file. Two attributes are available, and you should +always define values for both of them:

    + +
      +
    • android:versionCode — An integer value that represents +the version of the application code, relative to other versions. + +

      The value is an integer so that other applications can programmatically +evaluate it, for example to check an upgrade or downgrade relationship. You can +set the value to any integer you want, however you should make sure that each +successive release of your application uses a greater value. The system does not +enforce this behavior, but increasing the value with successive releases is +normative.

      + +

      Typically, you would release the first version of your application with +versionCode set to 1, then monotonically increase the value with each release, +regardless whether the release constitutes a major or minor release. This means +that the android:versionCode value does not necessarily have a +strong resemblance to the application release version that is visible to the +user (see android:versionName, below). Applications and publishing +services should not display this version value to users.

      +
    • +
    • android:versionName — A string value that represents the +release version of the application code, as it should be shown to users. +

      The value is a string so that you can describe the application version as a +<major>.<minor>.<point> string, or as any other type of +absolute or relative version identifier.

      + +

      As with android:versionCode, the system does not use this value +for any internal purpose, other than to enable applications to display it to +users. Publishing services may also extract the android:versionName +value for display to users.

      +
    • +
    + +

    You define both of these version attributes in the +<manifest> element of the manifest file.

    + +

    Here's an example manifest that shows the android:versionCode +and android:versionName attributes in the +<manifest> element.

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +      package="com.example.package.name"
    +      android:versionCode="2"
    +      android:versionName="1.1">
    +    <application android:icon="@drawable/icon" android:label="@string/app_name">
    +        ...
    +    </application>
    +</manifest>
    +
    + +

    In this example, note that android:versionCode value indicates +that the current .apk contains the second release of the application code, which +corresponds to a minor follow-on release, as shown by the +android:versionName string.

    + +

    The Android framework provides an API to let applications query the system +for version information about your application. To obtain version information, +applications use the +{@link android.content.pm.PackageManager#getPackageInfo(java.lang.String, int)} +method of {@link android.content.pm.PackageManager PackageManager}.

    + +

    Specifying Your Application's System API Requirements

    + +

    If your application requires a specific minimum version of the Android +platform, or is designed only to support a certain range of Android platform +versions, you can specify those version requirements as API Level identifiers +in the application's manifest file. Doing so ensures that your +application can only be installed on devices that +are running a compatible version of the Android system.

    + +

    To specify API Level requirements, add a <uses-sdk> +element in the application's manifest, with one or more of these attributes:

    + +
      +
    • android:minSdkVersion — The minimum version +of the Android platform on which the application will run, specified +by the platform's API Level identifier.
    • +
    • android:targetSdkVersion — Specifies the API Level +on which the application is designed to run. In some cases, this allows the +application to use manifest elements or behaviors defined in the target +API Level, rather than being restricted to using only those defined +for the minimum API Level.
    • +
    • android:maxSdkVersion — The maximum version +of the Android platform on which the application is designed to run, +specified by the platform's API Level identifier. Important: Please read the <uses-sdk> +documentation before using this attribute.
    • +
    + +

    When preparing to install your application, the system checks the value of this +attribute and compares it to the system version. If the +android:minSdkVersion value is greater than the system version, the +system aborts the installation of the application. Similarly, the system +installs your application only if its android:maxSdkVersion +is compatible with the platform version.

    + +

    If you do not specify these attributes in your manifest, the system assumes +that your application is compatible with all platform versions, with no +maximum API Level.

    + +

    To specify a minimum platform version for your application, add a +<uses-sdk> element as a child of +<manifest>, then define the +android:minSdkVersion as an attribute.

    + +

    For more information, see the <uses-sdk> +manifest element documentation and the API Levels document.

    diff --git a/docs/html/tools/workflow/publishing_overview.jd b/docs/html/tools/workflow/publishing_overview.jd new file mode 100755 index 000000000000..ca0dca8ce233 --- /dev/null +++ b/docs/html/tools/workflow/publishing_overview.jd @@ -0,0 +1,231 @@ +page.title=Publishing Overview +@jd:body + +
    +
    +

    Quickview

    +
      +
    • Learn how to publish Android apps.
    • +
    • Find out how to prepare apps for release.
    • +
    • Learn how to release apps to users.
    • +
    +

    In this document

    +
      +
    1. Preparing Your Application for Release
    2. +
    3. Releasing Your Application to Users +
        +
      1. Releasing on Google Play
      2. +
      3. Releasing on your own website
      4. +
      5. Releasing through email
      6. +
      +
    +

    See also

    +
      +
    1. Preparing for + Release
    2. +
    3. Publishing on Google Play
    4. +
    +
    +
    + +

    Publishing is the process that makes your Android applications available to users. When you +publish an Android application you perform two main tasks:

    + +
      +
    • You prepare the application for release. +

      During the preparation step you build a release version of your application, which users can + download and install on their Android-powered devices.

      +
    • +
    • You release the application to users. +

      During the release step you publicize, sell, and distribute the release version of your + application to users.

      +
    • +
    + +

    Usually, you release your application through an application marketplace, such as Google Play. +However, you can also release applications by sending them directly to users or by letting users +download them from your own website.

    + +

    Figure 1 shows how the publishing process fits into the overall Android application development process. +The publishing process is typically performed after you finish testing your application in a debug +environment. Also, as a best practice, your application should meet all of your release criteria for +functionality, performance, and stability before you begin the publishing process.

    + +Shows where the publishing
+       process fits into the overall development process +

    + Figure 1. Publishing is the last phase of the Android application development process. +

    + +

    Preparing Your Application for Release

    + +

    Preparing your application for release is a multi-step process that involves the following +tasks:

    + +
      + +
    • Configuring your application for release. +

      At a minimum you need to remove {@link android.util.Log} calls and remove the + android:debuggable + attribute from your manifest file. You should also provide values for the + android:versionCode and android:versionName attributes, which are + located in the + <manifest> + element. You may also have to configure several other settings to meet Google Play + requirements or accomodate whatever method you're using to release your application.

      +
    • +
    • Building and signing a release version of your application. +

      The Android Development Tools (ADT) plugin and the Ant build script that are provided + with the Android SDK tools provide everything you need to build and sign a release version of + your application.

      +
    • +
    • Testing the release version of your application. +

      Before you distribute your application, you should thoroughly test the release version on at + least one target handset device and one target tablet device.

      +
    • +
    • Updating application resources for release. +

      You need to be sure that all application resources such as multimedia files and graphics + are updated and included with your application or staged on the proper production servers.

      +
    • +
    • Preparing remote servers and services that your application depends on. +

      If your application depends on external servers or services, you need to be sure they + are secure and production ready.

      +
    • +
    + +

    You may have to perform several other tasks as part of the preparation process. For example, you +will need to get a private key for signing your application, and you may need to get a Maps API +release key if you are using the Google Maps external +library. You will also need to create an icon for your application, and you may want to prepare +an End User License Agreement (EULA) to protect your person, organization, and intellectual +property.

    + +

    When you are finished preparing your application for release you will have a signed +.apk file that you can distribute to users.

    + +

    To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This +topic provides step-by-step instructions for configuring and building a release version of your +application.

    + +

    Releasing Your Application to Users

    + +

    You can release your Android applications several ways. Usually, you release applications +through an application marketplace, such as Google Play, but you can also release applications +on your own website or by sending an application directly to a user. Google Play is the +recommended marketplace for Android applications and is particularly useful if you want to +distribute your applications to a large global audience. The other two release methods—server +distribution and email distribution—are useful if you are releasing an application to a small +group of users (for example, a work group in an enterprise environment), or if you do not want to +make your application available to the general public.

    + +

    Releasing Your Applications on Google Play

    + +

    Google Play is a robust publishing platform that helps you publicize, sell, and distribute +your Android applications to users around the world. When you release your applications through +Google Play you have access to a suite of developer tools that let you analyze your sales, +identify market trends, and control who your applications are being distributed to. You also have +access to several revenue-enhancing features that are not available anywhere else, such as in-app billing and application licensing. This rich array of tools +and features, coupled with numerous end-user community features, makes Google Play the premier +marketplace for selling and buying Android applications.

    + +

    Releasing your application on Google Play is a simple process that involves three basic + steps:

    + +
    + Screenshot showing the graphical user interface element that allows unknown sources
+       to be installed +

    + Figure 2. The Unknown sources setting lets you install + applications that are not published on Google Play . +

    +
    + +
      +
    • Preparing promotional materials. +

      To fully leverage the marketing and publicity capabilities of Google Play, you need to + create promotional materials for your application, such as screenshots, videos, graphics, and + promotional text.

      +
    • +
    • Configuring options and uploading assets. +

      Google Play lets you target your application to a worldwide pool of users and devices. + By configuring various Google Play settings, you can choose the countries you want to + reach, the listing languages you want to use, and the price you want to charge in each + country. You can also configure listing details such as the application type, category, and + content rating. When you are done configuring options you can upload your promotional materials + and your application as a draft (unpublished) application.

      +
    • +
    • Publishing the release version of your application. +

      If you are satisfied that your publishing settings are correctly configured and your + uploaded application is ready to be released to the public, you can simply click + Publish in the developer console and within minutes your application will be + live and available for download around the world.

      +
    • +
    + +

    For information about Google Play, see Publishing on Google Play. This +topic provides an introduction to Google Play features and provides a step-by-step guide for +distributing your applications on Google Play.

    + +

    Releasing your application on your own website

    + +

    If you do not want to release your application on an application marketplace like Google Play, +you can release your application by making it available for download on your own website or server. +To do this, you must first prepare your application for release (that is, you must build it for +release and sign it). Then all you need to do is host the release-ready application on your website +and provide a download link for the application. When users browse to your website with their +Android-powered devices and download your application, the Android system will automatically start +installing the application on the device. However, the installation process will start automatically +only if the user has configured their device to allow the installation of non-Google Play +applications.

    + +
    + Screenshot showing the graphical user interface users see when you send them an app +

    + Figure 3. Users can simply click Install when you send them + an application via email. +

    +
    + +

    By default, Android-powered devices allow users to install applications only if the applications +have been downloaded from Google Play. To allow the installation of applications from other +sources, users need to enable the Unknown sources setting on their devices, and +they need to make this configuration change before they download your application to their +device (see figure 2).

    + +

    Note: Some network providers do not allow users to install +applications from unknown sources.

    + +

    Although it is relatively easy to release your application on your own website, it can be +inefficient and cumbersome. For example, if you want to monetize your application you will +have to process and track all financial transactions yourself and you will not be able to use +Google Play's in-app billing feature to sell in-app products. In addition, you will not be +able to use the licensing feature to help prevent unauthorized installation and use of your +application.

    + +

    Releasing your application through email

    + +

    The easiest and quickest way to release your application is to send it to a user through +email. To do this, you prepare your application for release and then attach it to an email +and send it to a user. When the user opens your email message on their Android-powered device +the Android system will recognize the .apk and display an Install Now +button in the email message (see figure 3). Users can install your application by touching the +button.

    + +

    Note: The Install Now button appears only if a +user has configured their device to allow the installation of non-Google Play applications and +they open your email with the native Gmail application.

    + +

    Releasing applications through email is convenient if you are sending your application to +only a few trusted users, but it provides few protections from piracy and unauthorized +distribution; that is, anyone you send your application to can simply forward it to someone else. +else. diff --git a/docs/html/tools/workflow/versioning.jd b/docs/html/tools/workflow/versioning.jd new file mode 100644 index 000000000000..e0b443501306 --- /dev/null +++ b/docs/html/tools/workflow/versioning.jd @@ -0,0 +1,174 @@ +page.title=Versioning Your Applications +@jd:body + +

    +
    + +

    Quickview

    + +
      +
    • Your application must be versioned
    • +
    • You set the version in the application's manifest file
    • +
    • How you version your applications affects how users upgrade
    • +
    • Determine your versioning strategy early in the development process, including considerations for future releases.
    • +
    + +

    In this document

    + +
      +
    1. Setting Application Version
    2. +
    3. Specifying Your Application's System API Requirements +
    + + +

    See also

    + +
      +
    1. Preparing to Publish Your Application
    2. +
    3. Publishing On Google Play
    4. +
    5. The AndroidManifest.xml File
    6. +
    + +
    +
    + +

    Versioning is a critical component of your application upgrade and maintenance +strategy. Versioning is important because:

    + +
      +
    • Users need to have specific information about the application version that +is installed on their devices and the upgrade versions available for +installation.
    • +
    • Other applications — including other applications that you publish as +a suite — need to query the system for your application's version, to +determine compatibility and identify dependencies.
    • +
    • Services through which you will publish your application(s) may also need to +query your application for its version, so that they can display the version to +users. A publishing service may also need to check the application version to +determine compatibility and establish upgrade/downgrade relationships.
    • +
    + +

    The Android system does not use app version information to enforce +restrictions on upgrades, downgrades, or compatibility of third-party apps. Instead, you (the +developer) are responsible for enforcing version restrictions within your application or by +informing users of the version restrictions and limitations. The Android system does, however, +enforce system version compatibility as expressed by the minSdkVersion attribute in the +manifest. This attribute allows an application to specify the minimum system API with which it is +compatible. For more information see Specifying Minimum System API +Version.

    + +

    Setting Application Version

    +

    To define the version information for your application, you set attributes in +the application's manifest file. Two attributes are available, and you should +always define values for both of them:

    + +
      +
    • android:versionCode — An integer value that represents +the version of the application code, relative to other versions. + +

      The value is an integer so that other applications can programmatically +evaluate it, for example to check an upgrade or downgrade relationship. You can +set the value to any integer you want, however you should make sure that each +successive release of your application uses a greater value. The system does not +enforce this behavior, but increasing the value with successive releases is +normative.

      + +

      Typically, you would release the first version of your application with +versionCode set to 1, then monotonically increase the value with each release, +regardless whether the release constitutes a major or minor release. This means +that the android:versionCode value does not necessarily have a +strong resemblance to the application release version that is visible to the +user (see android:versionName, below). Applications and publishing +services should not display this version value to users.

      +
    • +
    • android:versionName — A string value that represents the +release version of the application code, as it should be shown to users. +

      The value is a string so that you can describe the application version as a +<major>.<minor>.<point> string, or as any other type of +absolute or relative version identifier.

      + +

      As with android:versionCode, the system does not use this value +for any internal purpose, other than to enable applications to display it to +users. Publishing services may also extract the android:versionName +value for display to users.

      +
    • +
    + +

    You define both of these version attributes in the +<manifest> element of the manifest file.

    + +

    Here's an example manifest that shows the android:versionCode +and android:versionName attributes in the +<manifest> element.

    + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +      package="com.example.package.name"
    +      android:versionCode="2"
    +      android:versionName="1.1">
    +    <application android:icon="@drawable/icon" android:label="@string/app_name">
    +        ...
    +    </application>
    +</manifest>
    +
    + +

    In this example, note that android:versionCode value indicates +that the current .apk contains the second release of the application code, which +corresponds to a minor follow-on release, as shown by the +android:versionName string.

    + +

    The Android framework provides an API to let applications query the system +for version information about your application. To obtain version information, +applications use the +{@link android.content.pm.PackageManager#getPackageInfo(java.lang.String, int)} +method of {@link android.content.pm.PackageManager PackageManager}.

    + +

    Specifying Your Application's System API Requirements

    + +

    If your application requires a specific minimum version of the Android +platform, or is designed only to support a certain range of Android platform +versions, you can specify those version requirements as API Level identifiers +in the application's manifest file. Doing so ensures that your +application can only be installed on devices that +are running a compatible version of the Android system.

    + +

    To specify API Level requirements, add a <uses-sdk> +element in the application's manifest, with one or more of these attributes:

    + +
      +
    • android:minSdkVersion — The minimum version +of the Android platform on which the application will run, specified +by the platform's API Level identifier.
    • +
    • android:targetSdkVersion — Specifies the API Level +on which the application is designed to run. In some cases, this allows the +application to use manifest elements or behaviors defined in the target +API Level, rather than being restricted to using only those defined +for the minimum API Level.
    • +
    • android:maxSdkVersion — The maximum version +of the Android platform on which the application is designed to run, +specified by the platform's API Level identifier. Important: Please read the <uses-sdk> +documentation before using this attribute.
    • +
    + +

    When preparing to install your application, the system checks the value of this +attribute and compares it to the system version. If the +android:minSdkVersion value is greater than the system version, the +system aborts the installation of the application. Similarly, the system +installs your application only if its android:maxSdkVersion +is compatible with the platform version.

    + +

    If you do not specify these attributes in your manifest, the system assumes +that your application is compatible with all platform versions, with no +maximum API Level.

    + +

    To specify a minimum platform version for your application, add a +<uses-sdk> element as a child of +<manifest>, then define the +android:minSdkVersion as an attribute.

    + +

    For more information, see the <uses-sdk> +manifest element documentation and the API Levels document.

    diff --git a/docs/html/training/advanced.jd b/docs/html/training/advanced.jd new file mode 100644 index 000000000000..7f9ddd4d291b --- /dev/null +++ b/docs/html/training/advanced.jd @@ -0,0 +1,11 @@ +page.title=Advanced Training + +@jd:body + +

    Advanced Training contains a variety of classes that teach you best practices in Android +development. These classes simplify the steps required to enhance your app with powerful +platform features or effectively optimize your app performance.

    + +

    What you see now is still the beginning. We plan to add many more classes, expand and refine +existing classes, re-organize, and build courses that help you enhance your apps using +objective-oriented collections of classes.

    \ No newline at end of file diff --git a/docs/html/training/backward-compatible-ui/index.jd b/docs/html/training/backward-compatible-ui/index.jd index 7e27e68e19d2..f81b5a79bacb 100644 --- a/docs/html/training/backward-compatible-ui/index.jd +++ b/docs/html/training/backward-compatible-ui/index.jd @@ -14,7 +14,7 @@ next.link=abstracting.html

    You should also read

    diff --git a/docs/html/training/basics/activity-lifecycle/index.jd b/docs/html/training/basics/activity-lifecycle/index.jd index d278f042e839..127c1c24925f 100644 --- a/docs/html/training/basics/activity-lifecycle/index.jd +++ b/docs/html/training/basics/activity-lifecycle/index.jd @@ -21,7 +21,7 @@ Project)

    You should also read

    diff --git a/docs/html/training/basics/activity-lifecycle/pausing.jd b/docs/html/training/basics/activity-lifecycle/pausing.jd index 216d55e1d87a..fa88beb39bfb 100644 --- a/docs/html/training/basics/activity-lifecycle/pausing.jd +++ b/docs/html/training/basics/activity-lifecycle/pausing.jd @@ -21,7 +21,7 @@ next.link=stopping.html

    You should also read

    diff --git a/docs/html/training/basics/activity-lifecycle/recreating.jd b/docs/html/training/basics/activity-lifecycle/recreating.jd index 941f1fd11c37..005a95b2d9c0 100644 --- a/docs/html/training/basics/activity-lifecycle/recreating.jd +++ b/docs/html/training/basics/activity-lifecycle/recreating.jd @@ -23,7 +23,7 @@ previous.link=stopping.html Different Screens
  • Handling Runtime Changes
  • -
  • Activities +
  • Activities
  • diff --git a/docs/html/training/basics/activity-lifecycle/starting.jd b/docs/html/training/basics/activity-lifecycle/starting.jd index 1d328c717856..c32968bab907 100644 --- a/docs/html/training/basics/activity-lifecycle/starting.jd +++ b/docs/html/training/basics/activity-lifecycle/starting.jd @@ -22,7 +22,7 @@ next.link=pausing.html

    You should also read

    Try it out

    diff --git a/docs/html/training/basics/activity-lifecycle/stopping.jd b/docs/html/training/basics/activity-lifecycle/stopping.jd index 7dfc6d322aa9..d56c921e3761 100644 --- a/docs/html/training/basics/activity-lifecycle/stopping.jd +++ b/docs/html/training/basics/activity-lifecycle/stopping.jd @@ -21,7 +21,7 @@ next.link=recreating.html

    You should also read

    @@ -37,7 +37,7 @@ class="button">Download the demo

    Properly stopping and restarting your activity is an important process in the activity lifecycle -that ensures your users perceive that your app is always alive and doesn't loose their progress. +that ensures your users perceive that your app is always alive and doesn't lose their progress. There are a few of key scenarios in which your activity is stopped and restarted:

    - +

    Figure 1. Illustration of how {@link android.view.ViewGroup} objects form branches in the layout and contain {@link android.view.View} objects.

    @@ -130,12 +130,12 @@ href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layout guide.

    -

    Add a Text Input Box

    +

    Add a Text Field

    -

    To create a user-editable text box, add an {@link android.widget.EditText +

    To create a user-editable text field, add an {@link android.widget.EditText <EditText>} element inside the {@link android.widget.LinearLayout <LinearLayout>}. The {@link android.widget.EditText} class is a subclass of {@link android.view.View} that displays an editable -text box.

    +text field.

    Like every {@link android.view.View} object, you must define certain XML attributes to specify the {@link android.widget.EditText} object's properties. Here’s how you should declare it @@ -185,7 +185,8 @@ first time. It tells the SDK tools that the resource ID needs to be created. Thu compiled, the SDK tools use the ID value, edit_message, to create a new identifier in your project's {@code gen/R.java} file that is now assiciated with the {@link android.widget.EditText} element. Once the resource ID is created, other references to the ID do not -need the plus symbol. See the sidebox for more information about resource objects.

    +need the plus symbol. This is the only attribute that may need the plus-symbol. See the sidebox for +more information about resource objects.

    {@code @@ -202,12 +203,12 @@ href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts guide.{@code android:hint}
    -
    This is a default string to display when the text box is empty. Instead of using a hard-coded -string as the value, the value given in this example refers to a string resource. When you add the -{@code -"@string/edit_message"} value, you’ll see a compiler error because there’s no matching string -resource by that name. You'll fix this in the next section by defining the string -resource.
    +
    This is a default string to display when the text field is empty. Instead of using a hard-coded +string as the value, the {@code "@string/edit_message"} value refers to a string resource defined +in a separate file. Because this value refers to an existing resource, it does not need the +plus-symbol. However, because you haven't defined the string resource yet, you’ll see a compiler +error when you add the {@code "@string/edit_message"} value. You'll fix this in the next section by +defining the string resource.
    @@ -276,9 +277,9 @@ figure 2.

    android.widget.Button} widgets have their widths set to "wrap_content".

    -

    This works fine for the button, but not as well for the text box, because the user might type +

    This works fine for the button, but not as well for the text field, because the user might type something longer and there's extra space left on the screen. So, it'd be nice to fill that width -using the text box. +using the text field. {@link android.widget.LinearLayout} enables such a design with the weight property, which you can specify using the {@code diff --git a/docs/html/training/basics/firstapp/creating-project.jd b/docs/html/training/basics/firstapp/creating-project.jd index 5a89f2e7b8e4..4fbfe3490a8d 100644 --- a/docs/html/training/basics/firstapp/creating-project.jd +++ b/docs/html/training/basics/firstapp/creating-project.jd @@ -23,9 +23,9 @@ next.link=running-app.html

    You should also read

    @@ -42,8 +42,8 @@ SDK tools from a command line.

    Note: You should already have the Android SDK installed, and if you're using Eclipse, you should have installed the ADT plugin as well. If you have not installed -these, see Installing the Android SDK and return here +href="{@docRoot}tools/sdk/eclipse-adt.html">ADT plugin as well. If you have not installed +these, see Installing the Android SDK and return here when you've completed the installation.

    @@ -59,7 +59,7 @@ when you've completed the installation.

    The resulting dialog should have a folder labeled Android. (If you don’t see the Android folder, then you have not installed the ADT plugin—see Installing the ADT Plugin). +href="{@docRoot}tools/sdk/eclipse-adt.html#installing">Installing the ADT Plugin).
  • Open the Android folder, select Android Project and click Next.
  • Enter a project name (such as "MyFirstApp") and click Next.
  • @@ -68,7 +68,7 @@ href="{@docRoot}sdk/eclipse-adt.html#installing">Installing the ADT Plugin). support older versions, but setting the build target to the latest version allows you to easily optimize your app for a great user experience on the latest Android-powered devices.

    If you don't see any built targets listed, you need to install some using the Android SDK -Manager tool. See step 4 in the +Manager tool. See step 4 in the installing guide.

    Click Next.

  • Specify other app details, such as the: @@ -87,7 +87,7 @@ app (an activity represents a single screen in your app). Enter "MyFirstActivity
  • Minimum SDK: Select 4 (Android 1.6).

    Because this version is lower than the build target selected for the app, a warning appears, but that's alright. You simply need to be sure that you don't use any APIs that require an -API level greater than the minimum SDK +API level greater than the minimum SDK version without first using some code to verify the device's system version (you'll see this in some other classes).

  • @@ -117,7 +117,7 @@ support older versions, but setting the build target to the latest version allow your app for the latest devices.

    If you don't see any targets listed, you need to install some using the Android SDK -Manager tool. See step 4 in the +Manager tool. See step 4 in the installing guide.

  • Execute:
    diff --git a/docs/html/training/basics/firstapp/index.jd b/docs/html/training/basics/firstapp/index.jd
    index 9ff5b18867d3..43b289bfb051 100644
    --- a/docs/html/training/basics/firstapp/index.jd
    +++ b/docs/html/training/basics/firstapp/index.jd
    @@ -35,7 +35,7 @@ to:

  • Download the latest SDK tools and platforms using the SDK Manager.
  • -

    If you haven't already done this setup, read Installing +

    If you haven't already done this setup, read Installing the SDK. Once you've finished the setup, you're ready to begin this class.

    This class uses a tutorial format that incrementally builds a small Android app in order to teach diff --git a/docs/html/training/basics/firstapp/running-app.jd b/docs/html/training/basics/firstapp/running-app.jd index 43b898396475..5105a3bec987 100644 --- a/docs/html/training/basics/firstapp/running-app.jd +++ b/docs/html/training/basics/firstapp/running-app.jd @@ -25,9 +25,9 @@ next.link=building-ui.html

    You should also read

    @@ -85,7 +85,7 @@ the app.

    1. Plug in your Android-powered device to your machine with a USB cable. If you’re developing on Windows, you might need to install the appropriate USB driver for your -device. For help installing drivers, see the OEM USB +device. For help installing drivers, see the OEM USB Drivers document.
    2. Ensure that USB debugging is enabled in the device Settings (open Settings and navitage to Applications > Development on most devices, or select @@ -116,7 +116,7 @@ lesson.

      Run on the Emulator

      Whether you’re using Eclipse or the command line, you need to first create an Android Virtual +href="{@docRoot}tools/devices/index.html">Android Virtual Device (AVD). An AVD is a device configuration for the Android emulator that allows you to model different device configurations.

      diff --git a/docs/html/training/basics/firstapp/starting-activity.jd b/docs/html/training/basics/firstapp/starting-activity.jd index c548c1de259e..a8d32b63e23f 100644 --- a/docs/html/training/basics/firstapp/starting-activity.jd +++ b/docs/html/training/basics/firstapp/starting-activity.jd @@ -31,7 +31,7 @@ previous.link=building-ui.html

      You should also read

      @@ -42,7 +42,7 @@ SDK
    3. After completing the previous lesson, you have an app that -shows an activity (a single screen) with a text box and a button. In this lesson, you’ll add some +shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some code to MyFirstActivity that starts a new activity when the user selects the Send button.

      @@ -90,7 +90,7 @@ the signature must be exactly as shown. Specifically, the method must:

      android.view.View} that was clicked) -

      Next, you’ll fill in this method to read the contents of the text box and deliver that text to +

      Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.

      @@ -290,8 +290,8 @@ public void onCreate(Bundle savedInstanceState) { }
    -

    You can now run the app, type a message in the text box, press Send, and view the message on the -second activity.

    +

    You can now run the app, type a message in the text field, press Send, and view the message on +the second activity.

    Figure 1. Both activities in the final app, running diff --git a/docs/html/training/basics/fragments/communicating.jd b/docs/html/training/basics/fragments/communicating.jd index e3e308f1bd31..3ac987372ec7 100644 --- a/docs/html/training/basics/fragments/communicating.jd +++ b/docs/html/training/basics/fragments/communicating.jd @@ -19,7 +19,7 @@ previous.link=fragment-ui.html

    You should also read

    Try it out

    diff --git a/docs/html/training/basics/fragments/creating.jd b/docs/html/training/basics/fragments/creating.jd index c4a9b4686c2c..0646230beb26 100644 --- a/docs/html/training/basics/fragments/creating.jd +++ b/docs/html/training/basics/fragments/creating.jd @@ -21,7 +21,7 @@ next.link=fragment-ui.html

    You should also read

    Try it out

    @@ -84,7 +84,7 @@ android.app.Activity#onPause()} method is called, any fragments in the activity to {@link android.support.v4.app.Fragment#onPause()}.

    More information about the fragment lifecycle and callback methods is available in the Fragments developer guide.

    +href="{@docRoot}guide/components/fragments.html">Fragments developer guide.

    diff --git a/docs/html/training/basics/fragments/fragment-ui.jd b/docs/html/training/basics/fragments/fragment-ui.jd index f906f468971f..4ec4de56366d 100644 --- a/docs/html/training/basics/fragments/fragment-ui.jd +++ b/docs/html/training/basics/fragments/fragment-ui.jd @@ -20,7 +20,7 @@ next.link=communicating.html

    You should also read

    diff --git a/docs/html/training/basics/fragments/index.jd b/docs/html/training/basics/fragments/index.jd index dcdcd3174cd8..bc93f43df923 100644 --- a/docs/html/training/basics/fragments/index.jd +++ b/docs/html/training/basics/fragments/index.jd @@ -23,7 +23,7 @@ layouts
  • You should also read

    diff --git a/docs/html/training/basics/fragments/support-lib.jd b/docs/html/training/basics/fragments/support-lib.jd index e2166f5db8ff..ba10b782aee4 100644 --- a/docs/html/training/basics/fragments/support-lib.jd +++ b/docs/html/training/basics/fragments/support-lib.jd @@ -17,12 +17,12 @@ next.link=creating.html

    You should also read

    -

    The Android Support Library provides a JAR +

    The Android Support Library provides a JAR file with an API library that allow you to use some of the more recent Android APIs in your app while running on earlier versions of Android. For instance, the Support Library provides a version of the {@link android.app.Fragment} APIs that you can use on Android 1.6 (API level 4) and diff --git a/docs/html/training/basics/intents/index.jd b/docs/html/training/basics/intents/index.jd index c661d98b9b35..d94ff0154a84 100644 --- a/docs/html/training/basics/intents/index.jd +++ b/docs/html/training/basics/intents/index.jd @@ -24,7 +24,7 @@ Lifecycle)

  • Integrating Application with Intents (blog post)
  • -
  • Intents and Intent +
  • Intents and Intent Filters
  • @@ -32,7 +32,7 @@ Filters

    An Android app typically has several activities. Each activity displays a +href="{@docRoot}guide/components/activities.html">activities. Each activity displays a user interface that allows the user to perform a specific task (such as view a map or take a photo). To take the user from one activity to another, your app must use an {@link android.content.Intent} to define your app's "intent" to do something. When you pass an diff --git a/docs/html/training/basics/intents/sending.jd b/docs/html/training/basics/intents/sending.jd index bfd8f9bcf827..f2a2cc3e38b6 100644 --- a/docs/html/training/basics/intents/sending.jd +++ b/docs/html/training/basics/intents/sending.jd @@ -166,7 +166,7 @@ the intent. If it is false, then there aren't any apps to handle th starts in case you need to disable the feature that uses the intent before the user attempts to use it. If you know of a specific app that can handle the intent, you can also provide a link for the user to download the app (see how to link to an app on Google +href="{@docRoot}distribute/googleplay/promote/linking.html">link to your product on Google Play).

    diff --git a/docs/html/training/basics/network-ops/connecting.jd b/docs/html/training/basics/network-ops/connecting.jd new file mode 100644 index 000000000000..f70cf58989f3 --- /dev/null +++ b/docs/html/training/basics/network-ops/connecting.jd @@ -0,0 +1,284 @@ +page.title=Connecting to the Network +parent.title=Performing Network Operations +parent.link=index.html + +trainingnavtop=true +next.title=Managing Network Usage +next.link=managing.html + +@jd:body + + + +

    This lesson shows you how to implement a simple application that connects to +the network. It explains some of the best practices you should follow in +creating even the simplest network-connected app.

    + +

    Note that to perform the network operations described in this lesson, your +application manifest must include the following permissions:

    + +
    <uses-permission android:name="android.permission.INTERNET" />
    +<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    + + + +

    Choose an HTTP Client

    + +

    Most network-connected Android apps use HTTP to send and receive data. +Android includes two HTTP clients: {@link java.net.HttpURLConnection} and Apache + {@link org.apache.http.client.HttpClient}. Both support HTTPS, streaming uploads and downloads, configurable +timeouts, IPv6, and connection pooling. We recommend using {@link +java.net.HttpURLConnection} for applications targeted at Gingerbread and higher. For +more discussion of this topic, see the blog post Android's HTTP Clients.

    + +

    Check the Network Connection

    + +

    Before your app attempts to connect to the network, it should check to see whether a +network connection is available using +{@link android.net.ConnectivityManager#getActiveNetworkInfo getActiveNetworkInfo()} +and {@link android.net.NetworkInfo#isConnected isConnected()}. +Remember, the device may be out of range of a +network, or the user may have disabled both Wi-Fi and mobile data access. +For more discussion of this topic, see the lesson Managing Network +Usage.

    + +
    +public void myClickHandler(View view) {
    +    ...
    +    ConnectivityManager connMgr = (ConnectivityManager) 
    +        getSystemService(Context.CONNECTIVITY_SERVICE);
    +    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    +    if (networkInfo != null && networkInfo.isConnected()) {
    +        // fetch data
    +    } else {
    +        // display error
    +    }
    +    ...
    +}
    + +

    Perform Network Operations on a Separate Thread

    + +

    Network operations can involve unpredictable delays. To prevent this from +causing a poor user experience, always perform network operations on a separate +thread from the UI. The {@link android.os.AsyncTask} class provides one of the +simplest ways to fire off a new task from the UI thread. For more discussion of +this topic, see the blog post Multithreading For Performance.

    + + +

    In the following snippet, the myClickHandler() method invokes new +DownloadWebpageTask().execute(stringUrl). The +DownloadWebpageTask class is a subclass of {@link +android.os.AsyncTask}. DownloadWebpageTask implements the following +{@link android.os.AsyncTask} methods:

    + +
      + +
    • {@link android.os.AsyncTask#doInBackground doInBackground()} executes +the method downloadUrl(). It passes the web page URL as a +parameter. The method downloadUrl() fetches and processes the web +page content. When it finishes, it passes back a result string.
    • + +
    • {@link android.os.AsyncTask#onPostExecute onPostExecute()} takes the +returned string and displays it in the UI.
    • + + +
    + +
    +public class HttpExampleActivity extends Activity {
    +    private static final String DEBUG_TAG = "HttpExample";
    +    private EditText urlText;
    +    private TextView textView;
    +    
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main);   
    +        urlText = (EditText) findViewById(R.id.myUrl);
    +        textView = (TextView) findViewById(R.id.myText);
    +    }
    +
    +    // When user clicks button, calls AsyncTask.
    +    // Before attempting to fetch the URL, makes sure that there is a network connection.
    +    public void myClickHandler(View view) {
    +        // Gets the URL from the UI's text field.
    +        String stringUrl = urlText.getText().toString();
    +        ConnectivityManager connMgr = (ConnectivityManager) 
    +            getSystemService(Context.CONNECTIVITY_SERVICE);
    +        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    +        if (networkInfo != null && networkInfo.isConnected()) {
    +            new DownloadWebpageText().execute(stringUrl);
    +        } else {
    +            textView.setText("No network connection available.");
    +        }
    +    }
    +
    +     // Uses AsyncTask to create a task away from the main UI thread. This task takes a 
    +     // URL string and uses it to create an HttpUrlConnection. Once the connection
    +     // has been established, the AsyncTask downloads the contents of the webpage as
    +     // an InputStream. Finally, the InputStream is converted into a string, which is
    +     // displayed in the UI by the AsyncTask's onPostExecute method.
    +     private class DownloadWebpageText extends AsyncTask {
    +        @Override
    +        protected String doInBackground(String... urls) {
    +              
    +            // params comes from the execute() call: params[0] is the url.
    +            try {
    +                return downloadUrl(urls[0]);
    +            } catch (IOException e) {
    +                return "Unable to retrieve web page. URL may be invalid.";
    +            }
    +        }
    +        // onPostExecute displays the results of the AsyncTask.
    +        @Override
    +        protected void onPostExecute(String result) {
    +            textView.setText(result);
    +       }
    +    }
    +    ...
    +}
    + +

    The sequence of events in this snippet is as follows:

    +
      + +
    1. When users click the button that invokes {@code myClickHandler()}, + the app passes +the specified URL to the {@link android.os.AsyncTask} subclass +DownloadWebpageTask.
    2. + +
    3. The {@link android.os.AsyncTask} method {@link +android.os.AsyncTask#doInBackground doInBackground()} calls the +downloadUrl() method.
    4. + +
    5. The downloadUrl() method takes a URL string as a parameter +and uses it to create a {@link java.net.URL} object.
    6. + +
    7. The {@link java.net.URL} object is used to establish an {@link +java.net.HttpURLConnection}.
    8. + +
    9. Once the connection has been established, the {@link +java.net.HttpURLConnection} object fetches the web page content as an {@link +java.io.InputStream}.
    10. + +
    11. The {@link java.io.InputStream} is passed to the readIt() +method, which converts the stream to a string.
    12. + +
    13. Finally, the {@link android.os.AsyncTask}'s {@link +android.os.AsyncTask#onPostExecute onPostExecute()} method displays the string +in the main activity's UI.
    14. + +
    + +

    Connect and Download Data

    + +

    In your thread that performs your network transactions, you can use + {@link java.net.HttpURLConnection} to perform a {@code GET} and download your data. + After you call {@code connect()}, you can get an {@link java.io.InputStream} of the data + by calling {@code getInputStream()}. + +

    In the following snippet, the {@link android.os.AsyncTask#doInBackground +doInBackground()} method calls the method downloadUrl(). The +downloadUrl() method takes the given URL and uses it to connect to +the network via {@link java.net.HttpURLConnection}. Once a connection has been +established, the app uses the method getInputStream() to retrieve +the data as an {@link java.io.InputStream}.

    + +
    +// Given a URL, establishes an HttpUrlConnection and retrieves
    +// the web page content as a InputStream, which it returns as
    +// a string.
    +private String downloadUrl(String myurl) throws IOException {
    +    InputStream is = null;
    +    // Only display the first 500 characters of the retrieved
    +    // web page content.
    +    int len = 500;
    +        
    +    try {
    +        URL url = new URL(myurl);
    +        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    +        conn.setReadTimeout(10000 /* milliseconds */);
    +        conn.setConnectTimeout(15000 /* milliseconds */);
    +        conn.setRequestMethod("GET");
    +        conn.setDoInput(true);
    +        // Starts the query
    +        conn.connect();
    +        int response = conn.getResponseCode();
    +        Log.d(DEBUG_TAG, "The response is: " + response);
    +        is = conn.getInputStream();
    +
    +        // Convert the InputStream into a string
    +        String contentAsString = readIt(is, len);
    +        return contentAsString;
    +        
    +    // Makes sure that the InputStream is closed after the app is
    +    // finished using it.
    +    } finally {
    +        if (is != null) {
    +            is.close();
    +        } 
    +    }
    +}
    + +

    Note that the method getResponseCode() returns the connection's +status code. This is +a useful way of getting additional information about the connection. A status +code of 200 indicates success.

    + +

    Convert the InputStream to a String

    + +

    An {@link java.io.InputStream} is a readable source of bytes. Once you get an {@link java.io.InputStream}, +it's common to decode or convert it into a +target data type. For example, if you were downloading image data, you might +decode and display it like this:

    + +
    InputStream is = null;
    +...
    +Bitmap bitmap = BitmapFactory.decodeStream(is);
    +ImageView imageView = (ImageView) findViewById(R.id.image_view);
    +imageView.setImageBitmap(bitmap);
    +
    + +

    In the example shown above, the {@link java.io.InputStream} represents the text of a +web page. This is how the example converts the {@link java.io.InputStream} to +a string so that the activity can display it in the UI:

    + +
    // Reads an InputStream and converts it to a String.
    +public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    +    Reader reader = null;
    +    reader = new InputStreamReader(stream, "UTF-8");        
    +    char[] buffer = new char[len];
    +    reader.read(buffer);
    +    return new String(buffer);
    +}
    + + + diff --git a/docs/html/training/basics/network-ops/index.jd b/docs/html/training/basics/network-ops/index.jd new file mode 100644 index 000000000000..b213c035d423 --- /dev/null +++ b/docs/html/training/basics/network-ops/index.jd @@ -0,0 +1,73 @@ +page.title=Performing Network Operations + +trainingnavtop=true +startpage=true +next.title=Connecting to the Network +next.link=connecting.html + +@jd:body + +
    +
    + + +

    Dependencies and prerequisites

    +
      +
    • Android 1.6 (API level 4) or higher
    • +
    • A device that is able to connect to mobile and Wi-Fi networks
    • +
    + + +

    You should also read

    + + + +

    Try it out

    + +
    + Download the sample +

    NetworkUsage.zip

    +
    + +
    +
    + +

    This class explains the basic tasks involved in connecting to the network, +monitoring the network connection (including connection changes), and giving +users control over an app's network usage. It also describes how to parse and +consume XML data.

    + +

    This class includes a sample application that illustrates how to perform +common network operations. You can download the sample (to the right) and use it +as a source of reusable code for your own application.

    + +

    By going through these lessons, you'll have the +fundamental building blocks for creating Android applications that download +content and parse data efficiently, while minimizing network traffic.

    + + + +

    Lessons

    + +
    +
    Connecting to the Network
    + +
    Learn how to connect to the network, choose an HTTP client, and perform +network operations outside of the UI thread.
    + +
    Managing Network Usage
    + +
    Learn how to check a +device's network connection, create a preferences UI for controlling network +usage, and respond to connection changes.
    + +
    Parsing XML Data
    +
    Learn how to parse and consume XML data.
    + +
    + diff --git a/docs/html/training/basics/network-ops/managing.jd b/docs/html/training/basics/network-ops/managing.jd new file mode 100644 index 000000000000..33cb19571b47 --- /dev/null +++ b/docs/html/training/basics/network-ops/managing.jd @@ -0,0 +1,445 @@ +page.title=Managing Network Usage +parent.title=Performing Network Operations +parent.link=index.html + +trainingnavtop=true + +previous.title=Connecting to the Network +previous.link=connecting.html +next.title=Parsing XML Data +next.link=xml.html + +@jd:body + + + +

    This lesson describes how to write applications that have fine-grained +control over their usage of network resources. If your application performs a +lot of network operations, you should provide user settings that allow users +to control your app’s data habits, such as how often your app syncs data, +whether to perform uploads/downloads only when on Wi-Fi, whether to use data +while roaming, and so on. With these controls available to them, users are much +less likely to disable your app’s access to background data when they approach their +limits, because they can instead precisely control how much data your app +uses.

    + +

    For general guidelines on how to write apps that minimize the battery life +impact of downloads and network connections, see +Optimizing Battery Life +and Transferring Data Without Draining the Battery. + +

    Check a Device's Network Connection

    + +

    A device can have various types of network connections. This lesson +focuses on using either a Wi-Fi or a mobile network connection. For the full +list of possible network types, see {@link android.net.ConnectivityManager}.

    + +

    Wi-Fi is typically faster. Also, mobile data is often metered, which can get +expensive. +A common strategy for apps is to only fetch large data +if a Wi-Fi network is available.

    + +

    Before you perform network operations, it's good practice to check the state of +network connectivity. Among other things, this could prevent your app from inadvertently using +the wrong radio. If a network connection is unavailable, your application +should respond gracefully. To check the network connection, you typically use +the following classes:

    + +
      + +
    • {@link android.net.ConnectivityManager}: Answers queries about the state +of network connectivity. It also notifies applications when network +connectivity changes.
    • + +
    • {@link android.net.NetworkInfo}: Describes the status of a network +interface of a given type (currently either Mobile or Wi-Fi). +
    • + +
    + + + +

    This code snippet tests network connectivity for Wi-Fi and mobile. It +determines whether these network interfaces are available (that is, whether +network connectivity is possible) and/or connected (that is, whether network +connectivity exists and if it is possible to establish sockets and pass +data):

    + +
    +private static final String DEBUG_TAG = "NetworkStatusExample";
    +...      
    +ConnectivityManager connMgr = (ConnectivityManager) 
    +        getSystemService(Context.CONNECTIVITY_SERVICE);
    +NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    +boolean isWifiConn = networkInfo.isConnected();
    +networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    +boolean isMobileConn = networkInfo.isConnected();
    +Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
    +Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);
    +
    + +

    Note that you should not base decisions on whether a network is +"available." You should always check {@link +android.net.NetworkInfo#isConnected isConnected()} before performing network +operations, since {@link android.net.NetworkInfo#isConnected isConnected()} +handles cases like flaky mobile networks, airplane mode, and restricted +background data.

    + +

    A more concise way of checking whether a network interface is available is as +follows. The method {@link +android.net.ConnectivityManager#getActiveNetworkInfo() getActiveNetworkInfo()} +returns a {@link android.net.NetworkInfo} instance representing the first +connected network interface it can find, or null if none if the +interfaces is connected (meaning that an +internet connection is not available):

    + +
    +public boolean isOnline() {
    +    ConnectivityManager connMgr = (ConnectivityManager) 
    +            getSystemService(Context.CONNECTIVITY_SERVICE);
    +    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    +    return (networkInfo != null && networkInfo.isConnected());
    +}  
    + +

    To query more fine-grained state you can use {@link +android.net.NetworkInfo.DetailedState}, but this should seldom be necessary.

    + + +

    Manage Network Usage

    + +

    You can implement a preferences activity that gives users explicit control +over your app's usage of network resources. For +example:

    + +
      + +
    • You might allow users to upload videos only when the device is connected to a +Wi-Fi network.
    • + +
    • You might sync (or not) depending on specific criteria such as network +availability, time interval, and so on.
    • + +
    + +

    To write an app that supports network access and managing +network usage, your manifest must have the right permissions and +intent filters. +

    + +
      +
    • The manifest excerpted below includes the following permissions: +
        + +
      • {@link android.Manifest.permission#INTERNET +android.permission.INTERNET}—Allows applications to open network +sockets.
      • + +
      • {@link android.Manifest.permission#ACCESS_NETWORK_STATE +android.permission.ACCESS_NETWORK_STATE}—Allows applications to access +information about networks.
      • + +
      +
    • + +
    • You can declare the intent filter for the +{@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} action (introduced in +Android 4.0) to indicate that your application defines an activity that offers +options to control data usage. {@link +android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} shows settings for managing +the network data usage of a specific application. When your app has a settings activity +that allows users to control network usage, you should declare this intent filter for that activity. +In the sample application, this action is handled by the class +SettingsActivity, which displays a preferences UI to let users +decide when to download a feed.
    • + +
    + + +
    +<?xml version="1.0" encoding="utf-8"?>
    +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    +    package="com.example.android.networkusage"
    +    ...>
    +
    +    <uses-sdk android:minSdkVersion="4" 
    +           android:targetSdkVersion="14" />
    +        
    +    <uses-permission android:name="android.permission.INTERNET" />
    +    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    +
    +    <application
    +        ...>
    +        ...
    +        <activity android:label="SettingsActivity" android:name=".SettingsActivity">
    +             <intent-filter>
    +                <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
    +                <category android:name="android.intent.category.DEFAULT" />
    +          </intent-filter>
    +        </activity>
    +    </application>
    +</manifest>
    +
    + +

    Implement a Preferences Activity

    + +

    As you can see in the manifest excerpt above, the sample app's activity +SettingsActivity has an intent filter for the {@link +android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} action. +SettingsActivity is a subclass of {@link +android.preference.PreferenceActivity}. It displays a preferences screen +(shown in figure 1) that +lets users specify the following:

    + +
      + +
    • Whether to display summaries for each XML feed entry, or just a link for +each entry.
    • + +
    • Whether to download the XML feed if any network connection is available, +or only if Wi-Fi is available.
    • + +
    + +Preferences panel + +Setting a network preference +

    Figure 1. Preferences activity.

    + +

    Here is SettingsActivity. Note that it implements +{@link android.content.SharedPreferences.OnSharedPreferenceChangeListener OnSharedPreferenceChangeListener}. +When a user changes a preference, it fires +{@link android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged onSharedPreferenceChanged()}, +which sets {@code refreshDisplay} to true. This causes the display to refresh when the user +returns to the main activity:

    + +
    public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
    +    
    +    @Override
    +    protected void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        
    +        // Loads the XML preferences file
    +        addPreferencesFromResource(R.xml.preferences);
    +    }
    +  
    +    @Override
    +    protected void onResume() {
    +        super.onResume();
    +
    +        // Registers a listener whenever a key changes            
    +        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    +    }
    +  
    +    @Override
    +    protected void onPause() {
    +        super.onPause();
    +
    +       // Unregisters the listener set in onResume().
    +       // It's best practice to unregister listeners when your app isn't using them to cut down on 
    +       // unnecessary system overhead. You do this in onPause().            
    +       getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);    
    +    }
    +  
    +    // When the user changes the preferences selection, 
    +    // onSharedPreferenceChanged() restarts the main activity as a new
    +    // task. Sets the the refreshDisplay flag to "true" to indicate that 
    +    // the main activity should update its display.
    +    // The main activity queries the PreferenceManager to get the latest settings.
    +    
    +    @Override
    +    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {    
    +        // Sets refreshDisplay to true so that when the user returns to the main
    +        // activity, the display refreshes to reflect the new settings.
    +        NetworkActivity.refreshDisplay = true;
    +    }
    +}
    + +

    Respond to Preference Changes

    + +

    When the user changes preferences in the settings screen, it typically has +consequences for the app's behavior. In this snippet, the app checks the +preferences settings in {@code onStart()}. if there is a match between the setting and +the device's network connection (for example, if the setting is {@code "Wi-Fi"} and the +device has a Wi-Fi connection), the app downloads the feed and refreshes the +display.

    + +
    +public class NetworkActivity extends Activity {
    +    public static final String WIFI = "Wi-Fi";
    +    public static final String ANY = "Any";
    +    private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";
    +   
    +    // Whether there is a Wi-Fi connection.
    +    private static boolean wifiConnected = false; 
    +    // Whether there is a mobile connection.
    +    private static boolean mobileConnected = false;
    +    // Whether the display should be refreshed.
    +    public static boolean refreshDisplay = true;
    +    
    +    // The user's current network preference setting.
    +    public static String sPref = null;
    +    
    +    // The BroadcastReceiver that tracks network connectivity changes.
    +    private NetworkReceiver receiver = new NetworkReceiver();
    +    
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        
    +        // Registers BroadcastReceiver to track network connection changes.
    +        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    +        receiver = new NetworkReceiver();
    +        this.registerReceiver(receiver, filter);
    +    }
    +    
    +    @Override 
    +    public void onDestroy() {
    +        super.onDestroy();
    +        // Unregisters BroadcastReceiver when app is destroyed.
    +        if (receiver != null) {
    +            this.unregisterReceiver(receiver);
    +        }
    +    }
    +    
    +    // Refreshes the display if the network connection and the
    +    // pref settings allow it.
    +    
    +    @Override
    +    public void onStart () {
    +        super.onStart();  
    +        
    +        // Gets the user's network preference settings
    +        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    +        
    +        // Retrieves a string value for the preferences. The second parameter
    +        // is the default value to use if a preference value is not found.
    +        sPref = sharedPrefs.getString("listPref", "Wi-Fi");
    +
    +        updateConnectedFlags(); 
    +       
    +        if(refreshDisplay){
    +            loadPage();    
    +        }
    +    }
    +    
    +    // Checks the network connection and sets the wifiConnected and mobileConnected
    +    // variables accordingly. 
    +    public void updateConnectedFlags() {
    +        ConnectivityManager connMgr = (ConnectivityManager) 
    +                getSystemService(Context.CONNECTIVITY_SERVICE);
    +        
    +        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
    +        if (activeInfo != null && activeInfo.isConnected()) {
    +            wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
    +            mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
    +        } else {
    +            wifiConnected = false;
    +            mobileConnected = false;
    +        }  
    +    }
    +      
    +    // Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
    +    public void loadPage() {
    +        if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
    +                || ((sPref.equals(WIFI)) && (wifiConnected))) {
    +            // AsyncTask subclass
    +            new DownloadXmlTask().execute(URL);
    +        } else {
    +            showErrorPage();
    +        }
    +    }
    +...
    +    
    +}
    + +

    Detect Connection Changes

    + +

    The final piece of the puzzle is the {@link +android.content.BroadcastReceiver} subclass, NetworkReceiver. When +the device's network connection changes, NetworkReceiver intercepts +the action {@link android.net.ConnectivityManager#CONNECTIVITY_ACTION}, +determines what the network connection status is, and sets the flags +wifiConnected and mobileConnected to true/false +accordingly. The upshot is that the next time the user returns to the app, the +app will only download the latest feed and update the display if +NetworkActivity.refreshDisplay is set to true.

    + +

    Setting up a BroadcastReceiver that gets called unnecessarily can be a +drain on system resources. +The sample application registers the +{@link android.content.BroadcastReceiver} {@code NetworkReceiver} in +{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()}, +and it unregisters it in +{@link android.app.Activity#onDestroy onDestroy()}. This is more lightweight +than declaring a {@code <receiver>} in the manifest. When you declare a +{@code <receiver>} in the manifest, it can wake up your app at any time, +even if you haven't run it for weeks. By registering and unregistering +{@code NetworkReceiver} within the main activity, you ensure that the app won't +be woken up after the user leaves the app. +If you do declare a {@code <receiver>} in the manifest and you know exactly +where you need it, you can use +{@link android.content.pm.PackageManager#setComponentEnabledSetting setComponentEnabledSetting()} +to enable and disable it as appropriate.

    + +

    Here is NetworkReceiver:

    + +
    public class NetworkReceiver extends BroadcastReceiver {   
    +      
    +@Override
    +public void onReceive(Context context, Intent intent) {
    +    ConnectivityManager conn =  (ConnectivityManager)
    +        context.getSystemService(Context.CONNECTIVITY_SERVICE);
    +    NetworkInfo networkInfo = conn.getActiveNetworkInfo();
    +       
    +    // Checks the user prefs and the network connection. Based on the result, decides whether
    +    // to refresh the display or keep the current display.
    +    // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
    +    if (WIFI.equals(sPref) && networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
    +        // If device has its Wi-Fi connection, sets refreshDisplay
    +        // to true. This causes the display to be refreshed when the user
    +        // returns to the app.
    +        refreshDisplay = true;
    +        Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
    +
    +    // If the setting is ANY network and there is a network connection
    +    // (which by process of elimination would be mobile), sets refreshDisplay to true.
    +    } else if (ANY.equals(sPref) && networkInfo != null) {
    +        refreshDisplay = true;
    +                 
    +    // Otherwise, the app can't download content--either because there is no network
    +    // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there 
    +    // is no Wi-Fi connection.
    +    // Sets refreshDisplay to false.
    +    } else {
    +        refreshDisplay = false;
    +        Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
    +    }
    +}
    + diff --git a/docs/html/training/basics/network-ops/xml.jd b/docs/html/training/basics/network-ops/xml.jd new file mode 100644 index 000000000000..b148257ec7c3 --- /dev/null +++ b/docs/html/training/basics/network-ops/xml.jd @@ -0,0 +1,555 @@ +page.title=Parsing XML Data +parent.title=Performing Network Operations +parent.link=index.html + +trainingnavtop=true + +previous.title=Managing Network Usage +previous.link=managing.html + +@jd:body + +
    +
    + + + +

    This lesson teaches you to

    +
      +
    1. Choose a Parser
    2. +
    3. Analyze the Feed
    4. +
    5. Instantiate the Parser
    6. +
    7. Read the Feed
    8. +
    9. Parse XML
    10. +
    11. Skip Tags You Don't Care About
    12. +
    13. Consume XML Data
    14. +
    + +

    You should also read

    + + +

    Try it out

    + +
    + Download the sample +

    NetworkUsage.zip

    +
    + +
    +
    + +

    Extensible Markup Language (XML) is a set of rules for encoding documents in +machine-readable form. XML is a popular format for sharing data on the internet. +Websites that frequently update their content, such as news sites or blogs, +often provide an XML feed so that external programs can keep abreast of content +changes. Uploading and parsing XML data is a common task for network-connected +apps. This lesson explains how to parse XML documents and use their data.

    + +

    Choose a Parser

    + +

    We recommend {@link org.xmlpull.v1.XmlPullParser}, which is an efficient and +maintainable way to parse XML on Android. Historically Android has had two +implementations of this interface:

    + +
      +
    • KXmlParser + via {@link org.xmlpull.v1.XmlPullParserFactory#newPullParser XmlPullParserFactory.newPullParser()}. +
    • +
    • ExpatPullParser, via + {@link android.util.Xml#newPullParser Xml.newPullParser()}. +
    • +
    + +

    Either choice is fine. The +example in this section uses ExpatPullParser, via +{@link android.util.Xml#newPullParser Xml.newPullParser()}.

    + +

    Analyze the Feed

    + +

    The first step in parsing a feed is to decide which fields you're interested in. +The parser extracts data for those fields and ignores the rest.

    + +

    Here is an excerpt from the feed that's being parsed in the sample app. Each +post to StackOverflow.com appears in the +feed as an entry tag that contains several nested tags:

    + +
    <?xml version="1.0" encoding="utf-8"?> 
    +<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" ...">     
    +<title type="text">newest questions tagged android - Stack Overflow</title>
    +...
    +    <entry>
    +    ...
    +    </entry>
    +    <entry>
    +        <id>http://stackoverflow.com/q/9439999</id>
    +        <re:rank scheme="http://stackoverflow.com">0</re:rank>
    +        <title type="text">Where is my data file?</title>
    +        <category scheme="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest/tags" term="android"/>
    +        <category scheme="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest/tags" term="file"/>
    +        <author>
    +            <name>cliff2310</name>
    +            <uri>http://stackoverflow.com/users/1128925</uri>
    +        </author>
    +        <link rel="alternate" href="http://stackoverflow.com/questions/9439999/where-is-my-data-file" />
    +        <published>2012-02-25T00:30:54Z</published>
    +        <updated>2012-02-25T00:30:54Z</updated>
    +        <summary type="html">
    +            <p>I have an Application that requires a data file...</p>
    +
    +        </summary>
    +    </entry>
    +    <entry>
    +    ...
    +    </entry>
    +...
    +</feed>
    + +

    The sample app +extracts data for the entry tag and its nested tags +title, link, and summary.

    + + +

    Instantiate the Parser

    + +

    The next step is to +instantiate a parser and kick off the parsing process. In this snippet, a parser +is initialized to not process namespaces, and to use the provided {@link +java.io.InputStream} as its input. It starts the parsing process with a call to +{@link org.xmlpull.v1.XmlPullParser#nextTag() nextTag()} and invokes the +readFeed() method, which extracts and processes the data the app is +interested in:

    + +
    public class StackOverflowXmlParser {
    +    // We don't use namespaces
    +    private static final String ns = null;
    +   
    +    public List parse(InputStream in) throws XmlPullParserException, IOException {
    +        try {
    +            XmlPullParser parser = Xml.newPullParser();
    +            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
    +            parser.setInput(in, null);
    +            parser.nextTag();
    +            return readFeed(parser);
    +        } finally {
    +            in.close();
    +        }
    +    }
    + ... 
    +}
    + +

    Read the Feed

    + +

    The readFeed() method does the actual work of processing the +feed. It looks for elements tagged "entry" as a starting point for recursively +processing the feed. If a tag isn't an {@code entry} tag, it skips it. Once the whole +feed has been recursively processed, readFeed() returns a {@link +java.util.List} containing the entries (including nested data members) it +extracted from the feed. This {@link java.util.List} is then returned by the +parser.

    + +
    +private List readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
    +    List entries = new ArrayList();
    +
    +    parser.require(XmlPullParser.START_TAG, ns, "feed");
    +    while (parser.next() != XmlPullParser.END_TAG) {
    +        if (parser.getEventType() != XmlPullParser.START_TAG) {
    +            continue;
    +        }
    +        String name = parser.getName();
    +        // Starts by looking for the entry tag
    +        if (name.equals("entry")) {
    +            entries.add(readEntry(parser));
    +        } else {
    +            skip(parser);
    +        }
    +    }  
    +    return entries;
    +}
    + + +

    Parse XML

    + + +

    The steps for parsing an XML feed are as follows:

    +
      + +
    1. As described in Analyze the Feed, identify the tags you want to include in your app. This +example extracts data for the entry tag and its nested tags +title, link, and summary.
    2. + +
    3. Create the following methods:

      + +
        + +
      • A "read" method for each tag you're interested in. For example, +readEntry(), readTitle(), and so on. The parser reads +tags from the input stream. When it encounters a tag named entry, +title, +link or summary, it calls the appropriate method +for that tag. Otherwise, it skips the tag. +
      • + +
      • Methods to extract data for each different type of tag and to advance the +parser to the next tag. For example: +
          + +
        • For the title and summary tags, the parser calls +readText(). This method extracts data for these tags by calling +parser.getText().
        • + +
        • For the link tag, the parser extracts data for links by first +determining if the link is the kind +it's interested in. Then it uses parser.getAttributeValue() to +extract the link's value.
        • + +
        • For the entry tag, the parser calls readEntry(). +This method parses the entry's nested tags and returns an Entry +object with the data members title, link, and +summary.
        • + +
        +
      • +
      • A helper skip() method that's recursive. For more discussion of this topic, see Skip Tags You Don't Care About.
      • +
      + +
    4. +
    + +

    This snippet shows how the parser parses entries, titles, links, and summaries.

    +
    public static class Entry {
    +    public final String title;
    +    public final String link;
    +    public final String summary;
    +
    +    private Entry(String title, String summary, String link) {
    +        this.title = title;
    +        this.summary = summary;
    +        this.link = link;
    +    }
    +}
    +  
    +// Parses the contents of an entry. If it encounters a title, summary, or link tag, hands them off
    +// to their respective "read" methods for processing. Otherwise, skips the tag.
    +private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
    +    parser.require(XmlPullParser.START_TAG, ns, "entry");
    +    String title = null;
    +    String summary = null;
    +    String link = null;
    +    while (parser.next() != XmlPullParser.END_TAG) {
    +        if (parser.getEventType() != XmlPullParser.START_TAG) {
    +            continue;
    +        }
    +        String name = parser.getName();
    +        if (name.equals("title")) {
    +            title = readTitle(parser);
    +        } else if (name.equals("summary")) {
    +            summary = readSummary(parser);
    +        } else if (name.equals("link")) {
    +            link = readLink(parser);
    +        } else {
    +            skip(parser);
    +        }
    +    }
    +    return new Entry(title, summary, link);
    +}
    +
    +// Processes title tags in the feed.
    +private String readTitle(XmlPullParser parser) throws IOException, XmlPullParserException {
    +    parser.require(XmlPullParser.START_TAG, ns, "title");
    +    String title = readText(parser);
    +    parser.require(XmlPullParser.END_TAG, ns, "title");
    +    return title;
    +}
    +  
    +// Processes link tags in the feed.
    +private String readLink(XmlPullParser parser) throws IOException, XmlPullParserException {
    +    String link = "";
    +    parser.require(XmlPullParser.START_TAG, ns, "link");
    +    String tag = parser.getName();
    +    String relType = parser.getAttributeValue(null, "rel");  
    +    if (tag.equals("link")) {
    +        if (relType.equals("alternate")){
    +            link = parser.getAttributeValue(null, "href");
    +            parser.nextTag();
    +        } 
    +    }
    +    parser.require(XmlPullParser.END_TAG, ns, "link");
    +    return link;
    +}
    +
    +// Processes summary tags in the feed.
    +private String readSummary(XmlPullParser parser) throws IOException, XmlPullParserException {
    +    parser.require(XmlPullParser.START_TAG, ns, "summary");
    +    String summary = readText(parser);
    +    parser.require(XmlPullParser.END_TAG, ns, "summary");
    +    return summary;
    +}
    +
    +// For the tags title and summary, extracts their text values.
    +private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
    +    String result = "";
    +    if (parser.next() == XmlPullParser.TEXT) {
    +        result = parser.getText();
    +        parser.nextTag();
    +    }
    +    return result;
    +}
    +  ...
    +}
    + +

    Skip Tags You Don't Care About

    + +

    One of the steps in the XML parsing described above is for the parser to skip tags it's not interested in. Here is the parser's skip() method:

    + +
    +private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
    +    if (parser.getEventType() != XmlPullParser.START_TAG) {
    +        throw new IllegalStateException();
    +    }
    +    int depth = 1;
    +    while (depth != 0) {
    +        switch (parser.next()) {
    +        case XmlPullParser.END_TAG:
    +            depth--;
    +            break;
    +        case XmlPullParser.START_TAG:
    +            depth++;
    +            break;
    +        }
    +    }
    + }
    +
    + +

    This is how it works:

    + +
      + +
    • It throws an exception if the current event isn't a +START_TAG.
    • + +
    • It consumes the START_TAG, and all events up to and including +the matching END_TAG.
    • + +
    • To make sure that it stops at the correct END_TAG and not at +the first tag it encounters after the original START_TAG, it keeps +track of the nesting depth.
    • + +
    + +

    Thus if the current element has nested elements, the value of +depth won't be 0 until the parser has consumed all events between +the original START_TAG and its matching END_TAG. For +example, consider how the parser skips the <author> element, +which has 2 nested elements, <name> and +<uri>:

    + +
      + +
    • The first time through the while loop, the next tag the parser +encounters after <author> is the START_TAG for +<name>. The value for depth is incremented to +2.
    • + +
    • The second time through the while loop, the next tag the parser +encounters is the END_TAG </name>. The value +for depth is decremented to 1.
    • + +
    • The third time through the while loop, the next tag the parser +encounters is the START_TAG <uri>. The value +for depth is incremented to 2.
    • + +
    • The fourth time through the while loop, the next tag the parser +encounters is the END_TAG </uri>. The value for +depth is decremented to 1.
    • + +
    • The fifth time and final time through the while loop, the next +tag the parser encounters is the END_TAG +</author>. The value for depth is decremented to +0, indicating that the <author> element has been successfully +skipped.
    • + +
    + +

    Consume XML Data

    + +

    The example application fetches and parses the XML feed within an {@link +android.os.AsyncTask}. This takes the processing off the main UI thread. When +processing is complete, the app updates the UI in the main activity +(NetworkActivity).

    +

    In the excerpt shown below, the loadPage() method does the +following:

    + +
      + +
    • Initializes a string variable with the URL for the XML feed.
    • + +
    • If the user's settings and the network connection allow it, invokes +new DownloadXmlTask().execute(url). This instantiates a new +DownloadXmlTask object ({@link android.os.AsyncTask} subclass) and +runs its {@link android.os.AsyncTask#execute execute()} method, which downloads +and parses the feed and returns a string result to be displayed in the UI.
    • + +
    +
    +public class NetworkActivity extends Activity {
    +    public static final String WIFI = "Wi-Fi";
    +    public static final String ANY = "Any";
    +    private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";
    +   
    +    // Whether there is a Wi-Fi connection.
    +    private static boolean wifiConnected = false; 
    +    // Whether there is a mobile connection.
    +    private static boolean mobileConnected = false;
    +    // Whether the display should be refreshed.
    +    public static boolean refreshDisplay = true; 
    +    public static String sPref = null;
    +
    +    ...
    +      
    +    // Uses AsyncTask to download the XML feed from stackoverflow.com.
    +    public void loadPage() {  
    +      
    +        if((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) {
    +            new DownloadXmlTask().execute(URL);
    +        }
    +        else if ((sPref.equals(WIFI)) && (wifiConnected)) {
    +            new DownloadXmlTask().execute(URL);
    +        } else {
    +            // show error
    +        }  
    +    }
    + +

    The {@link android.os.AsyncTask} subclass shown below, +DownloadXmlTask, implements the following {@link +android.os.AsyncTask} methods:

    + +
      + +
    • {@link android.os.AsyncTask#doInBackground doInBackground()} executes +the method loadXmlFromNetwork(). It passes the feed URL as a +parameter. The method loadXmlFromNetwork() fetches and processes +the feed. When it finishes, it passes back a result string.
    • + +
    • {@link android.os.AsyncTask#onPostExecute onPostExecute()} takes the +returned string and displays it in the UI.
    • + +
    + +
    +// Implementation of AsyncTask used to download XML feed from stackoverflow.com.
    +private class DownloadXmlTask extends AsyncTask<String, Void, String> {
    +    @Override
    +    protected String doInBackground(String... urls) {
    +        try {
    +            return loadXmlFromNetwork(urls[0]);
    +        } catch (IOException e) {
    +            return getResources().getString(R.string.connection_error);
    +        } catch (XmlPullParserException e) {
    +            return getResources().getString(R.string.xml_error);
    +        }
    +    }
    +
    +    @Override
    +    protected void onPostExecute(String result) {  
    +        setContentView(R.layout.main);
    +        // Displays the HTML string in the UI via a WebView
    +        WebView myWebView = (WebView) findViewById(R.id.webview);
    +        myWebView.loadData(result, "text/html", null);
    +    }
    +}
    + +

    Below is the method loadXmlFromNetwork() that is invoked from +DownloadXmlTask. It does the following:

    + +
      + +
    1. Instantiates a StackOverflowXmlParser. It also creates variables for +a {@link java.util.List} of Entry objects (entries), and +title, url, and summary, to hold the +values extracted from the XML feed for those fields.
    2. + +
    3. Calls downloadUrl(), which fetches the feed and returns it as + an {@link java.io.InputStream}.
    4. + +
    5. Uses StackOverflowXmlParser to parse the {@link java.io.InputStream}. + StackOverflowXmlParser populates a + {@link java.util.List} of entries with data from the feed.
    6. + +
    7. Processes the entries {@link java.util.List}, + and combines the feed data with HTML markup.
    8. + +
    9. Returns an HTML string that is displayed in the main activity +UI by the {@link android.os.AsyncTask} method {@link +android.os.AsyncTask#onPostExecute onPostExecute()}.
    10. + +
    + +
    +// Uploads XML from stackoverflow.com, parses it, and combines it with
    +// HTML markup. Returns HTML string.
    +private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
    +    InputStream stream = null;
    +    // Instantiate the parser
    +    StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
    +    List<Entry> entries = null;
    +    String title = null;
    +    String url = null;
    +    String summary = null;
    +    Calendar rightNow = Calendar.getInstance(); 
    +    DateFormat formatter = new SimpleDateFormat("MMM dd h:mmaa");
    +        
    +    // Checks whether the user set the preference to include summary text
    +    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    +    boolean pref = sharedPrefs.getBoolean("summaryPref", false);
    +        
    +    StringBuilder htmlString = new StringBuilder();
    +    htmlString.append("<h3>" + getResources().getString(R.string.page_title) + "</h3>");
    +    htmlString.append("<em>" + getResources().getString(R.string.updated) + " " + 
    +            formatter.format(rightNow.getTime()) + "</em>");
    +        
    +    try {
    +        stream = downloadUrl(urlString);        
    +        entries = stackOverflowXmlParser.parse(stream);
    +    // Makes sure that the InputStream is closed after the app is
    +    // finished using it.
    +    } finally {
    +        if (stream != null) {
    +            stream.close();
    +        } 
    +     }
    +    
    +    // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
    +    // Each Entry object represents a single post in the XML feed.
    +    // This section processes the entries list to combine each entry with HTML markup.
    +    // Each entry is displayed in the UI as a link that optionally includes
    +    // a text summary.
    +    for (Entry entry : entries) {       
    +        htmlString.append("<p><a href='");
    +        htmlString.append(entry.link);
    +        htmlString.append("'>" + entry.title + "</a></p>");
    +        // If the user set the preference to include summary text,
    +        // adds it to the display.
    +        if (pref) {
    +            htmlString.append(entry.summary);
    +        }
    +    }
    +    return htmlString.toString();
    +}
    +
    +// Given a string representation of a URL, sets up a connection and gets
    +// an input stream.
    +private InputStream downloadUrl(String urlString) throws IOException {
    +    URL url = new URL(urlString);
    +    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    +    conn.setReadTimeout(10000 /* milliseconds */);
    +    conn.setConnectTimeout(15000 /* milliseconds */);
    +    conn.setRequestMethod("GET");
    +    conn.setDoInput(true);
    +    // Starts the query
    +    conn.connect();
    +    InputStream stream = conn.getInputStream();      
    +}
    diff --git a/docs/html/training/basics/supporting-devices/languages.jd b/docs/html/training/basics/supporting-devices/languages.jd index fcc95c2a7f94..d83fbca28995 100644 --- a/docs/html/training/basics/supporting-devices/languages.jd +++ b/docs/html/training/basics/supporting-devices/languages.jd @@ -97,6 +97,10 @@ locale currently set for the user's device.

    </resources> +

    Note: You can use the locale qualifier (or any +configuration qualifer) on any resource type, such as if you want to provide +localized versions of your bitmap drawable. For more information, see Localization.

    Use the String Resources

    diff --git a/docs/html/training/basics/supporting-devices/platforms.jd b/docs/html/training/basics/supporting-devices/platforms.jd index 0d4e7d98303a..04872a342a9c 100644 --- a/docs/html/training/basics/supporting-devices/platforms.jd +++ b/docs/html/training/basics/supporting-devices/platforms.jd @@ -21,9 +21,9 @@ previous.link=screens.html

    You should also read

    @@ -34,7 +34,7 @@ lesson shows you how to take advantage of the latest APIs while continuing to su versions as well.

    The dashboard for Platform Versions +href="http://developer.android.com/about/dashboards/index.html">Platform Versions is updated regularly to show the distribution of active devices running each version of Android, based on the number of devices that visit the Google Play Store. Generally, it’s a good practice to support about 90% of the active devices, while @@ -42,7 +42,7 @@ targeting your app to the latest version.

    Tip: In order to provide the best features and functionality across several Android versions, you should use the Android Support Library in your app, +href="{@docRoot}tools/extras/support-library.html">Android Support Library in your app, which allows you to use several recent platform APIs on older versions.

    diff --git a/docs/html/training/camera/index.jd b/docs/html/training/camera/index.jd index d209c7e41186..282bed8d8b08 100644 --- a/docs/html/training/camera/index.jd +++ b/docs/html/training/camera/index.jd @@ -21,7 +21,7 @@ next.link=photobasics.html

    You should also read

    diff --git a/docs/html/training/camera/photobasics.jd b/docs/html/training/camera/photobasics.jd index 3420918c20a1..8fa6d67b0aa3 100644 --- a/docs/html/training/camera/photobasics.jd +++ b/docs/html/training/camera/photobasics.jd @@ -25,7 +25,7 @@ next.link=videobasics.html

    You should also read

    diff --git a/docs/html/training/camera/videobasics.jd b/docs/html/training/camera/videobasics.jd index 5fe1a3a367fe..d011d09392b2 100644 --- a/docs/html/training/camera/videobasics.jd +++ b/docs/html/training/camera/videobasics.jd @@ -24,7 +24,7 @@ next.link=cameradirect.html

    You should also read

    diff --git a/docs/html/training/custom-views/create-view.jd b/docs/html/training/custom-views/create-view.jd new file mode 100644 index 000000000000..b0bc8b478245 --- /dev/null +++ b/docs/html/training/custom-views/create-view.jd @@ -0,0 +1,281 @@ +page.title=Creating a View Class +parent.title=Creating Custom Views +parent.link=index.html + +trainingnavtop=true +next.title=Custom Drawing +next.link=custom-drawing.html + +@jd:body + +
    +
    + +

    This lesson teaches you to

    +
      +
    1. Subclass a View
    2. +
    3. Define Custom Attributes
    4. +
    5. Apply Custom Attributes to a View
    6. +
    7. Add Properties and Events
    8. +
    9. Design For Accessibility
    10. +
    + +

    You should also read

    + +

    Try it out

    +
    +Download the sample +

    CustomView.zip

    +
    +
    +
    + +

    A well-designed custom view is much like any other well-designed class. It encapsulates a +specific set of +functionality with an easy to use interface, it uses CPU and memory efficiently, and so forth. In +addition to being a +well-designed class, though, a custom view should: + +

      +
    • Conform to Android standards
    • +
    • Provide custom styleable attributes that work with Android XML layouts
    • +
    • Send accessibility events
    • +
    • Be compatible with multiple Android platforms.
    • +
    + +

    The Android framework provides a set of base classes and XML tags to help you create a view that + meets all of these + requirements. This lesson discusses how to use the Android framework to create the core + functionality of a view + class.

    + +

    Subclass a View

    + +

    All of the view classes defined in the Android framework extend {@link android.view.View}. Your + custom view can also + extend {@link android.view.View View} directly, or you can save time by extending one of the + existing view + subclasses, such as {@link android.widget.Button}.

    + +

    To allow the Android Developer Tools + to interact with your view, at a minimum you must provide a constructor that takes a +{@link android.content.Context} and an {@link android.util.AttributeSet} object as parameters. +This constructor allows the layout editor to create and edit an instance of your view.

    + +
    +class PieChart extends View {
    +    public PieChart(Context ctx, AttributeSet attrs) {
    +        super(ctx, attrs);
    +    }
    +}
    +
    + +

    Define Custom Attributes

    + +

    To add a built-in {@link android.view.View View} to your user interface, you specify it in an XML element and +control its +appearance and behavior with element attributes. Well-written custom views can also be added and +styled via XML. To +enable this behavior in your custom view, you must: + +

      +
    • Define custom attributes for your view in a {@code + <declare-styleable> + } resource element +
    • +
    • Specify values for the attributes in your XML layout
    • +
    • Retrieve attribute values at runtime
    • +
    • Apply the retrieved attribute values to your view
    • +
    + +

    This section discusses how to define custom attributes and specify their values. + The next section deals with + retrieving and applying the values at runtime.

    + +

    To define custom attributes, add {@code + <declare-styleable> + } resources to your project. It's customary to put these resources into a {@code + res/values/attrs.xml} file. Here's + an example of an {@code attrs.xml} file: +

    + +
    +<resources>;
    +   <declare-styleable name="PieChart">
    +       <attr name="showText" format="boolean" />
    +       <attr name="labelPosition" format="enum">
    +           <enum name="left" value="0"/>
    +           <enum name="right" value="1"/>
    +       </attr>
    +   </declare-styleable>
    +</resources>
    +
    + +

    This code declares two custom attributes, {@code showText} and {@code labelPosition}, that belong + to a styleable + entity named {@code PieChart}. The name of the styleable entity is, by convention, the same name as the + name of the class + that defines the custom view. Although it's not strictly necessary to follow this convention, + many popular code + editors depend on this naming convention to provide statement completion.

    + +

    Once you define the custom attributes, you can use them in layout XML files just like built-in + attributes. The only + difference is that your custom attributes belong to a different namespace. Instead of belonging + to the {@code + http://schemas.android.com/apk/res/android} namespace, they belong to {@code + http://schemas.android.com/apk/res/[your package name]}. For example, here's how to use the + attributes defined for + {@code PieChart}: +

    + +

    +<?xml version="1.0" encoding="utf-8"?>
    +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +   xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
    + <com.example.customviews.charting.PieChart
    +     custom:showText="true"
    +     custom:labelPosition="left" />
    +</LinearLayout>
    +
    + +

    In order to avoid having to repeat the long namespace URI, the sample uses an {@code + xmlns} directive. This + directive assigns the alias {@code custom} to the namespace {@code + http://schemas.android.com/apk/res/com.example.customviews}. You can choose any alias + you want for your + namespace.

    + +

    Notice the name of the XML tag that adds the custom view to the layout. It is the fully + qualified name of the + custom view class. If your view class is an inner class, you must further qualify it with the name of the view's outer class. + further. For instance, the + {@code PieChart} class has an inner class called {@code PieView}. To use the custom attributes from this class, you would + use the tag {@code com.example.customviews.charting.PieChart$PieView}.

    + +

    Apply Custom Attributes

    + +

    When a view is created from an XML layout, all of the attributes in the XML tag are read + from the resource + bundle and passed into the view's constructor as an {@link android.util.AttributeSet}. + Although it's + possible to read values from the {@link android.util.AttributeSet} directly, doing so + has some disadvantages:

    + +
      +
    • Resource references within attribute values are not resolved
    • +
    • Styles are not applied
    • +
    + +

    Instead, pass the {@link android.util.AttributeSet} to {@link + android.content.res.Resources.Theme#obtainStyledAttributes obtainStyledAttributes()}. + This method passes back a {@link android.content.res.TypedArray TypedArray} array of + values that have + already been dereferenced and styled.

    + +

    The Android resource compiler does a lot of work for you to make calling {@link + android.content.res.Resources.Theme#obtainStyledAttributes obtainStyledAttributes()} + easier. For each {@code <declare-styleable>} + resource in the res directory, the generated R.java defines both an array of attribute + ids and a set of + constants that define the index for each attribute in the array. You use the predefined + constants to read + the attributes from the {@link android.content.res.TypedArray TypedArray}. Here's how + the {@code PieChart} class + reads its attributes:

    + +
    +public PieChart(Context ctx, AttributeSet attrs) {
    +   super(ctx, attrs);
    +   TypedArray a = context.getTheme().obtainStyledAttributes(
    +        attrs,
    +        R.styleable.PieChart,
    +        0, 0);
    +
    +   try {
    +       mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
    +       mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
    +   } finally {
    +       a.recycle();
    +   }
    +}
    +
    + +

    Note that {@link android.content.res.TypedArray TypedArray} objects + are a shared resource + and must be recycled after use.

    + +

    Add Properties and Events

    + +

    Attributes are a powerful way of controlling the behavior and appearance of views, but + they can only be read + when the view is initialized. To provide dynamic behavior, expose a property getter and + setter pair for each + custom attribute. The following snippet shows how {@code PieChart} exposes a property + called {@code + showText}:

    + +
    +public boolean isShowText() {
    +   return mShowText;
    +}
    +
    +public void setShowText(boolean showText) {
    +   mShowText = showText;
    +   invalidate();
    +   requestLayout();
    +}
    +
    + +

    Notice that {@code setShowText} calls {@link android.view.View#invalidate invalidate()} + and {@link android.view.View#requestLayout requestLayout()}. These calls are crucial + to ensure that the view behaves reliably. You have + to invalidate the view after any change to its properties that might change its + appearance, so that the + system knows that it needs to be redrawn. Likewise, you need to request a new layout if + a property changes + that might affect the size or shape of the view. Forgetting these method calls can cause + hard-to-find + bugs.

    + +

    Custom views should also support event listeners to communicate important events. For + instance, {@code PieChart} + exposes a custom event called {@code OnCurrentItemChanged} to notify listeners that the + user has rotated the + pie chart to focus on a new pie slice.

    + +

    It's easy to forget to expose properties and events, especially when you're the only user + of the custom view. + Taking some time to carefully define your view's interface reduces future maintenance + costs. + A good rule to follow is to always expose any property that affects the visible + appearance or behavior of + your custom view. + +

    Design For Accessibility

    + +

    Your custom view should support the widest range of users. This includes users with + disabilities that + prevent them from seeing or using a touchscreen. To support users with disabilities, + you should:

    + +
      +
    • Label your input fields using the {@code android:contentDescription} attribute +
    • +
    • Send accessibility events by calling {@link + android.view.accessibility.AccessibilityEventSource#sendAccessibilityEvent + sendAccessibilityEvent()} when + appropriate. +
    • +
    • + Support alternate controllers, such as D-pad and trackball
    • +
    + +

    For more information on creating accessible views, see + + Making Applications Accessible in the Android Developers Guide. +

    diff --git a/docs/html/training/custom-views/custom-drawing.jd b/docs/html/training/custom-views/custom-drawing.jd new file mode 100644 index 000000000000..8280237167bb --- /dev/null +++ b/docs/html/training/custom-views/custom-drawing.jd @@ -0,0 +1,284 @@ +page.title=Custom Drawing +parent.title=Creating Custom Views +parent.link=index.html + +trainingnavtop=true +previous.title=Creating a View Class +previous.link=create-view.html +next.title=Making the View Interactive +next.link=making-interactive.html + +@jd:body + +
    +
    + +

    This lesson teaches you to

    +
      +
    1. Override onDraw()
    2. +
    3. Create Drawing Objects
    4. +
    5. Handle Layout Events
    6. +
    7. Draw!
    8. +
    + +

    You should also read

    + +

    Try it out

    +
    +Download the sample +

    CustomView.zip

    +
    +
    +
    + +

    The most important part of a custom view is its appearance. Custom drawing can be easy or complex +according to your +application's needs. This lesson covers some of the most common operations.

    + +

    Override onDraw()

    + +

    The most important step in drawing a custom view is to override the {@link +android.view.View#onDraw(android.graphics.Canvas) onDraw()} method. The parameter to {@link +android.view.View#onDraw(android.graphics.Canvas) onDraw()} is a {@link +android.graphics.Canvas Canvas} object that the view can use to draw itself. The {@link +android.graphics.Canvas Canvas} +class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can +use these methods in +{@link +android.view.View#onDraw(android.graphics.Canvas) onDraw()} to create your custom user interface (UI).

    + +

    Before you can call any drawing methods, though, it's necessary to create a {@link +android.graphics.Paint Paint} +object. The next section discusses {@link android.graphics.Paint Paint} in more detail.

    + +

    Create Drawing Objects

    + +

    The {@link android.graphics} framework divides drawing into two areas:

    + +
      +
    • What to draw, handled by {@link android.graphics.Canvas Canvas}
    • +
    • How to draw, handled by {@link android.graphics.Paint}.
    • +
    + +

    For instance, {@link android.graphics.Canvas Canvas} provides a method to draw a line, while +{@link +android.graphics.Paint Paint} provides methods to define that line's color. {@link +android.graphics.Canvas Canvas} has a +method to draw a rectangle, while {@link android.graphics.Paint Paint} defines whether to fill that +rectangle with a +color or leave it empty. Simply put, {@link android.graphics.Canvas Canvas} defines shapes that you +can draw on the +screen, while {@link android.graphics.Paint Paint} defines the color, style, font, and so forth of +each shape you +draw.

    + +

    So, before you draw anything, you need to create one or more {@link android.graphics.Paint Paint} +objects. The {@code PieChart} example does this in a method called {@code init}, which is +called from the +constructor:

    + +
    +private void init() {
    +   mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    +   mTextPaint.setColor(mTextColor);
    +   if (mTextHeight == 0) {
    +       mTextHeight = mTextPaint.getTextSize();
    +   } else {
    +       mTextPaint.setTextSize(mTextHeight);
    +   }
    +
    +   mPiePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    +   mPiePaint.setStyle(Paint.Style.FILL);
    +   mPiePaint.setTextSize(mTextHeight);
    +
    +   mShadowPaint = new Paint(0);
    +   mShadowPaint.setColor(0xff101010);
    +   mShadowPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));
    +
    +   ...
    +
    + + +

    Creating objects ahead of time is an important optimization. Views are redrawn very frequently, +and many drawing +objects require expensive initialization. Creating drawing objects within your {@link +android.view.View#onDraw(android.graphics.Canvas) onDraw()} +method significantly +reduces performance and can make your UI appear sluggish.

    + +

    Handle Layout Events

    + +

    In order to properly draw your custom view, you need to know what size it is. Complex custom +views often need to +perform multiple layout calculations depending on the size and shape of their area on screen. You +should never make +assumptions about the size of your view on the screen. Even if only one app uses your view, that app +needs to handle +different screen sizes, multiple screen densities, and various aspect ratios in both portrait and +landscape mode.

    + +

    Although {@link android.view.View} has many methods for handling measurement, most of them do not +need to be +overridden. If your view doesn't need special control over its size, you only need to override one +method: {@link +android.view.View#onSizeChanged onSizeChanged()}.

    + +

    {@link +android.view.View#onSizeChanged onSizeChanged()} is called when your view is first assigned a size, +and again if the size of your view changes +for any reason. Calculate positions, dimensions, and any other values related to your view's size in +{@link +android.view.View#onSizeChanged onSizeChanged()}, instead of recalculating them every time you draw. +In the {@code PieChart} example, {@link +android.view.View#onSizeChanged onSizeChanged()} is +where the {@code PieChart} view calculates the bounding rectangle of the pie chart and the relative position +of the text label +and other visual elements.

    + +

    When your view is assigned a size, the layout manager assumes that the size includes all of the +view's padding. You +must handle the padding values when you calculate your view's size. Here's a snippet from {@code +PieChart.onSizeChanged()} +that shows how to do this:

    + +
    +       // Account for padding
    +       float xpad = (float)(getPaddingLeft() + getPaddingRight());
    +       float ypad = (float)(getPaddingTop() + getPaddingBottom());
    +
    +       // Account for the label
    +       if (mShowText) xpad += mTextWidth;
    +
    +       float ww = (float)w - xpad;
    +       float hh = (float)h - ypad;
    +
    +       // Figure out how big we can make the pie.
    +       float diameter = Math.min(ww, hh);
    +
    + +

    If you need finer control over your view's layout parameters, implement {@link +android.view.View#onMeasure onMeasure()}. This method's parameters are +{@link android.view.View.MeasureSpec} values that tell you how big your view's +parent wants your view to be, and whether that size is a hard maximum or just a suggestion. As an +optimization, these +values are stored as packed integers, and you use the static methods of +{@link android.view.View.MeasureSpec} to +unpack the information +stored in each integer. + +

    Here's an example implementation of {@link android.view.View#onMeasure onMeasure()}. + In this implementation, {@code PieChart} + attempts to make its area + big enough to make the pie as big as its label:

    + +
    +@Override
    +protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    +   // Try for a width based on our minimum
    +   int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
    +   int w = resolveSizeAndState(minw, widthMeasureSpec, 1);
    +
    +   // Whatever the width ends up being, ask for a height that would let the pie
    +   // get as big as it can
    +   int minh = MeasureSpec.getSize(w) - (int)mTextWidth + getPaddingBottom() + getPaddingTop();
    +   int h = resolveSizeAndState(MeasureSpec.getSize(w) - (int)mTextWidth, heightMeasureSpec, 0);
    +
    +   setMeasuredDimension(w, h);
    +}
    +
    + +

    There are three important things to note in this code:

    + +
      +
    • The calculations take into account the view's padding. As mentioned earlier, this is the + view's + responsibility. +
    • +
    • The helper method {@link android.view.View#resolveSizeAndState resolveSizeAndState()} is + used to create the + final width and height values. This helper returns an appropriate + {@link android.view.View.MeasureSpec} value + by comparing the view's desired size to the spec passed into + {@link android.view.View#onMeasure onMeasure()}. +
    • +
    • {@link android.view.View#onMeasure onMeasure()} has no return value. + Instead, the method communicates its results by + calling {@link + android.view.View#setMeasuredDimension setMeasuredDimension()}. Calling this method is + mandatory. If you omit + this call, the {@link android.view.View} class throws a runtime exception. +
    • +
    + +

    Draw!

    + +

    Once you have your object creation and measuring code defined, you can implement {@link + android.view.View#onDraw(android.graphics.Canvas) onDraw()}. Every view + implements {@link + android.view.View#onDraw(android.graphics.Canvas) onDraw()} + differently, but there are some common operations that most views + share:

    + +
      +
    • Draw text using {@link android.graphics.Canvas#drawText drawText()}. Specify the typeface by + calling {@link + android.graphics.Paint#setTypeface setTypeface()}, and the text color by calling {@link + android.graphics.Paint#setColor setColor()}. +
    • +
    • Draw primitive shapes using {@link android.graphics.Canvas#drawRect drawRect()}, {@link + android.graphics.Canvas#drawOval drawOval()}, and {@link android.graphics.Canvas#drawArc + drawArc()}. Change + whether the shapes are filled, outlined, or both by calling {@link + android.graphics.Paint#setStyle(android.graphics.Paint.Style) setStyle()}. +
    • +
    • Draw more complex shapes using the {@link android.graphics.Path} class. + Define a shape by adding lines and curves to a + {@link + android.graphics.Path} object, then draw the shape using {@link + android.graphics.Canvas#drawPath drawPath()}. + Just as with primitive shapes, paths can be outlined, filled, or both, depending on the + {@link android.graphics.Paint#setStyle + setStyle()}. +
    • +
    • + Define gradient fills by creating {@link android.graphics.LinearGradient} objects. Call {@link + android.graphics.Paint#setShader setShader()} to use your + {@link android.graphics.LinearGradient} on filled + shapes. +
    • Draw bitmaps using {@link android.graphics.Canvas#drawBitmap drawBitmap()}.
    • +
    + +

    For example, here's the code that draws {@code PieChart}. It uses a mix of text, lines, and shapes.

    + +
    +protected void onDraw(Canvas canvas) {
    +   super.onDraw(canvas);
    +
    +   // Draw the shadow
    +   canvas.drawOval(
    +           mShadowBounds,
    +           mShadowPaint
    +   );
    +
    +   // Draw the label text
    +   canvas.drawText(mData.get(mCurrentItem).mLabel, mTextX, mTextY, mTextPaint);
    +
    +   // Draw the pie slices
    +   for (int i = 0; i < mData.size(); ++i) {
    +       Item it = mData.get(i);
    +       mPiePaint.setShader(it.mShader);
    +       canvas.drawArc(mBounds,
    +               360 - it.mEndAngle,
    +               it.mEndAngle - it.mStartAngle,
    +               true, mPiePaint);
    +   }
    +
    +   // Draw the pointer
    +   canvas.drawLine(mTextX, mPointerY, mPointerX, mPointerY, mTextPaint);
    +   canvas.drawCircle(mPointerX, mPointerY, mPointerSize, mTextPaint);
    +}
    +
    diff --git a/docs/html/training/custom-views/index.jd b/docs/html/training/custom-views/index.jd new file mode 100644 index 000000000000..0661c053fc90 --- /dev/null +++ b/docs/html/training/custom-views/index.jd @@ -0,0 +1,79 @@ +page.title=Creating Custom Views + +trainingnavtop=true +startpage=true +next.title=Creating a View Class +next.link=create-view.html + +@jd:body + +
    +
    + +

    Dependencies and prerequisites

    +
      +
    • Android 2.1 (API level 7) or higher
    • +
    + +

    You should also read

    + +

    Try it out

    +
    +Download the sample +

    CustomView.zip

    +
    +
    +
    + +

    +The Android framework has a large set of {@link android.view.View} classes for +interacting with the user and displaying various +types of data. But +sometimes your app has unique needs that aren’t covered by the built-in views. This class shows you +how to create your +own views that are robust and reusable.

    + +

    Lessons

    + +
    +
    Creating a View Class
    +
    Create a class that acts like a built-in view, with custom + attributes and support from the ADT layout editor. +
    + +
    Custom Drawing
    +
    Make your view visually distinctive using the Android graphics system.
    + +
    Making the View Interactive
    +
    Users expect a view to react smoothly and naturally to input gestures. + This lesson discusses how to use gesture detection, physics, and animation + to give your user interface a professional feel. +
    + +
    Optimizing the View
    +
    No matter how beautiful your UI is, users won't love it if it + doesn't run at a consistently high frame rate. Learn how to avoid common + performance problems, and how to use hardware acceleration to make your + custom drawings run faster. +
    + +
    + + + + + + + + diff --git a/docs/html/training/custom-views/making-interactive.jd b/docs/html/training/custom-views/making-interactive.jd new file mode 100644 index 000000000000..4e9d53a5e773 --- /dev/null +++ b/docs/html/training/custom-views/making-interactive.jd @@ -0,0 +1,292 @@ +page.title=Making the View Interactive +parent.title=Creating Custom Views +parent.link=index.html + +trainingnavtop=true +previous.title=Custom Drawing +previous.link=custom-drawing.html +next.title=Optmizing the View +next.link=optimizing-view.html + +@jd:body + +
    +
    + +

    This lesson teaches you to

    +
      +
    1. Handle Input Gestures
    2. +
    3. Create Physically Plausible Motion
    4. +
    5. Make Your Transitions Smooth
    6. +
    + +

    You should also read

    + +

    Try it out

    +
    +Download the sample +

    CustomView.zip

    +
    +
    +
    + +

    Drawing a UI is only one part of creating a custom view. You also need to make your view respond +to user input in a +way that closely resembles the real-world action you're mimicking. Objects should always act in the +same way that real +objects do. For example, images should not immediately pop out of existence and reappear somewhere +else, because objects +in the real world don't do that. Instead, images should move from one place to another.

    + +

    Users also sense subtle behavior or feel in an interface, and react best to subtleties that +mimic the real world. +For example, when users fling a UI object, they should sense friction at the beginning that delays +the motion, and then +at the end sense momentum that carries the motion beyond the fling.

    + +

    This lesson demonstrates how to use features of the Android framework to add these real-world +behaviors to your +custom view. + +

    Handle Input Gestures

    + +

    Like many other UI frameworks, Android supports an input event model. User actions are turned + into events that + trigger callbacks, and you can override the callbacks to customize how your application responds + to the user. The + most common input event in the Android system is touch, which triggers {@link + android.view.View#onTouchEvent(android.view.MotionEvent)}. Override this method to handle the + event:

    + +
    +   @Override
    +   public boolean onTouchEvent(MotionEvent event) {
    +    return super.onTouchEvent(event);
    +   }
    +
    + +

    Touch events by themselves are not particularly useful. Modern touch UIs define interactions in + terms of gestures + such as tapping, pulling, pushing, flinging, and zooming. To convert raw touch events into + gestures, Android + provides {@link android.view.GestureDetector}.

    + +

    Construct a {@link android.view.GestureDetector} by passing in an instance of a class that + implements {@link + android.view.GestureDetector.OnGestureListener}. If you only want to process a few gestures, you + can extend {@link + android.view.GestureDetector.SimpleOnGestureListener} instead of implementing the {@link + android.view.GestureDetector.OnGestureListener} + interface. For instance, this code creates a class that extends {@link + android.view.GestureDetector.SimpleOnGestureListener} and overrides {@link + android.view.GestureDetector.SimpleOnGestureListener#onDown}.

    + +
    +class mListener extends GestureDetector.SimpleOnGestureListener {
    +   @Override
    +   public boolean onDown(MotionEvent e) {
    +       return true;
    +   }
    +}
    +mDetector = new GestureDetector(PieChart.this.getContext(), new mListener());
    +
    + +

    Whether or not you use {@link + android.view.GestureDetector.SimpleOnGestureListener}, you must always implement an + {@link android.view.GestureDetector.OnGestureListener#onDown onDown()} method that + returns {@code true}. This step is necessary because all gestures begin with an + {@link android.view.GestureDetector.OnGestureListener#onDown onDown()} message. If + you return {@code + false} from {@link android.view.GestureDetector.OnGestureListener#onDown onDown()}, as + {@link android.view.GestureDetector.SimpleOnGestureListener} does, the system assumes that + you want to ignore the + rest of the gesture, and the other methods of + {@link android.view.GestureDetector.OnGestureListener} never get called. The + only time you should + return {@code false} from {@link android.view.GestureDetector.OnGestureListener#onDown onDown()} + is if you truly want to ignore an entire gesture. + + Once you've implemented {@link android.view.GestureDetector.OnGestureListener} + and created an instance of {@link android.view.GestureDetector}, you can use + your {@link android.view.GestureDetector} to interpret the touch events you receive in {@link + android.view.GestureDetector#onTouchEvent onTouchEvent()}.

    + +
    +@Override
    +public boolean onTouchEvent(MotionEvent event) {
    +   boolean result = mDetector.onTouchEvent(event);
    +   if (!result) {
    +       if (event.getAction() == MotionEvent.ACTION_UP) {
    +           stopScrolling();
    +           result = true;
    +       }
    +   }
    +   return result;
    +}
    +
    + +

    When you pass {@link android.view.GestureDetector#onTouchEvent onTouchEvent()} a touch event that + it doesn't + recognize as part of a gesture, it returns {@code false}. You can then run your own custom + gesture-detection + code.

    + +

    Create Physically Plausible Motion

    + +

    Gestures are a powerful way to control touchscreen devices, but they can be counterintuitive and + difficult to + remember unless they produce physically plausible results. A good example of this is the fling + gesture, where the + user quickly moves a finger across the screen and then lifts it. This gesture makes sense if the UI + responds by moving + quickly in the direction of the fling, then slowing down, as if the user had pushed on a + flywheel and set it + spinning.

    + +

    However, simulating the feel of a flywheel isn't trivial. A lot of physics and math are required + to get a flywheel + model working correctly. Fortunately, Android provides helper classes to simulate this and other + behaviors. The + {@link android.widget.Scroller} class is the basis for handling flywheel-style fling + gestures.

    + +

    To start a fling, call {@link android.widget.Scroller#fling fling()} with the starting velocity + and the minimum and + maximum x and y values of the fling. For the velocity value, you can use the value computed for + you by {@link android.view.GestureDetector}.

    + +
    +@Override
    +public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    +   mScroller.fling(currentX, currentY, velocityX / SCALE, velocityY / SCALE, minX, minY, maxX, maxY);
    +   postInvalidate();
    +}
    +
    + +

    Note: Although the velocity calculated by + {@link android.view.GestureDetector} is physically accurate, + many developers feel + that using this value makes the fling animation too fast. It's common to divide the x and y + velocity by a factor of + 4 to 8.

    + +

    The call to {@link android.widget.Scroller#fling fling()} sets up the physics model for the fling + gesture. + Afterwards, you need to update the {@link android.widget.Scroller Scroller} by calling {@link + android.widget.Scroller#computeScrollOffset Scroller.computeScrollOffset()} at regular + intervals. {@link + android.widget.Scroller#computeScrollOffset computeScrollOffset()} updates the {@link + android.widget.Scroller + Scroller} object's internal state by reading the current time and using the physics model to calculate + the x and y position + at that time. Call {@link android.widget.Scroller#getCurrX} and {@link + android.widget.Scroller#getCurrY} to + retrieve these values.

    + +

    Most views pass the {@link android.widget.Scroller Scroller} object's x and y position directly to + {@link + android.view.View#scrollTo scrollTo()}. The PieChart example is a little different: it + uses the current scroll + y position to set the rotational angle of the chart.

    + +
    +if (!mScroller.isFinished()) {
    +    mScroller.computeScrollOffset();
    +    setPieRotation(mScroller.getCurrY());
    +}
    +
    + +

    The {@link android.widget.Scroller Scroller} class computes scroll positions for you, but it does + not automatically + apply those positions to your view. It's your responsibility to make sure you get and apply new + coordinates often + enough to make the scrolling animation look smooth. There are two ways to do this:

    + +
      +
    • Call {@link android.view.View#postInvalidate() postInvalidate()} after calling + {@link android.widget.Scroller#fling(int, int, int, int, int, int, int, int) fling()}, + in order to + force a redraw. This + technique requires that you compute scroll offsets in {@link android.view.View#onDraw onDraw()} + and call {@link android.view.View#postInvalidate() postInvalidate()} every + time the scroll offset changes. +
    • +
    • Set up a {@link android.animation.ValueAnimator} to animate for the duration of the fling, + and add a listener to process animation updates + by calling {@link android.animation.ValueAnimator#addUpdateListener addUpdateListener()}. +
    • +
    + +

    The PieChart example uses the second approach. This technique is slightly more complex to set up, but + it works more + closely with the animation system and doesn't require potentially unnecessary view + invalidation. The drawback is that {@link android.animation.ValueAnimator} + is not available prior to API level 11, so this technique cannot be used +on devices running Android versions lower than 3.0.

    + +

    Note: {@link android.animation.ValueAnimator} isn't available + prior to API level 11, but you can still use it in applications that +target lower API levels. You just need to make sure to check the current API level +at runtime, and omit the calls to the view animation system if the current level is less than 11.

    + +
    +       mScroller = new Scroller(getContext(), null, true);
    +       mScrollAnimator = ValueAnimator.ofFloat(0,1);
    +       mScrollAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    +           @Override
    +           public void onAnimationUpdate(ValueAnimator valueAnimator) {
    +               if (!mScroller.isFinished()) {
    +                   mScroller.computeScrollOffset();
    +                   setPieRotation(mScroller.getCurrY());
    +               } else {
    +                   mScrollAnimator.cancel();
    +                   onScrollFinished();
    +               }
    +           }
    +       });
    +
    + +

    Make Your Transitions Smooth

    + +

    Users expect a modern UI to transition smoothly between states. UI elements fade in and out + instead of appearing and + disappearing. Motions begin and end smoothly instead of starting and stopping abruptly. The + Android property animation + framework, introduced in + Android 3.0, makes smooth transitions easy.

    + +

    To use the animation system, whenever a property changes that will affect your view's appearance, + do not change the + property directly. Instead, use {@link android.animation.ValueAnimator} to make the change. In + the following + example, modifying the + currently selected pie slice in PieChart causes the entire chart to rotate so that the selection + pointer is centered + in the selected slice. {@link android.animation.ValueAnimator} changes the rotation over a + period of several + hundred milliseconds, + rather than immediately setting the new rotation value.

    + +
    +mAutoCenterAnimator = ObjectAnimator.ofInt(PieChart.this, "PieRotation", 0);
    +mAutoCenterAnimator.setIntValues(targetAngle);
    +mAutoCenterAnimator.setDuration(AUTOCENTER_ANIM_DURATION);
    +mAutoCenterAnimator.start();
    +
    + +

    If the value you want to change is one of the base {@link android.view.View} properties, doing + the animation + is even easier, + because Views have a built-in {@link android.view.ViewPropertyAnimator} that is optimized for + simultaneous animation + of multiple properties. For example:

    + +
    +animate().rotation(targetAngle).setDuration(ANIM_DURATION).start();
    +
    diff --git a/docs/html/training/custom-views/optimizing-view.jd b/docs/html/training/custom-views/optimizing-view.jd new file mode 100644 index 000000000000..1f489dd2db1b --- /dev/null +++ b/docs/html/training/custom-views/optimizing-view.jd @@ -0,0 +1,176 @@ +page.title=Optimizing the View +parent.title=Creating Custom Views +parent.link=index.html + +trainingnavtop=true +previous.title=Making the View Interactive +previous.link=making-interactive.html + +@jd:body + +
    +
    + +

    This lesson teaches you to

    +
      +
    1. Do Less, Less Frequently
    2. +
    3. Use Hardware Acceleration
    4. +
    + +

    You should also read

    + +

    Try it out

    +
    +Download the sample +

    CustomView.zip

    +
    +
    +
    + + +

    Now that you have a well-designed view that responds to gestures and transitions between states, +you need to ensure +that the view runs fast. To avoid a UI that feels sluggish or stutters during playback, you must +ensure that your +animations consistently run at 60 frames per second.

    + +

    Do Less, Less Frequently

    + +

    To speed up your view, eliminate unnecessary code from routines that are called frequently. Start +by working on +{@link android.view.View#onDraw onDraw()}, which will give you the biggest payback. In particular +you should eliminate +allocations in {@link android.view.View#onDraw onDraw()}, because allocations may lead to a garbage +collection that +would cause a stutter. Allocate objects during initialization, or between animations. Never make an +allocation while an +animation is running.

    + +

    In addition to making {@link android.view.View#onDraw onDraw()} leaner, you should also make sure +it's called as +infrequently as possible. Most calls to {@link android.view.View#onDraw onDraw()} are the result of +a call to {@link +android.view.View#invalidate() invalidate()}, so eliminate unnecessary calls to {@link +android.view.View#invalidate() +invalidate()}. When possible, call the four-parameter variant of {@link +android.view.View#invalidate() invalidate()} +rather than the version that takes no parameters. The no-parameter variant invalidates the entire +view, while the +four-parameter variant invalidates only a specified portion of the view. This approach allows draw calls to +be more efficient and +can eliminate unnecessary invalidation of views that fall outside the invalid rectangle.

    + +

    Another very expensive operation is traversing layouts. Any time a view calls {@link +android.view.View#requestLayout() +requestLayout()}, the Android UI system needs to traverse the entire view hierarchy to find out how +big each view needs +to be. If it finds conflicting measurements, it may need to traverse the hierarchy multiple times. +UI designers +sometimes create deep hierarchies of nested {@link android.view.ViewGroup ViewGroup} objects in +order to get the UI to +behave properly. These deep view hierarchies cause performance problems. Make your view hierarchies +as shallow as +possible.

    + +

    If you have a complex UI, you should consider writing a custom {@link android.view.ViewGroup +ViewGroup} to perform +its layout. Unlike the built-in views, your custom view can make application-specific assumptions +about the size and +shape of its children, and thus avoid traversing its children to calculate measurements. The +PieChart example shows how +to extend {@link android.view.ViewGroup ViewGroup} as part of a custom view. PieChart has child +views, but it never +measures them. Instead, it sets their sizes directly according to its own custom layout +algorithm.

    + +

    Use Hardware Acceleration

    + +

    As of Android 3.0, the Android 2D graphics system can be accelerated by the GPU (Graphics +Processing Unit) hardware +found in most newer Android devices. GPU hardware acceleration can result in a tremendous +performance increase for many +applications, but it isn't the right choice for every application. The Android framework +gives you the ability to finely control which parts of your application are or are not +hardware accelerated.

    + +

    See Hardware Acceleration + in the Android Developers Guide for directions on how to enable acceleration at the + application, activity, or window level. Notice that in addition to the directions in + the developer guide, you must also set your application's target API to 11 or higher by + specifying {@code <uses-sdk + android:targetSdkVersion="11"/>} in your {@code AndroidManifest.xml} file.

    + +

    Once you've enabled hardware acceleration, you may or may not see a performance increase. +Mobile GPUs are very good at certain tasks, such as scaling, rotating, and translating +bitmapped images. They are not particularly good at other tasks, such as drawing lines or curves. To +get the most out of GPU acceleration, you should maximize the number of operations that the GPU is +good at, and minimize the number of operations that the GPU isn't good at.

    + +

    In the PieChart example, for instance, drawing the pie is relatively expensive. Redrawing the pie +each time it's +rotated causes the UI to feel sluggish. The solution is to place the pie chart into a child +{@link android.view.View} and set that +{@link android.view.View}'s + + layer type to {@link android.view.View#LAYER_TYPE_HARDWARE}, so that the GPU can cache it as +a static +image. The sample +defines the child view as an inner class of {@code PieChart}, which minimizes the amount of code +changes that are needed +to implement this solution.

    + +
    +   private class PieView extends View {
    +
    +       public PieView(Context context) {
    +           super(context);
    +           if (!isInEditMode()) {
    +               setLayerType(View.LAYER_TYPE_HARDWARE, null);
    +           }
    +       }
    +       
    +       @Override
    +       protected void onDraw(Canvas canvas) {
    +           super.onDraw(canvas);
    +
    +           for (Item it : mData) {
    +               mPiePaint.setShader(it.mShader);
    +               canvas.drawArc(mBounds,
    +                       360 - it.mEndAngle,
    +                       it.mEndAngle - it.mStartAngle,
    +                       true, mPiePaint);
    +           }
    +       }
    +
    +       @Override
    +       protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    +           mBounds = new RectF(0, 0, w, h);
    +       }
    +
    +       RectF mBounds;
    +   }
    +
    + +

    After this code change, {@code PieChart.PieView.onDraw()} is called only when the view is first +shown. During the rest +of the application's lifetime, the pie chart is cached as an image, and redrawn at different +rotation angles by the GPU. +GPU hardware is particularly good at this sort of thing, and the performance difference is +immediately noticeable.

    + +

    There is a tradeoff, though. Caching images as hardware layers consumes video memory, which is a +limited resource. +For this reason, the final version of {@code PieChart.PieView} only sets its layer type to +{@link android.view.View#LAYER_TYPE_HARDWARE} +while the user is actively scrolling. At all other times, it sets its layer type to +{@link android.view.View#LAYER_TYPE_NONE}, which +allows the GPU to stop caching the image.

    + +

    Finally, don't forget to profile your code. Techniques that improve performance on one view +might negatively affect performance on another.

    diff --git a/docs/html/training/design-navigation/ancestral-temporal.jd b/docs/html/training/design-navigation/ancestral-temporal.jd index ab6a64d2925a..33a75b2e213e 100644 --- a/docs/html/training/design-navigation/ancestral-temporal.jd +++ b/docs/html/training/design-navigation/ancestral-temporal.jd @@ -22,7 +22,7 @@ next.link=wireframing.html

    You should also read

    @@ -58,7 +58,7 @@ the Email app from the People (or Contacts) app.

    Applications generally don't have to worry about managing the Back button themselves; -the system handles tasks and +the system handles tasks and the back stack, or the list of previous screens, automatically. The Back button by default simply traverses this list of screens, removing the current screen from the list upon being pressed.

    diff --git a/docs/html/training/design-navigation/wireframing.jd b/docs/html/training/design-navigation/wireframing.jd index 6deceb1b4653..42f892df1f61 100644 --- a/docs/html/training/design-navigation/wireframing.jd +++ b/docs/html/training/design-navigation/wireframing.jd @@ -78,7 +78,7 @@ previous.link=ancestral-temporal.html
  • What's the learning curve? Professional vector illustration tools may have a steep learning curve, while tools designed for wireframing may offer a smaller set of features that are more relevant to the task.
  • -

    Lastly, the XML Layout Editor that comes with the Android Development Tools (ADT) plugin for Eclipse can often be used for prototyping. However, you should be careful to focus more on the high-level layout and less on visual design details at this point.

    +

    Lastly, the XML Layout Editor that comes with the Android Development Tools (ADT) plugin for Eclipse can often be used for prototyping. However, you should be careful to focus more on the high-level layout and less on visual design details at this point.

    Create Digital Wireframes

    @@ -120,6 +120,6 @@ previous.link=ancestral-temporal.html diff --git a/docs/html/training/displaying-bitmaps/index.jd b/docs/html/training/displaying-bitmaps/index.jd index 6755c24495ae..78371ad64fa0 100644 --- a/docs/html/training/displaying-bitmaps/index.jd +++ b/docs/html/training/displaying-bitmaps/index.jd @@ -13,7 +13,7 @@ next.link=load-bitmap.html

    Dependencies and prerequisites

    Try it out

    diff --git a/docs/html/training/displaying-bitmaps/process-bitmap.jd b/docs/html/training/displaying-bitmaps/process-bitmap.jd index c1450b4a8850..d1e346c86ad5 100644 --- a/docs/html/training/displaying-bitmaps/process-bitmap.jd +++ b/docs/html/training/displaying-bitmaps/process-bitmap.jd @@ -21,7 +21,7 @@ previous.link=load-bitmap.html

    You should also read

      -
    • Designing for Responsiveness
    • +
    • Designing for Responsiveness
    • Multithreading for Performance
    • @@ -45,7 +45,7 @@ disk or a network location (or really any source other than memory). The time th load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for +href="{@docRoot}guide/practices/responsiveness.html">Designing for Responsiveness for more information).

      This lesson walks you through processing bitmaps in a background thread using diff --git a/docs/html/training/efficient-downloads/efficient-network-access.jd b/docs/html/training/efficient-downloads/efficient-network-access.jd index 0efad7d2adbc..1d3a8a59c681 100644 --- a/docs/html/training/efficient-downloads/efficient-network-access.jd +++ b/docs/html/training/efficient-downloads/efficient-network-access.jd @@ -142,7 +142,7 @@ The wireless radio needs to become active in order to transmit the termination /

      Use the DDMS Network Traffic Tool to Identify Areas of Concern

      -

      The Android DDMS (Dalvik Debug Monitor Server) includes a Detailed Network Usage tab that makes it possible to track when your application is making network requests. Using this tool, you can monitor how and when your app transfers data and optimize the underlying code appropriately.

      +

      The Android DDMS (Dalvik Debug Monitor Server) includes a Detailed Network Usage tab that makes it possible to track when your application is making network requests. Using this tool, you can monitor how and when your app transfers data and optimize the underlying code appropriately.

      Figure 3 shows a pattern of transferring small amounts of data roughly 15 seconds apart, suggesting that efficiency could be dramatically improved by prefetching each request or bundling the uploads.

      diff --git a/docs/html/training/graphics/opengl/draw.jd b/docs/html/training/graphics/opengl/draw.jd new file mode 100644 index 000000000000..156ff704ac8f --- /dev/null +++ b/docs/html/training/graphics/opengl/draw.jd @@ -0,0 +1,195 @@ +page.title=Drawing Shapes +parent.title=Displaying Graphics with OpenGL ES +parent.link=index.html + +trainingnavtop=true +previous.title=Defining Shapes +previous.link=environment.html +next.title=Applying Projection and Camera Views +next.link=projection.html + +@jd:body + +
      +
      + +

      This lesson teaches you to

      +
        +
      1. Initialize Shapes
      2. +
      3. Draw a Shape
      4. +
      + +

      You should also read

      + + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + +

      After you define shapes to be drawn with OpenGL, you probably want to draw them. Drawing shapes +with the OpenGL ES 2.0 takes a bit more code than you might imagine, because the API provides a +great deal of control over the graphics rendering pipeline.

      + +

      This lesson explains how to draw the shapes you defined in the previous lesson using the OpenGL +ES 2.0 API.

      + + +

      Initialize Shapes

      + +

      Before you do any drawing, you must initialize and load the shapes you plan to draw. Unless the +structure (the original coordinates) of the shapes you use in your program change during the course +of execution, you should initialize them in the {@link +android.opengl.GLSurfaceView.Renderer#onSurfaceCreated onSurfaceCreated()} method of your renderer +for memory and processing efficiency.

      + +
      +public void onSurfaceCreated(GL10 unused, EGLConfig config) {
      +    ...
      +
      +    // initialize a triangle
      +    mTriangle = new Triangle();
      +    // initialize a square
      +    mSquare = new Square();
      +}
      +
      + + +

      Draw a Shape

      + +

      Drawing a defined shape using OpenGL ES 2.0 requires a significant amount of code, because you +must provide a lot of details to the graphics rendering pipeline. Specifically, you must define the +following:

      + +
        +
      • Vertex Shader - OpenGL ES graphics code for rendering the vertices of a shape.
      • +
      • Fragment Shader - OpenGL ES code for rendering the face of a shape with colors or +textures.
      • +
      • Program - An OpenGL ES object that contains the shaders you want to use for drawing +one or more shapes.
      • +
      + +

      You need at least one vertex shader to draw a shape and one fragment shader to color that shape. +These shaders must be complied and then added to an OpenGL ES program, which is then used to draw +the shape. Here is an example of how to define basic shaders you can use to draw a shape:

      + +
      +private final String vertexShaderCode =
      +    "attribute vec4 vPosition;" +
      +    "void main() {" +
      +    "  gl_Position = vPosition;" +
      +    "}";
      +
      +private final String fragmentShaderCode =
      +    "precision mediump float;" +
      +    "uniform vec4 vColor;" +
      +    "void main() {" +
      +    "  gl_FragColor = vColor;" +
      +    "}";
      +
      + +

      Shaders contain OpenGL Shading Language (GLSL) code that must be compiled prior to using it in +the OpenGL ES environment. To compile this code, create a utility method in your renderer class:

      + +
      +public static int loadShader(int type, String shaderCode){
      +
      +    // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
      +    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
      +    int shader = GLES20.glCreateShader(type);
      +
      +    // add the source code to the shader and compile it
      +    GLES20.glShaderSource(shader, shaderCode);
      +    GLES20.glCompileShader(shader);
      +
      +    return shader;
      +}
      +
      + +

      In order to draw your shape, you must compile the shader code, add them to a OpenGL ES program +object and then link the program. Do this in your drawn object’s constructor, so it is only done +once.

      + +

      Note: Compiling OpenGL ES shaders and linking programs is expensive +in terms of CPU cycles and processing time, so you should avoid doing this more than once. If you do +not know the content of your shaders at runtime, you should build your code such that they only +get created once and then cached for later use.

      + +
      +public Triangle() {
      +    ...
      +
      +    int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
      +    int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
      +
      +    mProgram = GLES20.glCreateProgram();             // create empty OpenGL ES Program
      +    GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
      +    GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
      +    GLES20.glLinkProgram(mProgram);                  // creates OpenGL ES program executables
      +}
      +
      + +

      At this point, you are ready to add the actual calls that draw your shape. Drawing shapes with +OpenGL ES requires that you specify several parameters to tell the rendering pipeline what you want +to draw and how to draw it. Since drawing options can vary by shape, it's a good idea to have your +shape classes contain their own drawing logic.

      + +

      Create a {@code draw()} method for drawing the shape. This code sets the position and +color values to the shape’s vertex shader and fragment shader, and then executes the drawing +function.

      + +
      +public void draw() {
      +    // Add program to OpenGL ES environment
      +    GLES20.glUseProgram(mProgram);
      +
      +    // get handle to vertex shader's vPosition member
      +    mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
      +
      +    // Enable a handle to the triangle vertices
      +    GLES20.glEnableVertexAttribArray(mPositionHandle);
      +
      +    // Prepare the triangle coordinate data
      +    GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
      +                                 GLES20.GL_FLOAT, false,
      +                                 vertexStride, vertexBuffer);
      +
      +    // get handle to fragment shader's vColor member
      +    mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
      +
      +    // Set color for drawing the triangle
      +    GLES20.glUniform4fv(mColorHandle, 1, color, 0);
      +
      +    // Draw the triangle
      +    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
      +
      +    // Disable vertex array
      +    GLES20.glDisableVertexAttribArray(mPositionHandle);
      +}
      +
      + +

      Once you have all this code in place, drawing this object just requires a call to the +{@code draw()} method from within your renderer’s {@link +android.opengl.GLSurfaceView.Renderer#onDrawFrame onDrawFrame()} method. When you run the +application, it should look something like this:

      + + +

      +Figure 1. Triangle drawn without a projection or camera view.

      + +

      There are a few problems with this code example. First of all, it is not going to impress your +friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen +orientation of the device. The reason the shape is skewed is due to the fact that the object’s +vertices have not been corrected for the proportions of the screen area where the {@link +android.opengl.GLSurfaceView} is displayed. You can fix that problem using a projection and camera +view in the next lesson.

      + +

      Lastly, the triangle is stationary, which is a bit boring. In the Adding +Motion lesson, you make this shape rotate and make more interesting use of the OpenGL ES +graphics pipeline.

      \ No newline at end of file diff --git a/docs/html/training/graphics/opengl/environment.jd b/docs/html/training/graphics/opengl/environment.jd new file mode 100644 index 000000000000..e1e2c8aca6b6 --- /dev/null +++ b/docs/html/training/graphics/opengl/environment.jd @@ -0,0 +1,223 @@ +page.title=Building an OpenGL ES Environment +parent.title=Displaying Graphics with OpenGL ES +parent.link=index.html + +trainingnavtop=true +previous.title=Displaying Graphics with OpenGL ES +previous.link=index.html +next.title=Defining Shapes +next.link=shapes.html + +@jd:body + +
      +
      + +

      This lesson teaches you to

      +
        +
      1. Declare OpenGL ES Use in the Manifest
      2. +
      3. Create an Activity for OpenGL ES Graphics
      4. +
      5. Build a GLSurfaceView Object
      6. +
      7. Build a Renderer Class
      8. +
      + +

      You should also read

      + + +

      Try it out

      + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + + +

      In order to draw graphics with OpenGL ES in your Android application, you must create a +view container for them. One of the more straight-forward ways to do this is to implement both a +{@link android.opengl.GLSurfaceView} and a {@link android.opengl.GLSurfaceView.Renderer}. A {@link +android.opengl.GLSurfaceView} is a view container for graphics drawn with OpenGL and {@link +android.opengl.GLSurfaceView.Renderer} controls what is drawn within that view. For more information +about these classes, see the OpenGL ES +developer guide.

      + +

      {@link android.opengl.GLSurfaceView} is just one way to incorporate OpenGL ES graphics into your +application. For a full-screen or near-full screen graphics view, it is a reasonable choice. +Developers who want to incorporate OpenGL ES graphics in a small portion of their layouts should +take a look at {@link android.view.TextureView}. For real, do-it-yourself developers, it is also +possible to build up an OpenGL ES view using {@link android.view.SurfaceView}, but this requires +writing quite a bit of additional code.

      + +

      This lesson explains how to complete a minimal implementation of {@link +android.opengl.GLSurfaceView} and {@link android.opengl.GLSurfaceView.Renderer} in a simple +application activity.

      + + +

      Declare OpenGL ES Use in the Manifest

      + +

      In order for your application to use the OpenGL ES 2.0 API, you must add the following +declaration to your manifest:

      + +
      +<uses-feature android:glEsVersion="0x00020000" android:required="true" />
      +
      + +

      If your application uses texture compression, you must also declare which compression formats +you support so that devices that do not support theses formats do not try to run your +application:

      + +
      +<supports-gl-texture android:name="GL_OES_compressed_ETC1_RGB8_texture" />
      +<supports-gl-texture android:name="GL_OES_compressed_paletted_texture" />
      +
      + +

      For more information about texture compression formats, see the +OpenGL developer guide.

      + + +

      Create an Activity for OpenGL ES Graphics

      + +

      Android applications that use OpenGL ES have activities just like any other application that has +a user interface. The main difference from other applications is what you put in the layout for your +activity. While in many applications you might use {@link android.widget.TextView}, {@link +android.widget.Button} and {@link android.widget.ListView}, in an app that uses OpenGL ES, you can +also add a {@link android.opengl.GLSurfaceView}.

      + +

      The following code example shows a minimal implementation of an activity that uses a +{@link android.opengl.GLSurfaceView} as its primary view:

      + +
      +public class OpenGLES20 extends Activity {
      +
      +    private GLSurfaceView mGLView;
      +
      +    @Override
      +    public void onCreate(Bundle savedInstanceState) {
      +        super.onCreate(savedInstanceState);
      +
      +        // Create a GLSurfaceView instance and set it
      +        // as the ContentView for this Activity.
      +        mGLView = new MyGLSurfaceView(this);
      +        setContentView(mGLView);
      +    }
      +}
      +
      + +

      Note: OpenGL ES 2.0 requires Android 2.2 (API Level 8) or higher, +so make sure your Android project targets that API or higher.

      + + +

      Build a GLSurfaceView Object

      + +

      A {@link android.opengl.GLSurfaceView} is a specialized view where you can draw OpenGL ES +graphics. +It does not do much by itself. The actual drawing of objects is controlled in the {@link +android.opengl.GLSurfaceView.Renderer} that you set on this view. In fact, the code for this object +is so thin, you may be tempted to skip extending it and just create an unmodified {@link +android.opengl.GLSurfaceView} instance, but don’t do that. You need to extend this class in +order to capture touch events, which is covered in the Responding to Touch +Events lesson.

      + +

      The essential code for a {@link android.opengl.GLSurfaceView} is minimal, so for a quick +implementation, it is common to +just create an inner class in the activity that uses it:

      + +
      +class MyGLSurfaceView extends GLSurfaceView {
      +
      +    public MyGLSurfaceView(Context context){
      +        super(context);
      +
      +        // Set the Renderer for drawing on the GLSurfaceView
      +        setRenderer(new MyRenderer());
      +    }
      +}
      +
      + +

      When using OpenGL ES 2.0, you must add another call to your {@link android.opengl.GLSurfaceView} +constructor, specifying that you want to use the 2.0 API:

      + +
      +// Create an OpenGL ES 2.0 context
      +setEGLContextClientVersion(2);
      +
      + +

      Note: If you are using the OpenGL ES 2.0 API, make sure you declare +this in your application manifest. For more information, see Declare OpenGL ES +Use +in the Manifest.

      + +

      One other optional addition to your {@link android.opengl.GLSurfaceView} implementation is to set +the render mode to only draw the view when there is a change to your drawing data using the +{@link android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY GLSurfaceView.RENDERMODE_WHEN_DIRTY} +setting:

      + +
      +// Render the view only when there is a change in the drawing data
      +setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
      +
      + +

      This setting prevents the {@link android.opengl.GLSurfaceView} frame from being redrawn until you +call {@link android.opengl.GLSurfaceView#requestRender requestRender()}, which is more +efficient for this sample app.

      + + +

      Build a Renderer Class

      + +

      The implementation of the {@link android.opengl.GLSurfaceView.Renderer} class, or renderer, +within an application that uses OpenGL ES is where things start to get interesting. This class +controls +what gets drawn on the {@link android.opengl.GLSurfaceView} with which it is associated. There are +three methods in a renderer that are called by the Android system in order to figure out what and +how to draw on a {@link android.opengl.GLSurfaceView}:

      + +
        +
      • {@link android.opengl.GLSurfaceView.Renderer#onSurfaceCreated onSurfaceCreated()} - +Called once to set up the view's OpenGL ES environment.
      • +
      • {@link android.opengl.GLSurfaceView.Renderer#onDrawFrame onDrawFrame()} - Called for each +redraw of the view.
      • +
      • {@link android.opengl.GLSurfaceView.Renderer#onSurfaceChanged onSurfaceChanged()} - Called if +the geometry of the view changes, for example when the device's screen orientation changes. +
      • +
      + +

      Here is a very basic implementation of an OpenGL ES renderer, that does nothing more than draw a +gray background in the {@link android.opengl.GLSurfaceView}:

      + +
      +public class MyGL20Renderer implements GLSurfaceView.Renderer {
      +
      +    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
      +        // Set the background frame color
      +        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
      +    }
      +
      +    public void onDrawFrame(GL10 unused) {
      +        // Redraw background color
      +        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
      +    }
      +
      +    public void onSurfaceChanged(GL10 unused, int width, int height) {
      +        GLES20.glViewport(0, 0, width, height);
      +    }
      +}
      +
      + +

      That’s all there is to it! The code examples above create a simple Android application that +displays a gray screen using OpenGL. While this code does not do anything very interesting, by +creating these classes, you have laid the foundation you need to start drawing graphic elements with +OpenGL.

      + +

      Note: You may wonder why these methods have a {@link +javax.microedition.khronos.opengles.GL10} parameter, when you are using the OpengGL ES 2.0 APIs. +These method signatures are simply reused for the 2.0 APIs to keep the Android framework code +simpler.

      + +

      If you are familiar with the OpenGL ES APIs, you should now be able to set up a OpenGL ES +environment in your app and start drawing graphics. However, if you need a bit more help getting +started with OpenGL, head on to the next lessons for a few more hints.

      diff --git a/docs/html/training/graphics/opengl/index.jd b/docs/html/training/graphics/opengl/index.jd new file mode 100644 index 000000000000..23a734acb473 --- /dev/null +++ b/docs/html/training/graphics/opengl/index.jd @@ -0,0 +1,75 @@ +page.title=Displaying Graphics with OpenGL ES +trainingnavtop=true +next.title=Building an OpenGL ES Environment +next.link=environment.html + +@jd:body + +
      +
      + +

      Dependencies and prerequisites

      +
        +
      • Android 2.2 (API Level 8) or higher
      • +
      • Experience building an Android +app
      • +
      + +

      You should also read

      + + +

      Try it out

      + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + +

      The Android framework provides plenty of standard tools for creating attractive, functional +graphical user interfaces. However, if you want more control of what your application draws on +screen, or are venturing into three dimensional graphics, you need to use a different tool. The +OpenGL ES APIs provided by the Android framework offers a set of tools for displaying high-end, +animated graphics that are limited only by your imagination and can also benefit from the +acceleration of graphics processing units (GPUs) provided on many Android devices.

      + +

      This class walks you through the basics of developing applications that use OpenGL, including +setup, drawing objects, moving drawn elements and responding to touch input.

      + +

      The example code in this class uses the OpenGL ES 2.0 APIs, which is the recommended API version +to use with current Android devices. For more information about versions of OpenGL ES, see the OpenGL +developer guide.

      + +

      Note: Be careful not to mix OpenGL ES 1.x API calls with OpenGL +ES 2.0 methods! The two APIs are not interchangeable and trying to use them together only results in +frustration and sadness.

      + + +

      Lessons

      + +
      +
      Building an OpenGL ES Environment
      +
      Learn how to set up an Android application to be able to draw OpenGL graphics.
      + +
      Defining Shapes
      +
      Learn how to define shapes and why you need to know about faces and winding.
      + +
      Drawing Shapes
      +
      Learn how to draw OpenGL shapes in your application.
      + +
      Applying Projection and Camera Views
      +
      Learn how to use projection and camera views to get a new perspective on your drawn +objects.
      + +
      Adding Motion
      +
      Learn how to do basic movement and animation of drawn objects with OpenGL.
      + +
      Responding to Touch Events
      +
      Learn how to do basic interaction with OpenGL graphics.
      +
      diff --git a/docs/html/training/graphics/opengl/motion.jd b/docs/html/training/graphics/opengl/motion.jd new file mode 100644 index 000000000000..688823560e8d --- /dev/null +++ b/docs/html/training/graphics/opengl/motion.jd @@ -0,0 +1,92 @@ +page.title=Adding Motion +parent.title=Displaying Graphics with OpenGL ES +parent.link=index.html + +trainingnavtop=true +previous.title=Applying Projection and Camera Views +previous.link=projection.html +next.title=Responding to Touch Events +next.link=touch.html + +@jd:body + +
      +
      + +

      This lesson teaches you to

      +
        +
      1. Rotate a Shape
      2. +
      3. Enable Continuous Rendering
      4. +
      + +

      You should also read

      + + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + +

      Drawing objects on screen is a pretty basic feature of OpenGL, but you can do this with other +Android graphics framwork classes, including {@link android.graphics.Canvas} and +{@link android.graphics.drawable.Drawable} objects. OpenGL ES provides additional capabilities for +moving and transforming drawn objects in three dimensions or in other unique ways to create +compelling user experiences.

      + +

      In this lesson, you take another step forward into using OpenGL ES by learning how to add motion +to a shape with rotation.

      + + +

      Rotate a Shape

      + +

      Rotating a drawing object with OpenGL ES 2.0 is relatively simple. You create another +transformation matrix (a rotation matrix) and then combine it with your projection and +camera view tranformation matrices:

      + +
      +private float[] mRotationMatrix = new float[16];
      +public void onDrawFrame(GL10 gl) {
      +    ...
      +    // Create a rotation transformation for the triangle
      +    long time = SystemClock.uptimeMillis() % 4000L;
      +    float angle = 0.090f * ((int) time);
      +    Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
      +
      +    // Combine the rotation matrix with the projection and camera view
      +    Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);
      +
      +    // Draw triangle
      +    mTriangle.draw(mMVPMatrix);
      +}
      +
      + +

      If your triangle does not rotate after making these changes, make sure you have commented out the +{@link android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY GLSurfaceView.RENDERMODE_WHEN_DIRTY} +setting, as described in the next section.

      + + +

      Enable Continuous Rendering

      + +

      If you have diligently followed along with the example code in this class to this point, make +sure you comment out the line that sets the render mode only draw when dirty, otherwise OpenGL +rotates the shape only one increment and then waits for a call to {@link +android.opengl.GLSurfaceView#requestRender requestRender()} from the {@link +android.opengl.GLSurfaceView} container:

      + +
      +public MyGLSurfaceView(Context context) {
      +    ...
      +    // Render the view only when there is a change in the drawing data
      +    //setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // comment out for auto-rotation
      +}
      +
      + +

      Unless you have objects changing without any user interaction, it’s usually a good idea have this +flag turned on. Be ready to uncomment this code, because the next lesson makes this call applicable +once again.

      diff --git a/docs/html/training/graphics/opengl/projection.jd b/docs/html/training/graphics/opengl/projection.jd new file mode 100644 index 000000000000..2a91093d8909 --- /dev/null +++ b/docs/html/training/graphics/opengl/projection.jd @@ -0,0 +1,152 @@ +page.title=Applying Projection and Camera Views +parent.title=Displaying Graphics with OpenGL ES +parent.link=index.html + +trainingnavtop=true +previous.title=Drawing Shapes +previous.link=draw.html +next.title=Applying Projection and Camera Views +next.link=projection.html + +@jd:body + +
      +
      + +

      This lesson teaches you to

      +
        +
      1. Define a Projection
      2. +
      3. Define a Camera View
      4. +
      5. Apply Projection and Camera Transformations
      6. +
      + +

      You should also read

      + + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + +

      In the OpenGL ES environment, projection and camera views allow you to display drawn objects in a +way that more closely resembles how you see physical objects with your eyes. This simulation of +physical viewing is done with mathematical transformations of drawn object coordinates:

      + +
        +
      • Projection - This transformation adjusts the coordinates of drawn objects based on +the width and height of the {@link android.opengl.GLSurfaceView} where they are displayed. Without +this calculation, objects drawn by OpenGL ES are skewed by the unequal proportions of the view +window. A projection transformation typically only has to be calculated when the proportions of the +OpenGL view are established or changed in the {@link +android.opengl.GLSurfaceView.Renderer#onSurfaceChanged +onSurfaceChanged()} method of your renderer. For more information about OpenGL ES projections and +coordinate mapping, see Mapping Coordinates for Drawn +Objects.
      • +
      • Camera View - This transformation adjusts the coordinates of drawn objects based on a +virtual camera position. It’s important to note that OpenGL ES does not define an actual camera +object, but instead provides utility methods that simulate a camera by transforming the display of +drawn objects. A camera view transformation might be calculated only once when you establish your +{@link android.opengl.GLSurfaceView}, or might change dynamically based on user actions or your +application’s function.
      • +
      + +

      This lesson describes how to create a projection and camera view and apply it to shapes drawn in +your {@link android.opengl.GLSurfaceView}.

      + + +

      Define a Projection

      + +

      The data for a projection transformation is calculated in the {@link +android.opengl.GLSurfaceView.Renderer#onSurfaceChanged onSurfaceChanged()} +method of your {@link android.opengl.GLSurfaceView.Renderer} class. The following example code +takes the height and width of the {@link android.opengl.GLSurfaceView} and uses it to populate a +projection transformation {@link android.opengl.Matrix} using the {@link +android.opengl.Matrix#frustumM Matrix.frustumM()} method:

      + +
      +@Override
      +public void onSurfaceChanged(GL10 unused, int width, int height) {
      +    GLES20.glViewport(0, 0, width, height);
      +
      +    float ratio = (float) width / height;
      +
      +    // this projection matrix is applied to object coordinates
      +    // in the onDrawFrame() method
      +    Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
      +}
      +
      + +

      This code populates a projection matrix, {@code mProjMatrix} which you can then combine with a +camera view transformation in the {@link android.opengl.GLSurfaceView.Renderer#onDrawFrame +onDrawFrame()} method, which is shown in the next section.

      + +

      Note: Just applying a projection transformation to your +drawing objects typically results in a very empty display. In general, you must also apply a camera +view transformation in order for anything to show up on screen.

      + + +

      Define a Camera View

      + +

      Complete the process of transforming your drawn objects by adding a camera view transformation as +part of the drawing process. In the following example code, the camera view transformation is +calculated using the {@link android.opengl.Matrix#setLookAtM Matrix.setLookAtM()} method and then +combined with the previously calculated projection matrix. The combined transformation matrices +are then passed to the drawn shape.

      + +
      +@Override
      +public void onDrawFrame(GL10 unused) {
      +    ...
      +
      +    // Set the camera position (View matrix)
      +    Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
      +
      +    // Calculate the projection and view transformation
      +    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
      +
      +    // Draw shape
      +    mTriangle.draw(mMVPMatrix);
      +}
      +
      + + +

      Apply Projection and Camera Transformations

      + +

      In order to use the combined projection and camera view transformation matrix shown in the +previews sections, modify the {@code draw()} method of your graphic objects to accept the combined +transformation matrix and apply it to the shape:

      + +
      +public void draw(float[] mvpMatrix) { // pass in the calculated transformation matrix
      +    ...
      +
      +    // get handle to shape's transformation matrix
      +    mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
      +
      +    // Apply the projection and view transformation
      +    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
      +
      +    // Draw the triangle
      +    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
      +    ...
      +}
      +
      + +

      Once you have correctly calulated and applied the projection and camera view transformations, +your graphic objects are drawn in correct proportions and should look like this:

      + + + +

      +Figure 1. Triangle drawn with a projection and camera view applied.

      + + +

      Now that you have an application that displays your shapes in correct proportions, it's time to +add motion to your shapes.

      diff --git a/docs/html/training/graphics/opengl/shapes.jd b/docs/html/training/graphics/opengl/shapes.jd new file mode 100644 index 000000000000..98381cc6de4b --- /dev/null +++ b/docs/html/training/graphics/opengl/shapes.jd @@ -0,0 +1,153 @@ +page.title=Defining Shapes +parent.title=Displaying Graphics with OpenGL ES +parent.link=index.html + +trainingnavtop=true +previous.title=Building an OpenGL ES Environment +previous.link=environment.html +next.title=Drawing Shapes +next.link=draw.html + +@jd:body + +
      +
      + +

      This lesson teaches you to

      +
        +
      1. Define a Triangle
      2. +
      3. Define a Square
      4. +
      + +

      You should also read

      + + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + +

      Being able to define shapes to be drawn in the context of an OpenGL ES view is the first step in +creating your high-end graphics masterpiece. Drawing with OpenGL ES can be a little tricky without +knowing a few basic things about how OpenGL ES expects you to define graphic objects.

      + +

      This lesson explains the OpenGL ES coordinate system relative to an Android device screen, the +basics of defining a shape, shape faces, as well as defining a triangle and a square.

      + + +

      Define a Triangle

      + +

      OpenGL ES allows you to define drawn objects using coordinates in three-dimensional space. So, +before you can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do +this is to define a vertex array of floating point numbers for the coordinates. For maximum +efficiency, you write these coordinates into a {@link java.nio.ByteBuffer}, that is passed into the +OpenGL ES graphics pipeline for processing.

      + +
      +class Triangle {
      +
      +    private FloatBuffer vertexBuffer;
      +
      +    // number of coordinates per vertex in this array
      +    static final int COORDS_PER_VERTEX = 3;
      +    static float triangleCoords[] = { // in counterclockwise order:
      +         0.0f,  0.622008459f, 0.0f,   // top
      +        -0.5f, -0.311004243f, 0.0f,   // bottom left
      +         0.5f, -0.311004243f, 0.0f    // bottom right
      +    };
      +
      +    // Set color with red, green, blue and alpha (opacity) values
      +    float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
      +
      +    public Triangle() {
      +        // initialize vertex byte buffer for shape coordinates
      +        ByteBuffer bb = ByteBuffer.allocateDirect(
      +                // (number of coordinate values * 4 bytes per float)
      +                triangleCoords.length * 4);
      +        // use the device hardware's native byte order
      +        bb.order(ByteOrder.nativeOrder());
      +
      +        // create a floating point buffer from the ByteBuffer
      +        vertexBuffer = bb.asFloatBuffer();
      +        // add the coordinates to the FloatBuffer
      +        vertexBuffer.put(triangleCoords);
      +        // set the buffer to read the first coordinate
      +        vertexBuffer.position(0);
      +    }
      +}
      +
      + +

      By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of +the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top right corner of the frame and +[-1,-1,0] is bottom left corner of the frame. For an illustration of this coordinate system, see the +OpenGL ES developer +guide.

      + +

      Note that the coordinates of this shape are defined in a counterclockwise order. The drawing +order is important because it defines which side is the front face of the shape, which you typically +want to have drawn, and the back face, which you can choose to not draw using the OpenGL ES cull +face feature. For more information about faces and culling, see the OpenGL ES developer guide.

      + + +

      Define a Square

      + +

      Defining triangles is pretty easy in OpenGL, but what if you want to get a just a little more +complex? Say, a square? There are a number of ways to do this, but a typical path to drawing such a +shape in OpenGL ES is to use two triangles drawn together:

      + + +

      + Figure 1. Drawing a square using two triangles.

      + +

      Again, you should define the vertices in a counterclockwise order for both triangles that +represent this shape, and put the values in a {@link java.nio.ByteBuffer}. In order to avoid +defining the two coordinates shared by each triangle twice, use a drawing list to tell the +OpenGL ES graphics pipeline how to draw these vertices. Here’s the code for this shape:

      + +
      +class Square {
      +
      +    private FloatBuffer vertexBuffer;
      +    private ShortBuffer drawListBuffer;
      +
      +    // number of coordinates per vertex in this array
      +    static final int COORDS_PER_VERTEX = 3;
      +    static float squareCoords[] = { -0.5f,  0.5f, 0.0f,   // top left
      +                                    -0.5f, -0.5f, 0.0f,   // bottom left
      +                                     0.5f, -0.5f, 0.0f,   // bottom right
      +                                     0.5f,  0.5f, 0.0f }; // top right
      +
      +    private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
      +
      +    public Square() {
      +        // initialize vertex byte buffer for shape coordinates
      +        ByteBuffer bb = ByteBuffer.allocateDirect(
      +        // (# of coordinate values * 4 bytes per float)
      +                squareCoords.length * 4);
      +        bb.order(ByteOrder.nativeOrder());
      +        vertexBuffer = bb.asFloatBuffer();
      +        vertexBuffer.put(squareCoords);
      +        vertexBuffer.position(0);
      +
      +        // initialize byte buffer for the draw list
      +        ByteBuffer dlb = ByteBuffer.allocateDirect(
      +        // (# of coordinate values * 2 bytes per short)
      +                drawOrder.length * 2);
      +        dlb.order(ByteOrder.nativeOrder());
      +        drawListBuffer = dlb.asShortBuffer();
      +        drawListBuffer.put(drawOrder);
      +        drawListBuffer.position(0);
      +    }
      +}
      +
      + +

      This example gives you a peek at what it takes to create more complex shapes with OpenGL. In +general, you use collections of triangles to draw objects. In the next lesson, you learn how to draw +these shapes on screen.

      diff --git a/docs/html/training/graphics/opengl/touch.jd b/docs/html/training/graphics/opengl/touch.jd new file mode 100644 index 000000000000..c058a5963ee3 --- /dev/null +++ b/docs/html/training/graphics/opengl/touch.jd @@ -0,0 +1,145 @@ +page.title= Responding to Touch Events +parent.title=Displaying Graphics with OpenGL ES +parent.link=index.html + +trainingnavtop=true +previous.title=Adding Motion +previous.link=motion.html + +@jd:body + +
      +
      + +

      This lesson teaches you to

      +
        +
      1. Setup a Touch Listener
      2. +
      3. Expose the Rotation Angle
      4. +
      5. Apply Rotation
      6. +
      + +

      You should also read

      + + +
      + Download the sample +

      OpenGLES.zip

      +
      + +
      +
      + +

      Making objects move according to a preset program like the rotating triangle is useful for +getting some attention, but what if you want to have users interact with your OpenGL ES graphics? +The key to making your OpenGL ES application touch interactive is expanding your implementation of +{@link android.opengl.GLSurfaceView} to override the {@link +android.opengl.GLSurfaceView#onTouchEvent onTouchEvent()} to listen for touch events.

      + +

      This lesson shows you how to listen for touch events to let users rotate an OpenGL ES object.

      + + +

      Setup a Touch Listener

      + +

      In order to make your OpenGL ES application respond to touch events, you must implement the +{@link android.opengl.GLSurfaceView#onTouchEvent onTouchEvent()} method in your +{@link android.opengl.GLSurfaceView} class. The example implementation below shows how to listen for +{@link android.view.MotionEvent#ACTION_MOVE MotionEvent.ACTION_MOVE} events and translate them to +an angle of rotation for a shape.

      + +
      +@Override
      +public boolean onTouchEvent(MotionEvent e) {
      +    // MotionEvent reports input details from the touch screen
      +    // and other input controls. In this case, you are only
      +    // interested in events where the touch position changed.
      +
      +    float x = e.getX();
      +    float y = e.getY();
      +
      +    switch (e.getAction()) {
      +        case MotionEvent.ACTION_MOVE:
      +
      +            float dx = x - mPreviousX;
      +            float dy = y - mPreviousY;
      +
      +            // reverse direction of rotation above the mid-line
      +            if (y > getHeight() / 2) {
      +              dx = dx * -1 ;
      +            }
      +
      +            // reverse direction of rotation to left of the mid-line
      +            if (x < getWidth() / 2) {
      +              dy = dy * -1 ;
      +            }
      +
      +            mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;  // = 180.0f / 320
      +            requestRender();
      +    }
      +
      +    mPreviousX = x;
      +    mPreviousY = y;
      +    return true;
      +}
      +
      + +

      Notice that after calculating the rotation angle, this method calls {@link +android.opengl.GLSurfaceView#requestRender requestRender()} to tell the +renderer that it is time to render the frame. This approach is the most efficient in this example +because the frame does not need to be redrawn unless there is a change in the rotation. However, it +does not have any impact on efficiency unless you also request that the renderer only redraw when +the data changes using the {@link android.opengl.GLSurfaceView#setRenderMode setRenderMode()} +method, so make sure this line is uncommented in the renderer:

      + +
      +public MyGLSurfaceView(Context context) {
      +    ...
      +    // Render the view only when there is a change in the drawing data
      +    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
      +}
      +
      + +

      Expose the Rotation Angle

      + +

      The example code above requires that you expose the rotation angle through your renderer by +adding a public member. Since the renderer code is running on a separate thread from the main user +interface thread of your application, you must declare this public variable as {@code volatile}. +Here is the code to do that:

      + +
      +public class MyGLRenderer implements GLSurfaceView.Renderer {
      +    ...
      +    public volatile float mAngle;
      +
      + + +

      Apply Rotation

      + +

      To apply the rotation generated by touch input, comment out the code that generates an angle and +add {@code mAngle}, which contains the touch input generated angle:

      + +
      +public void onDrawFrame(GL10 gl) {
      +    ...
      +    // Create a rotation for the triangle
      +    // long time = SystemClock.uptimeMillis() % 4000L;
      +    // float angle = 0.090f * ((int) time);
      +    Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
      +
      +    // Combine the rotation matrix with the projection and camera view
      +    Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0);
      +
      +    // Draw triangle
      +    mTriangle.draw(mMVPMatrix);
      +}
      +
      + +

      When you have completed the steps described above, run the program and drag your finger over the +screen to rotate the triangle:

      + + +

      +Figure 1. Triangle being rotated with touch input (circle shows touch +location).

      diff --git a/docs/html/training/id-auth/index.jd b/docs/html/training/id-auth/index.jd index 361e6cfa0da0..140545c74e92 100644 --- a/docs/html/training/id-auth/index.jd +++ b/docs/html/training/id-auth/index.jd @@ -14,7 +14,7 @@ next.link=identify.html

      Requirements and prerequisites

      diff --git a/docs/html/training/implementing-navigation/ancestral.jd b/docs/html/training/implementing-navigation/ancestral.jd index 495b45dc71dd..ac35e642ed17 100644 --- a/docs/html/training/implementing-navigation/ancestral.jd +++ b/docs/html/training/implementing-navigation/ancestral.jd @@ -22,7 +22,7 @@ next.link=temporal.html

      You should also read

      @@ -87,7 +87,7 @@ public boolean onOptionsItemSelected(MenuItem item) {

      When the current activity belongs to a task from a different application—for example if it was reached via an intent from another application—pressing Up should create a new task for the application with a synthesized back stack. This approach is described in Android Design: Navigation and the {@link android.support.v4.app.TaskStackBuilder} class reference.

      -

      The {@link android.support.v4.app.NavUtils} and {@link android.support.v4.app.TaskStackBuilder} classes in the Android Support Package provide helpers for implementing this behavior correctly. An example usage of these two helper classes is below:

      +

      The {@link android.support.v4.app.NavUtils} and {@link android.support.v4.app.TaskStackBuilder} classes in the Android Support Package provide helpers for implementing this behavior correctly. An example usage of these two helper classes is below:

       {@literal @}Override
      diff --git a/docs/html/training/implementing-navigation/index.jd b/docs/html/training/implementing-navigation/index.jd
      index da61c8162025..ebb4995ef91a 100644
      --- a/docs/html/training/implementing-navigation/index.jd
      +++ b/docs/html/training/implementing-navigation/index.jd
      @@ -15,7 +15,7 @@ next.link=lateral.html
       
       
      @@ -23,7 +23,7 @@ next.link=lateral.html
       
       
       
      diff --git a/docs/html/training/implementing-navigation/lateral.jd b/docs/html/training/implementing-navigation/lateral.jd
      index d9ba5c9cb9bd..76acf03b051f 100644
      --- a/docs/html/training/implementing-navigation/lateral.jd
      +++ b/docs/html/training/implementing-navigation/lateral.jd
      @@ -119,7 +119,7 @@ public void onCreate(Bundle savedInstanceState) {
       
       

      Implement Horizontal Paging (Swipe Views)

      -

      Horizontal paging, or swipe views, allow users to swipe horizontally on the current screen to navigate to adjacent screens. This pattern can be implemented using the {@link android.support.v4.view.ViewPager} widget, currently available as part of the Android Support Package. For navigating between sibling screens representing a fixed number of sections, it's best to provide the {@link android.support.v4.view.ViewPager} with a {@link android.support.v4.app.FragmentPagerAdapter}. For horizontal paging across collections of objects, it's best to use a {@link android.support.v4.app.FragmentStatePagerAdapter}, which destroys fragments as the user navigates to other pages, minimizing memory usage.

      +

      Horizontal paging, or swipe views, allow users to swipe horizontally on the current screen to navigate to adjacent screens. This pattern can be implemented using the {@link android.support.v4.view.ViewPager} widget, currently available as part of the Android Support Package. For navigating between sibling screens representing a fixed number of sections, it's best to provide the {@link android.support.v4.view.ViewPager} with a {@link android.support.v4.app.FragmentPagerAdapter}. For horizontal paging across collections of objects, it's best to use a {@link android.support.v4.app.FragmentStatePagerAdapter}, which destroys fragments as the user navigates to other pages, minimizing memory usage.

      Below is an example of using a {@link android.support.v4.view.ViewPager} to swipe across a collection of objects.

      diff --git a/docs/html/training/implementing-navigation/temporal.jd b/docs/html/training/implementing-navigation/temporal.jd index f36991fb0ebd..1c41732fd530 100644 --- a/docs/html/training/implementing-navigation/temporal.jd +++ b/docs/html/training/implementing-navigation/temporal.jd @@ -22,7 +22,7 @@ next.link=descendant.html

      You should also read

      @@ -32,7 +32,7 @@ next.link=descendant.html

      Temporal navigation is navigation to previously visited screens. Users can visit previous screens by pressing the device Back button. This user interface pattern is described further in Providing Ancestral and Temporal Navigation in Designing Effective Navigation and in Android Design: Navigation.

      -

      Android handles basic Back navigation for you (see Tasks and Back Stack for details on this behavior). This lesson discusses a number of cases where applications should provide specialized logic for the Back button.

      +

      Android handles basic Back navigation for you (see Tasks and Back Stack for details on this behavior). This lesson discusses a number of cases where applications should provide specialized logic for the Back button.

      Implement Back Navigation with Fragments

      diff --git a/docs/html/training/improving-layouts/optimizing-layout.jd b/docs/html/training/improving-layouts/optimizing-layout.jd index 0eaf199b132e..520ce5677ae3 100644 --- a/docs/html/training/improving-layouts/optimizing-layout.jd +++ b/docs/html/training/improving-layouts/optimizing-layout.jd @@ -44,8 +44,8 @@ is inflated repeatedly, such as when used in a {@link android.widget.ListView} o android.widget.GridView}.

      In this lesson you'll learn to use Hierarchy Viewer and Layoutopt to examine and optimize your +href="{@docRoot}tools/help/hierarchy-viewer.html">Hierarchy Viewer and Layoutopt to examine and optimize your layout.

      @@ -53,7 +53,7 @@ layout.

      Inspect Your Layout

      The Android SDK tools include a tool called Hierarchy Viewer that allows +href="{@docRoot}tools/help/hierarchy-viewer.html">Hierarchy Viewer that allows you to analyze your layout while your application is running. Using this tool helps you discover bottlenecks in the layout performance.

      diff --git a/docs/html/training/index.jd b/docs/html/training/index.jd index 8bf32bbb5d48..3c67af9dba2c 100644 --- a/docs/html/training/index.jd +++ b/docs/html/training/index.jd @@ -1,18 +1,14 @@ -page.title=Orientation to Android Training +page.title=Android Training page.metaDescription=Android Training provides a collection of classes that aim to help you build great apps for Android. Each class explains the steps required to solve a problem or implement a feature using code snippets and sample code for you to use in your apps. @jd:body -
      - -
      -

      Welcome to Android Training. Here you'll find a collection of classes that aim to help you build great apps for Android, using best practices in a variety of framework topics.

      Each class explains the steps required to solve a problem or implement a feature using code snippets and sample code for you to use in your apps.

      -

      What you see now is just the beginning. We plan to add many more classes, expand and refine -existing classes, and build Training Courses that help you enhance your apps using -objective-oriented collections of classes.

      +

      This first section is focused on teaching you the bare essentials. If you're a new developer +on Android, you should walk through each of these classes, beginning with +Building Your First App.

      diff --git a/docs/html/training/managing-audio/index.jd b/docs/html/training/managing-audio/index.jd index 3aa2d8809e88..0f7bbfdd0d8e 100644 --- a/docs/html/training/managing-audio/index.jd +++ b/docs/html/training/managing-audio/index.jd @@ -19,7 +19,7 @@ Playback

      You should also read

    diff --git a/docs/html/training/monitoring-device-state/battery-monitoring.jd b/docs/html/training/monitoring-device-state/battery-monitoring.jd index 6e25df82356e..c963a18624fc 100644 --- a/docs/html/training/monitoring-device-state/battery-monitoring.jd +++ b/docs/html/training/monitoring-device-state/battery-monitoring.jd @@ -21,7 +21,7 @@ next.link=docking-monitoring.html

    You should also read

    diff --git a/docs/html/training/monitoring-device-state/connectivity-monitoring.jd b/docs/html/training/monitoring-device-state/connectivity-monitoring.jd index 98ba63cc6b6c..11a05e18f8c3 100644 --- a/docs/html/training/monitoring-device-state/connectivity-monitoring.jd +++ b/docs/html/training/monitoring-device-state/connectivity-monitoring.jd @@ -24,7 +24,7 @@ next.link=manifest-receivers.html

    You should also read

    diff --git a/docs/html/training/monitoring-device-state/docking-monitoring.jd b/docs/html/training/monitoring-device-state/docking-monitoring.jd index 82d655e6d0ef..3787a554ce04 100644 --- a/docs/html/training/monitoring-device-state/docking-monitoring.jd +++ b/docs/html/training/monitoring-device-state/docking-monitoring.jd @@ -23,7 +23,7 @@ next.link=connectivity-monitoring.html

    You should also read

    diff --git a/docs/html/training/monitoring-device-state/index.jd b/docs/html/training/monitoring-device-state/index.jd index 61f7176c3f21..585b669ac7bf 100644 --- a/docs/html/training/monitoring-device-state/index.jd +++ b/docs/html/training/monitoring-device-state/index.jd @@ -13,12 +13,12 @@ next.link=battery-monitoring.html

    Dependencies and prerequisites

    You should also read

    diff --git a/docs/html/training/monitoring-device-state/manifest-receivers.jd b/docs/html/training/monitoring-device-state/manifest-receivers.jd index 0b79ce6f36ce..d4aeed353a87 100644 --- a/docs/html/training/monitoring-device-state/manifest-receivers.jd +++ b/docs/html/training/monitoring-device-state/manifest-receivers.jd @@ -21,7 +21,7 @@ Efficiency

    You should also read

    diff --git a/docs/html/training/multiple-apks/api.jd b/docs/html/training/multiple-apks/api.jd index 3492245cec19..1a2593ae29c0 100644 --- a/docs/html/training/multiple-apks/api.jd +++ b/docs/html/training/multiple-apks/api.jd @@ -33,7 +33,7 @@ next.link=screensize.html

    You should also read